I have the form working with a small update to our common pear library.
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * A framework for authentication and authorization in PHP applications
- *
- * LiveUser_Admin is meant to be used with the LiveUser package.
- * It is composed of all the classes necessary to administrate
- * data used by LiveUser.
- *
- * You'll be able to add/edit/delete/get things like:
- * * Rights
- * * Users
- * * Groups
- * * Areas
- * * Applications
- * * Subgroups
- * * ImpliedRights
- *
- * And all other entities within LiveUser.
- *
- * At the moment we support the following storage containers:
- * * DB
- * * MDB
- * * MDB2
- *
- * But it takes no time to write up your own storage container,
- * so if you like to use native mysql functions straight, then it's possible
- * to do so in under a hour!
- *
- * PHP version 4 and 5
- *
- * LICENSE: This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library 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
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
- * MA 02111-1307 USA
- *
- *
- * @category authentication
- * @package LiveUser_Admin
- * @author Markus Wolff <wolff@21st.de>
- * @author Helgi Þormar Þorbjörnsson <dufuz@php.net>
- * @author Lukas Smith <smith@pooteeweet.org>
- * @author Arnaud Limbourg <arnaud@php.net>
- * @author Christian Dickmann <dickmann@php.net>
- * @author Matt Scifo <mscifo@php.net>
- * @author Bjoern Kraus <krausbn@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version CVS: $Id: Admin.php,v 1.1.1.1 2008/04/28 15:20:46 jamie Exp $
- * @link http://pear.php.net/LiveUser_Admin
- */
-
-require_once 'LiveUser.php';
-require_once 'LiveUser/Admin/Storage.php';
-
-/**#@+
- * Error related constants definition
- *
- * @var int
- */
-define('LIVEUSER_ADMIN_ERROR', -1);
-define('LIVEUSER_ADMIN_ERROR_FILTER', -2);
-define('LIVEUSER_ADMIN_ERROR_DATA', -3);
-define('LIVEUSER_ADMIN_ERROR_QUERY_BUILDER', -4);
-define('LIVEUSER_ADMIN_ERROR_ALREADY_ASSIGNED', -5);
-define('LIVEUSER_ADMIN_ERROR_NOT_SUPPORTED', -6);
-/**#@-*/
-
-/**
- * A unified admin class
- *
- * Simple usage:
- *
- * <code>
- * $admin = LiveUser_Admin::factory($conf);
- * $filters = array(
- * 'perm_user_id' => '3'
- * );
- * $found = $admin->getUsers($filters);
- *
- * if ($found) {
- * var_dump($admin->perm->getRights());
- * }
- * </code>
- *
- * @see LiveUser::factory()
- *
- * @category authentication
- * @package LiveUser_Admin
- * @author Lukas Smith <smith@pooteeweet.org>
- * @author Arnaud Limbourg <arnaud@php.net>
- * @author Helgi Þormar Þorbjörnsson <dufuz@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version Release: @package_version@
- * @link http://pear.php.net/LiveUser_Admin
- */
-class LiveUser_Admin
-{
- /**
- * Name of the current selected auth container
- *
- * @var string
- * @access public
- */
- var $authContainerName;
-
- /**
- * Array containing the auth objects.
- *
- * @var array
- * @access private
- */
- var $_authContainers = array();
-
- /**
- * Admin perm object
- *
- * @var LiveUser_Admin_Perm_Simple
- * @access public
- */
- var $perm = null;
-
- /**
- * Auth admin object
- *
- * @var LiveUser_Admin_Auth_Common
- * @access public
- */
- var $auth = null;
-
- /**
- * Configuration array
- *
- * @var array
- * @access private
- */
- var $_conf = null;
-
- /**
- * Error codes to message mapping array
- *
- * @var array
- * @access private
- */
- var $_errorMessages = array(
- LIVEUSER_ADMIN_ERROR => 'An error occurred %msg%',
- LIVEUSER_ADMIN_ERROR_FILTER => 'There\'s something obscure with the filter array, key %key%',
- LIVEUSER_ADMIN_ERROR_DATA => 'There\'s something obscure with the data array, key %key%',
- LIVEUSER_ADMIN_ERROR_QUERY_BUILDER => 'Couldn\'t create the query, reason: %reason%',
- LIVEUSER_ADMIN_ERROR_ALREADY_ASSIGNED => 'That given %field1% has already been assigned to %field2%',
- LIVEUSER_ADMIN_ERROR_NOT_SUPPORTED => 'This method is not supported'
- );
-
- /**
- * PEAR::Log object used for error logging by ErrorStack
- *
- * @var Log
- * @access public
- */
- var $log = null;
-
- /**
- *
- * @param bool|log boolean value to denote if the debug mode should be
- enabled, or instance of a PEAR_ErrorStack compatible Log object
- * @return LiveUser_Admin
- *
- * @access public
- * @see init
- */
- function LiveUser_Admin(&$debug)
- {
- $this->stack = &PEAR_ErrorStack::singleton('LiveUser_Admin');
-
- if ($debug) {
- $log =& LiveUser::PEARLogFactory($debug);
- if ($log) {
- $this->log =& $log;
- $this->stack->setLogger($this->log);
- }
- }
-
- $this->stack->setErrorMessageTemplate($this->_errorMessages);
- }
-
- /**
- *
- * @param array configuration array
- * @return LiveUser_Admin|bool
- *
- * @access public
- * @see init
- */
- function &factory(&$conf)
- {
- $debug = false;
- if (array_key_exists('debug', $conf)) {
- $debug =& $conf['debug'];
- }
-
- $obj = &new LiveUser_Admin($debug);
-
- if (is_array($conf)) {
- $obj->_conf =& $conf;
- }
-
- return $obj;
- }
-
- /**
- *
- * @param array configuration array
- * @return LiveUser_Admin|bool
- *
- * @access public
- * @see factory
- */
- function &singleton(&$conf)
- {
- static $instance;
-
- if (!isset($instance)) {
- if (!$conf) {
- return false;
- }
- $obj = &LiveUser_Admin::factory($conf);
- $instance =& $obj;
- }
-
- return $instance;
- }
-
- /**
- * Sets the current auth container to the one with the given auth container name
- *
- * Upon success it will return the auth instance. You can then
- * access the auth backend container by using the
- * auth property of this class or the auth object directly
- *
- * e.g.: $admin->auth->addUser(); or $auth->addUser();
- *
- * @param string auth container name
- * @return LiveUser_Admin_Auth_Common|bool auth instance upon success, false otherwise
- *
- * @access public
- */
- function &setAdminAuthContainer($authName)
- {
- if (!array_key_exists($authName, $this->_authContainers)
- || !is_object($this->_authContainers[$authName])
- ) {
- if (!isset($this->_conf['authContainers'][$authName])) {
- $this->stack->push(LIVEUSER_ADMIN_ERROR, 'exception',
- array('msg' => 'Could not create auth container instance'));
- $result = false;
- return $result;
- }
- $auth = &LiveUser::authFactory(
- $this->_conf['authContainers'][$authName],
- $authName,
- 'LiveUser_Admin_'
- );
- if ($auth === false) {
- $this->stack->push(LIVEUSER_ADMIN_ERROR, 'exception',
- array('msg' => 'Could not instanciate auth container: '.$authName));
- return $auth;
- }
- $this->_authContainers[$authName] = &$auth;
- }
- $this->authContainerName = $authName;
- $this->auth = &$this->_authContainers[$authName];
- return $this->auth;
- }
-
- /**
- * Sets the perm container
- *
- * Upon success it will return a perm instance. You can then
- * access the perm backend container by using the
- * perm properties of this class or the perm object directly.
- *
- * e.g.: $admin->perm->addUser(); or $perm->addUser();
- *
- * @return LiveUser_Admin_Perm_Simple|bool auth instance upon success, false otherwise
- *
- * @access public
- */
- function &setAdminPermContainer()
- {
- if (!array_key_exists('permContainer', $this->_conf)) {
- $this->stack->push(LIVEUSER_ADMIN_ERROR, 'exception',
- array('msg' => 'Could not create perm container instance'));
- $result = false;
- return $result;
- }
-
- $perm = &LiveUser::permFactory($this->_conf['permContainer'], 'LiveUser_Admin_');
- if ($perm === false) {
- $this->stack->push(LIVEUSER_ADMIN_ERROR, 'exception',
- array('msg' => 'Could not instanciate perm container of type: '.$this->_conf['permContainer']['type']));
- return $perm;
- }
- $this->perm = &$perm;
-
- return $this->perm;
- }
-
- /**
- * Setup backend container.
- *
- * Upon success it will return true. You can then
- * access the backend container by using the auth
- * and perm properties of this class.
- *
- * e.g.: $admin->perm->getUsers();
- *
- * @param int user auth id
- * @param string auth container name
- * @return bool true upon success, false otherwise
- *
- * @access public
- */
- function init($authUserId = null, $authName = null)
- {
- if (!is_array($this->_conf)) {
- $this->stack->push(LIVEUSER_ADMIN_ERROR, 'exception',
- array('msg' => 'Missing configuration array'));
- return false;
- }
-
- if (is_null($authName)) {
- if (is_null($authUserId)) {
- reset($this->_conf['authContainers']);
- $authName = key($this->_conf['authContainers']);
- } else {
- foreach ($this->_conf['authContainers'] as $key => $value) {
- if (!isset($this->_authContainers[$key])
- || !is_object($this->_authContainers[$key])
- ) {
- $auth = &LiveUser::authFactory($value, $key, 'LiveUser_Admin_');
- if ($auth === false) {
- $this->stack->push(LIVEUSER_ADMIN_ERROR, 'exception',
- array('msg' => 'Could not instanciate auth container: '.$key));
- return $auth;
- }
- $this->_authContainers[$key] =& $auth;
- }
-
- if (!is_null($authUserId)) {
- $match = $this->_authContainers[$key]->getUsers(
- array('filters' => array('auth_user_id' => $authUserId))
- );
- if (is_array($match) && count($match) > 0) {
- $authName = $key;
- break;
- }
- }
- }
- }
- if (!isset($authName)) {
- $this->stack->push(LIVEUSER_ADMIN_ERROR, 'exception',
- array('msg' => 'Could not determine what auth container to use'));
- return false;
- }
- }
-
- if (!$this->setAdminAuthContainer($authName)) {
- return false;
- }
-
- if (!isset($this->perm) || !is_object($this->perm)) {
- if (!$this->setAdminPermContainer()) {
- return false;
- }
- }
-
- return true;
- }
-
- /**
- * Add a user to both containers.
- *
- * @param array auth user data and perm type
- * @return int|bool perm user id or false
- *
- * @access public
- */
- function addUser($data)
- {
- if (!is_object($this->auth) || !is_object($this->perm)) {
- $this->stack->push(LIVEUSER_ADMIN_ERROR, 'exception',
- array('msg' => 'Perm and/or Auth container not set.'));
- return false;
- }
-
- if (array_key_exists('perm_type', $data)) {
- $type = $data['perm_type'];
- unset($data['perm_type']);
- } else {
- $type = LIVEUSER_USER_TYPE_ID;
- }
-
- $authUserId = $this->auth->addUser($data);
- if (!$authUserId) {
- return false;
- }
-
- $data = array(
- 'auth_user_id' => $authUserId,
- 'auth_container_name' => $this->authContainerName,
- 'perm_type' => $type
- );
- return $this->perm->addUser($data);
- }
-
- /**
- * Changes user data for both containers.
- *
- * @param array auth user data and perm type
- * @param int permission user id
- * @return int|bool affected rows on success or false otherwise
- *
- * @access public
- */
- function updateUser($data, $permUserId)
- {
- if (!is_object($this->auth) || !is_object($this->perm)) {
- $this->stack->push(LIVEUSER_ADMIN_ERROR, 'exception',
- array('msg' => 'Perm and/or Auth container not set.'));
- return false;
- }
-
- $permData = $this->perm->getUsers(
- array(
- 'fields' => array('auth_user_id', 'auth_container_name'),
- 'filters' => array('perm_user_id' => $permUserId),
- 'select' => 'row',
- )
- );
-
- if (!$permData) {
- $this->stack->push(LIVEUSER_ADMIN_ERROR, 'exception',
- array('msg' => 'Could not find user in the permission backend'));
- return false;
- }
-
- $updateData = array();
- if (array_key_exists('perm_type', $data)) {
- $updateData['perm_type'] = $data['perm_type'];
- unset($data['perm_type']);
- }
-
- $this->setAdminAuthContainer($permData['auth_container_name']);
- $filters = array('auth_user_id' => $permData['auth_user_id']);
- $result = $this->auth->updateUser($data, $filters);
-
- if ($result === false) {
- return false;
- }
-
- if (array_key_exists('auth_user_id', $data)
- && $permData['auth_user_id'] != $data['auth_user_id']
- ) {
- $updateData['auth_user_id'] = $data['auth_user_id'];
- }
- if (empty($updateData)) {
- return $result;
- }
-
- $filters = array('perm_user_id' => $permUserId);
- return $this->perm->updateUser($updateData, $filters);
- }
-
- /**
- * Removes user from both Perm and Auth containers
- *
- * @param int Perm ID
- * @return int|bool affected rows on success or false otherwise
- *
- * @access public
- */
- function removeUser($permUserId)
- {
- if (!is_object($this->auth) || !is_object($this->perm)) {
- $this->stack->push(LIVEUSER_ADMIN_ERROR, 'exception',
- array('msg' => 'Perm and/or Auth container not set.'));
- return false;
- }
-
- $permData = $this->perm->getUsers(
- array(
- 'fields' => array('auth_user_id', 'auth_container_name'),
- 'filters' => array('perm_user_id' => $permUserId),
- 'select' => 'row',
- )
- );
-
- if (!$permData) {
- $this->stack->push(LIVEUSER_ADMIN_ERROR, 'exception',
- array('msg' => 'Could not find user in the permission backend'));
- return false;
- }
-
- $filters = array('perm_user_id' => $permUserId);
- $result = $this->perm->removeUser($filters);
-
- if ($result === false) {
- return false;
- }
-
- $this->setAdminAuthContainer($permData['auth_container_name']);
- $filters = array('auth_user_id' => $permData['auth_user_id']);
- return $this->auth->removeUser($filters);
- }
-
- /**
- * Finds and gets full userinfo by filtering inside the given container
- * Note that this method is not particularily efficient, as it fetches
- * the data in the primary container in a single call, but requires one call
- * to the secondary container for every user returned from the primary container
- *
- * @param array params (as for getUsers()
- * with an additional optional key 'container' 'perm' (default) or
- 'auth' to determine the primary and secondary container.
- data is first fetched from the primary container and then
- combined with data from the secondary container if available
- * @return array|bool array with userinfo if found on success or false otherwise
- *
- * @access public
- */
- function getUsers($params = array())
- {
- $params = LiveUser_Admin_Storage::setSelectDefaultParams($params);
-
- if ($params['select'] != 'row' && $params['select'] != 'all') {
- $this->stack->push(LIVEUSER_ADMIN_ERROR, 'exception',
- array('msg' => 'Select must be "row" or "all"'));
- return false;
- }
-
- if (array_key_exists('container', $params)
- && $params['container'] == 'auth'
- ) {
- return $this->_getUsersByAuth($params);
- }
- return $this->_getUsersByPerm($params);
- }
-
- /**
- * Finds and gets full userinfo by filtering inside the perm container
- *
- * @param array perm params (as for getUsers() from the perm container
- * @return array|bool Array with userinfo if found on success or false otherwise
- *
- * @access private
- */
- function _getUsersByPerm($permParams = array())
- {
- if (!is_object($this->perm)) {
- $this->stack->push(LIVEUSER_ADMIN_ERROR, 'exception',
- array('msg' => 'Perm container not set.'));
- return false;
- }
-
- $first = ($permParams['select'] == 'row');
- $permUsers = $this->perm->getUsers($permParams);
- if (!$permUsers) {
- return $permUsers;
- }
-
- if ($first) {
- $permUsers = array($permUsers);
- }
-
- $users = array();
- foreach ($permUsers as $permData) {
- if (!$this->setAdminAuthContainer($permData['auth_container_name'])) {
- $this->stack->push(LIVEUSER_ADMIN_ERROR, 'exception',
- array('msg' => 'Auth container could not be set.'));
- return false;
- }
-
- $authParams = array(
- 'filters' => array('auth_user_id' => $permData['auth_user_id']),
- 'select' => 'row',
- );
- $authData = $this->auth->getUsers($authParams);
- if (!$authData) {
- continue;
- }
-
- if ($first) {
- return LiveUser::arrayMergeClobber($permData, $authData);
- }
- $users[] = LiveUser::arrayMergeClobber($permData, $authData);
- }
-
- return $users;
- }
-
- /**
- * Finds and gets full userinfo by filtering inside the auth container
- *
- * @param array auth params (as for getUsers() from the auth container
- * @return array|bool Array with userinfo if found on success or false otherwise
- *
- * @access private
- */
- function _getUsersByAuth($authParams = array())
- {
- if (!is_object($this->auth) || !is_object($this->perm)) {
- $this->stack->push(LIVEUSER_ADMIN_ERROR, 'exception',
- array('msg' => 'Perm and/or Auth container not set.'));
- return false;
- }
-
- $first = ($authParams['select'] == 'row');
- $authUsers = $this->auth->getUsers($authParams);
- if (!$authUsers) {
- return $authUsers;
- }
-
- if ($first) {
- $authUsers = array($authUsers);
- }
-
- $users = array();
- foreach ($authUsers as $authData) {
- $permParams = array(
- 'filters' => array(
- 'auth_user_id' => $authData['auth_user_id'],
- 'auth_container_name' => $this->authContainerName,
- ),
- 'select' => 'row',
- );
- $permData = $this->perm->getUsers($permParams);
- if (!$permData) {
- continue;
- }
-
- if ($first) {
- return LiveUser::arrayMergeClobber($authData, $permData);
- }
- $users[] = LiveUser::arrayMergeClobber($authData, $permData);
- }
-
- return $users;
- }
-
- /**
- * Wrapper method to get the Error Stack
- *
- * @return array an array of the errors
- *
- * @access public
- */
- function getErrors()
- {
- if (is_object($this->stack)) {
- return $this->stack->getErrors();
- }
- return false;
- }
-
- /**
- * Calls a method using the __call() magic method on perm or auth
- *
- * @param string method name
- * @param array arguments
- * @return mixed returned value
- *
- * @access private
- */
- function __call($method, $params)
- {
- if (is_object($this->perm) && method_exists($this->perm, $method)) {
- return call_user_func_array(array(&$this->perm, $method), $params);
- }
- if (is_object($this->auth) && method_exists($this->auth, $method)) {
- return call_user_func_array(array(&$this->auth, $method), $params);
- }
- trigger_error(sprintf('Call to undefined function: %s::%s().', get_class($this), $method), E_USER_ERROR);
- }
-}
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */
-
-/**
- * The main include file for Auth package
- *
- * PHP versions 4 and 5
- *
- * LICENSE: This source file is subject to version 3.01 of the PHP license
- * that is available through the world-wide-web at the following URI:
- * http://www.php.net/license/3_01.txt. If you did not receive a copy of
- * the PHP License and are unable to obtain it through the web, please
- * send a note to license@php.net so we can mail you a copy immediately.
- *
- * @category Authentication
- * @package Auth
- * @author Martin Jansen <mj@php.net>
- * @author Adam Ashley <aashley@php.net>
- * @copyright 2001-2006 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version CVS: $Id: Auth.php,v 1.1.1.1 2008/04/28 15:20:46 jamie Exp $
- * @link http://pear.php.net/package/Auth
- */
-
-/**
- * Returned if session exceeds idle time
- */
-define('AUTH_IDLED', -1);
-/**
- * Returned if session has expired
- */
-define('AUTH_EXPIRED', -2);
-/**
- * Returned if container is unable to authenticate user/password pair
- */
-define('AUTH_WRONG_LOGIN', -3);
-/**
- * Returned if a container method is not supported.
- */
-define('AUTH_METHOD_NOT_SUPPORTED', -4);
-/**
- * Returned if new Advanced security system detects a breach
- */
-define('AUTH_SECURITY_BREACH', -5);
-/**
- * Returned if checkAuthCallback says session should not continue.
- */
-define('AUTH_CALLBACK_ABORT', -6);
-
-/**
- * Auth Log level - INFO
- */
-define('AUTH_LOG_INFO', 6);
-/**
- * Auth Log level - DEBUG
- */
-define('AUTH_LOG_DEBUG', 7);
-
-
-/**
- * PEAR::Auth
- *
- * The PEAR::Auth class provides methods for creating an
- * authentication system using PHP.
- *
- * @category Authentication
- * @package Auth
- * @author Martin Jansen <mj@php.net>
- * @author Adam Ashley <aashley@php.net>
- * @copyright 2001-2006 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version Release: 1.5.4 File: $Revision: 1.1.1.1 $
- * @link http://pear.php.net/package/Auth
- */
-class Auth {
-
- // {{{ properties
-
- /**
- * Auth lifetime in seconds
- *
- * If this variable is set to 0, auth never expires
- *
- * @var integer
- * @see setExpire(), checkAuth()
- */
- var $expire = 0;
-
- /**
- * Has the auth session expired?
- *
- * @var bool
- * @see checkAuth()
- */
- var $expired = false;
-
- /**
- * Maximum idletime in seconds
- *
- * The difference to $expire is, that the idletime gets
- * refreshed each time checkAuth() is called. If this
- * variable is set to 0, idletime is never checked.
- *
- * @var integer
- * @see setIdle(), checkAuth()
- */
- var $idle = 0;
-
- /**
- * Is the maximum idletime over?
- *
- * @var boolean
- * @see checkAuth()
- */
- var $idled = false;
-
- /**
- * Storage object
- *
- * @var object
- * @see Auth(), validateLogin()
- */
- var $storage = '';
-
- /**
- * User-defined function that creates the login screen
- *
- * @var string
- */
- var $loginFunction = '';
-
- /**
- * Should the login form be displayed
- *
- * @var bool
- * @see setShowlogin()
- */
- var $showLogin = true;
-
- /**
- * Is Login Allowed from this page
- *
- * @var bool
- * @see setAllowLogin
- */
- var $allowLogin = true;
-
- /**
- * Current authentication status
- *
- * @var string
- */
- var $status = '';
-
- /**
- * Username
- *
- * @var string
- */
- var $username = '';
-
- /**
- * Password
- *
- * @var string
- */
- var $password = '';
-
- /**
- * checkAuth callback function name
- *
- * @var string
- * @see setCheckAuthCallback()
- */
- var $checkAuthCallback = '';
-
- /**
- * Login callback function name
- *
- * @var string
- * @see setLoginCallback()
- */
- var $loginCallback = '';
-
- /**
- * Failed Login callback function name
- *
- * @var string
- * @see setFailedLoginCallback()
- */
- var $loginFailedCallback = '';
-
- /**
- * Logout callback function name
- *
- * @var string
- * @see setLogoutCallback()
- */
- var $logoutCallback = '';
-
- /**
- * Auth session-array name
- *
- * @var string
- */
- var $_sessionName = '_authsession';
-
- /**
- * Package Version
- *
- * @var string
- */
- var $version = "@version@";
-
- /**
- * Flag to use advanced security
- * When set extra checks will be made to see if the
- * user's IP or useragent have changed across requests.
- * Turned off by default to preserve BC.
- *
- * @var boolean
- */
- var $advancedsecurity = false;
-
- /**
- * Username key in POST array
- *
- * @var string
- */
- var $_postUsername = 'username';
-
- /**
- * Password key in POST array
- *
- * @var string
- */
- var $_postPassword = 'password';
-
- /**
- * Holds a reference to the session auth variable
- * @var array
- */
- var $session;
-
- /**
- * Holds a reference to the global server variable
- * @var array
- */
- var $server;
-
- /**
- * Holds a reference to the global post variable
- * @var array
- */
- var $post;
-
- /**
- * Holds a reference to the global cookie variable
- * @var array
- */
- var $cookie;
-
- /**
- * A hash to hold various superglobals as reference
- * @var array
- */
- var $authdata;
-
- /**
- * How many times has checkAuth been called
- * @var int
- */
- var $authChecks = 0;
-
- /**
- * PEAR::Log object
- *
- * @var object Log
- */
- var $logger = null;
-
- /**
- * Whether to enable logging of behaviour
- *
- * @var boolean
- */
- var $enableLogging = false;
-
- /**
- * Whether to regenerate session id everytime start is called
- *
- * @var boolean
- */
- var $regenerateSessionId = false;
-
- // }}}
- // {{{ Auth() [constructor]
-
- /**
- * Constructor
- *
- * Set up the storage driver.
- *
- * @param string Type of the storage driver
- * @param mixed Additional options for the storage driver
- * (example: if you are using DB as the storage
- * driver, you have to pass the dsn string here)
- *
- * @param string Name of the function that creates the login form
- * @param boolean Should the login form be displayed if neccessary?
- * @return void
- */
- function Auth($storageDriver, $options = '', $loginFunction = '', $showLogin = true)
- {
- $this->applyAuthOptions($options);
-
- // Start the session suppress error if already started
- if(!session_id()){
- @session_start();
- if(!session_id()) {
- // Throw error
- include_once 'PEAR.php';
- PEAR::throwError('Session could not be started by Auth, '
- .'possibly headers are already sent, try putting '
- .'ob_start in the beginning of your script');
- }
- }
-
- // Make Sure Auth session variable is there
- if(!isset($_SESSION[$this->_sessionName])) {
- $_SESSION[$this->_sessionName] = array();
- }
-
- // Assign Some globals to internal references, this will replace _importGlobalVariable
- $this->session =& $_SESSION[$this->_sessionName];
- $this->server =& $_SERVER;
- $this->post =& $_POST;
- $this->cookie =& $_COOKIE;
-
- if ($loginFunction != '' && is_callable($loginFunction)) {
- $this->loginFunction = $loginFunction;
- }
-
- if (is_bool($showLogin)) {
- $this->showLogin = $showLogin;
- }
-
- if (is_object($storageDriver)) {
- $this->storage =& $storageDriver;
- // Pass a reference to auth to the container, ugly but works
- // this is used by the DB container to use method setAuthData not staticaly.
- $this->storage->_auth_obj =& $this;
- } else {
- // $this->storage = $this->_factory($storageDriver, $options);
- //
- $this->storage_driver = $storageDriver;
- $this->storage_options =& $options;
- }
- }
-
- // }}}
- // {{{ applyAuthOptions()
-
- /**
- * Set the Auth options
- *
- * Some options which are Auth specific will be applied
- * the rest will be left for usage by the container
- *
- * @param array An array of Auth options
- * @return array The options which were not applied
- * @access private
- */
- function &applyAuthOptions(&$options)
- {
- if(is_array($options)){
- if (!empty($options['sessionName'])) {
- $this->_sessionName = $options['sessionName'];
- unset($options['sessionName']);
- }
- if (isset($options['allowLogin'])) {
- $this->allowLogin = $options['allowLogin'];
- unset($options['allowLogin']);
- }
- if (!empty($options['postUsername'])) {
- $this->_postUsername = $options['postUsername'];
- unset($options['postUsername']);
- }
- if (!empty($options['postPassword'])) {
- $this->_postPassword = $options['postPassword'];
- unset($options['postPassword']);
- }
- if (isset($options['advancedsecurity'])) {
- $this->advancedsecurity = $options['advancedsecurity'];
- unset($options['advancedsecurity']);
- }
- if (isset($options['enableLogging'])) {
- $this->enableLogging = $options['enableLogging'];
- unset($options['enableLogging']);
- }
- if (isset($options['regenerateSessionId']) && is_bool($options['regenerateSessionId'])) {
- $this->regenerateSessionId = $options['regenerateSessionId'];
- }
- }
- return($options);
- }
-
- // }}}
- // {{{ _loadStorage()
-
- /**
- * Load Storage Driver if not already loaded
- *
- * Suspend storage instantiation to make Auth lighter to use
- * for calls which do not require login
- *
- * @return bool True if the conainer is loaded, false if the container
- * is already loaded
- * @access private
- */
- function _loadStorage()
- {
- if(!is_object($this->storage)) {
- $this->storage =& $this->_factory($this->storage_driver,
- $this->storage_options);
- $this->storage->_auth_obj =& $this;
- $this->log('Loaded storage container ('.$this->storage_driver.')', AUTH_LOG_DEBUG);
- return(true);
- }
- return(false);
- }
-
- // }}}
- // {{{ _factory()
-
- /**
- * Return a storage driver based on $driver and $options
- *
- * @static
- * @param string $driver Type of storage class to return
- * @param string $options Optional parameters for the storage class
- * @return object Object Storage object
- * @access private
- */
- function &_factory($driver, $options = '')
- {
- $storage_class = 'Auth_Container_' . $driver;
- include_once 'Auth/Container/' . $driver . '.php';
- $obj =& new $storage_class($options);
- return $obj;
- }
-
- // }}}
- // {{{ assignData()
-
- /**
- * Assign data from login form to internal values
- *
- * This function takes the values for username and password
- * from $HTTP_POST_VARS/$_POST and assigns them to internal variables.
- * If you wish to use another source apart from $HTTP_POST_VARS/$_POST,
- * you have to derive this function.
- *
- * @global $HTTP_POST_VARS, $_POST
- * @see Auth
- * @return void
- * @access private
- */
- function assignData()
- {
- $this->log('Auth::assignData() called.', AUTH_LOG_DEBUG);
-
- if ( isset($this->post[$this->_postUsername])
- && $this->post[$this->_postUsername] != '') {
- $this->username = (get_magic_quotes_gpc() == 1
- ? stripslashes($this->post[$this->_postUsername])
- : $this->post[$this->_postUsername]);
- }
- if ( isset($this->post[$this->_postPassword])
- && $this->post[$this->_postPassword] != '') {
- $this->password = (get_magic_quotes_gpc() == 1
- ? stripslashes($this->post[$this->_postPassword])
- : $this->post[$this->_postPassword] );
- }
- }
-
- // }}}
- // {{{ start()
-
- /**
- * Start new auth session
- *
- * @return void
- * @access public
- */
- function start()
- {
- $this->log('Auth::start() called.', AUTH_LOG_DEBUG);
-
- // #10729 - Regenerate session id here if we are generating it on every
- // page load.
- if ($this->regenerateSessionId) {
- session_regenerate_id(true);
- }
-
- $this->assignData();
- if (!$this->checkAuth() && $this->allowLogin) {
- $this->login();
- }
- }
-
- // }}}
- // {{{ login()
-
- /**
- * Login function
- *
- * @return void
- * @access private
- */
- function login()
- {
- $this->log('Auth::login() called.', AUTH_LOG_DEBUG);
-
- $login_ok = false;
- $this->_loadStorage();
-
- // Check if using challenge response
- (isset($this->post['authsecret']) && $this->post['authsecret'] == 1)
- ? $usingChap = true
- : $usingChap = false;
-
-
- // When the user has already entered a username, we have to validate it.
- if (!empty($this->username)) {
- if (true === $this->storage->fetchData($this->username, $this->password, $usingChap)) {
- $this->session['challengekey'] = md5($this->username.$this->password);
- $login_ok = true;
- $this->log('Successful login.', AUTH_LOG_INFO);
- }
- }
-
- if (!empty($this->username) && $login_ok) {
- $this->setAuth($this->username);
- if (is_callable($this->loginCallback)) {
- $this->log('Calling loginCallback ('.$this->loginCallback.').', AUTH_LOG_DEBUG);
- call_user_func_array($this->loginCallback, array($this->username, &$this));
- }
- }
-
- // If the login failed or the user entered no username,
- // output the login screen again.
- if (!empty($this->username) && !$login_ok) {
- $this->log('Incorrect login.', AUTH_LOG_INFO);
- $this->status = AUTH_WRONG_LOGIN;
- if (is_callable($this->loginFailedCallback)) {
- $this->log('Calling loginFailedCallback ('.$this->loginFailedCallback.').', AUTH_LOG_DEBUG);
- call_user_func_array($this->loginFailedCallback, array($this->username, &$this));
- }
- }
-
- if ((empty($this->username) || !$login_ok) && $this->showLogin) {
- $this->log('Rendering Login Form.', AUTH_LOG_INFO);
- if (is_callable($this->loginFunction)) {
- $this->log('Calling loginFunction ('.$this->loginFunction.').', AUTH_LOG_DEBUG);
- call_user_func_array($this->loginFunction, array($this->username, $this->status, &$this));
- } else {
- // BC fix Auth used to use drawLogin for this
- // call is sub classes implement this
- if (is_callable(array($this, 'drawLogin'))) {
- $this->log('Calling Auth::drawLogin()', AUTH_LOG_DEBUG);
- return $this->drawLogin($this->username, $this);
- }
-
- $this->log('Using default Auth_Frontend_Html', AUTH_LOG_DEBUG);
-
- // New Login form
- include_once 'Auth/Frontend/Html.php';
- return Auth_Frontend_Html::render($this, $this->username);
- }
- } else {
- return;
- }
- }
-
- // }}}
- // {{{ setExpire()
-
- /**
- * Set the maximum expire time
- *
- * @param integer time in seconds
- * @param bool add time to current expire time or not
- * @return void
- * @access public
- */
- function setExpire($time, $add = false)
- {
- $add ? $this->expire += $time : $this->expire = $time;
- }
-
- // }}}
- // {{{ setIdle()
-
- /**
- * Set the maximum idle time
- *
- * @param integer time in seconds
- * @param bool add time to current maximum idle time or not
- * @return void
- * @access public
- */
- function setIdle($time, $add = false)
- {
- $add ? $this->idle += $time : $this->idle = $time;
- }
-
- // }}}
- // {{{ setSessionName()
-
- /**
- * Set name of the session to a customized value.
- *
- * If you are using multiple instances of PEAR::Auth
- * on the same domain, you can change the name of
- * session per application via this function.
- * This will chnage the name of the session variable
- * auth uses to store it's data in the session
- *
- * @param string New name for the session
- * @return void
- * @access public
- */
- function setSessionName($name = 'session')
- {
- $this->_sessionName = '_auth_'.$name;
- // Make Sure Auth session variable is there
- if(!isset($_SESSION[$this->_sessionName])) {
- $_SESSION[$this->_sessionName] = array();
- }
- $this->session =& $_SESSION[$this->_sessionName];
- }
-
- // }}}
- // {{{ setShowLogin()
-
- /**
- * Should the login form be displayed if neccessary?
- *
- * @param bool show login form or not
- * @return void
- * @access public
- */
- function setShowLogin($showLogin = true)
- {
- $this->showLogin = $showLogin;
- }
-
- // }}}
- // {{{ setAllowLogin()
-
- /**
- * Should the login form be displayed if neccessary?
- *
- * @param bool show login form or not
- * @return void
- * @access public
- */
- function setAllowLogin($allowLogin = true)
- {
- $this->allowLogin = $allowLogin;
- }
-
- // }}}
- // {{{ setCheckAuthCallback()
-
- /**
- * Register a callback function to be called whenever the validity of the login is checked
- * The function will receive two parameters, the username and a reference to the auth object.
- *
- * @param string callback function name
- * @return void
- * @access public
- * @since Method available since Release 1.4.3
- */
- function setCheckAuthCallback($checkAuthCallback)
- {
- $this->checkAuthCallback = $checkAuthCallback;
- }
-
- // }}}
- // {{{ setLoginCallback()
-
- /**
- * Register a callback function to be called on user login.
- * The function will receive two parameters, the username and a reference to the auth object.
- *
- * @param string callback function name
- * @return void
- * @see setLogoutCallback()
- * @access public
- */
- function setLoginCallback($loginCallback)
- {
- $this->loginCallback = $loginCallback;
- }
-
- // }}}
- // {{{ setFailedLoginCallback()
-
- /**
- * Register a callback function to be called on failed user login.
- * The function will receive two parameters, the username and a reference to the auth object.
- *
- * @param string callback function name
- * @return void
- * @access public
- */
- function setFailedLoginCallback($loginFailedCallback)
- {
- $this->loginFailedCallback = $loginFailedCallback;
- }
-
- // }}}
- // {{{ setLogoutCallback()
-
- /**
- * Register a callback function to be called on user logout.
- * The function will receive three parameters, the username and a reference to the auth object.
- *
- * @param string callback function name
- * @return void
- * @see setLoginCallback()
- * @access public
- */
- function setLogoutCallback($logoutCallback)
- {
- $this->logoutCallback = $logoutCallback;
- }
-
- // }}}
- // {{{ setAuthData()
-
- /**
- * Register additional information that is to be stored
- * in the session.
- *
- * @param string Name of the data field
- * @param mixed Value of the data field
- * @param boolean Should existing data be overwritten? (default
- * is true)
- * @return void
- * @access public
- */
- function setAuthData($name, $value, $overwrite = true)
- {
- if (!empty($this->session['data'][$name]) && $overwrite == false) {
- return;
- }
- $this->session['data'][$name] = $value;
- }
-
- // }}}
- // {{{ getAuthData()
-
- /**
- * Get additional information that is stored in the session.
- *
- * If no value for the first parameter is passed, the method will
- * return all data that is currently stored.
- *
- * @param string Name of the data field
- * @return mixed Value of the data field.
- * @access public
- */
- function getAuthData($name = null)
- {
- if (!isset($this->session['data'])) {
- return null;
- }
- if(!isset($name)) {
- return $this->session['data'];
- }
- if (isset($name) && isset($this->session['data'][$name])) {
- return $this->session['data'][$name];
- }
- return null;
- }
-
- // }}}
- // {{{ setAuth()
-
- /**
- * Register variable in a session telling that the user
- * has logged in successfully
- *
- * @param string Username
- * @return void
- * @access public
- */
- function setAuth($username)
- {
- $this->log('Auth::setAuth() called.', AUTH_LOG_DEBUG);
-
- // #10729 - Regenerate session id here only if generating at login only
- // Don't do it if we are regenerating on every request so we don't
- // regenerate it twice in one request.
- if (!$this->regenerateSessionId) {
- // #2021 - Change the session id to avoid session fixation attacks php 4.3.3 >
- session_regenerate_id(true);
- }
-
- if (!isset($this->session) || !is_array($this->session)) {
- $this->session = array();
- }
-
- if (!isset($this->session['data'])) {
- $this->session['data'] = array();
- }
-
- $this->session['sessionip'] = isset($this->server['REMOTE_ADDR'])
- ? $this->server['REMOTE_ADDR']
- : '';
- $this->session['sessionuseragent'] = isset($this->server['HTTP_USER_AGENT'])
- ? $this->server['HTTP_USER_AGENT']
- : '';
- $this->session['sessionforwardedfor'] = isset($this->server['HTTP_X_FORWARDED_FOR'])
- ? $this->server['HTTP_X_FORWARDED_FOR']
- : '';
-
- // This should be set by the container to something more safe
- // Like md5(passwd.microtime)
- if(empty($this->session['challengekey'])) {
- $this->session['challengekey'] = md5($username.microtime());
- }
-
- $this->session['challengecookie'] = md5($this->session['challengekey'].microtime());
- setcookie('authchallenge', $this->session['challengecookie']);
-
- $this->session['registered'] = true;
- $this->session['username'] = $username;
- $this->session['timestamp'] = time();
- $this->session['idle'] = time();
- }
-
- // }}}
- // {{{ setAdvancedSecurity()
-
- /**
- * Enables advanced security checks
- *
- * Currently only ip change and useragent change
- * are detected
- * @todo Add challenge cookies - Create a cookie which changes every time
- * and contains some challenge key which the server can verify with
- * a session var cookie might need to be crypted (user pass)
- * @param bool Enable or disable
- * @return void
- * @access public
- */
- function setAdvancedSecurity($flag=true)
- {
- $this->advancedsecurity = $flag;
- }
-
- // }}}
- // {{{ checkAuth()
-
- /**
- * Checks if there is a session with valid auth information.
- *
- * @access public
- * @return boolean Whether or not the user is authenticated.
- */
- function checkAuth()
- {
- $this->log('Auth::checkAuth() called.', AUTH_LOG_DEBUG);
- $this->authChecks++;
- if (isset($this->session)) {
- // Check if authentication session is expired
- if ( $this->expire > 0
- && isset($this->session['timestamp'])
- && ($this->session['timestamp'] + $this->expire) < time()) {
- $this->log('Session Expired', AUTH_LOG_INFO);
- $this->expired = true;
- $this->status = AUTH_EXPIRED;
- $this->logout();
- return false;
- }
-
- // Check if maximum idle time is reached
- if ( $this->idle > 0
- && isset($this->session['idle'])
- && ($this->session['idle'] + $this->idle) < time()) {
- $this->log('Session Idle Time Reached', AUTH_LOG_INFO);
- $this->idled = true;
- $this->status = AUTH_IDLED;
- $this->logout();
- return false;
- }
-
- if ( isset($this->session['registered'])
- && isset($this->session['username'])
- && $this->session['registered'] == true
- && $this->session['username'] != '') {
- Auth::updateIdle();
-
- if ($this->advancedsecurity) {
- $this->log('Advanced Security Mode Enabled.', AUTH_LOG_DEBUG);
-
- // Only Generate the challenge once
- if($this->authChecks == 1) {
- $this->log('Generating new Challenge Cookie.', AUTH_LOG_DEBUG);
- $this->session['challengecookieold'] = $this->session['challengecookie'];
- $this->session['challengecookie'] = md5($this->session['challengekey'].microtime());
- setcookie('authchallenge', $this->session['challengecookie']);
- }
-
- // Check for ip change
- if ( isset($this->server['REMOTE_ADDR'])
- && $this->session['sessionip'] != $this->server['REMOTE_ADDR']) {
- $this->log('Security Breach. Remote IP Address changed.', AUTH_LOG_INFO);
- // Check if the IP of the user has changed, if so we
- // assume a man in the middle attack and log him out
- $this->expired = true;
- $this->status = AUTH_SECURITY_BREACH;
- $this->logout();
- return false;
- }
-
- // Check for ip change (if connected via proxy)
- if ( isset($this->server['HTTP_X_FORWARDED_FOR'])
- && $this->session['sessionforwardedfor'] != $this->server['HTTP_X_FORWARDED_FOR']) {
- $this->log('Security Breach. Forwarded For IP Address changed.', AUTH_LOG_INFO);
- // Check if the IP of the user connecting via proxy has
- // changed, if so we assume a man in the middle attack
- // and log him out.
- $this->expired = true;
- $this->status = AUTH_SECURITY_BREACH;
- $this->logout();
- return false;
- }
-
- // Check for useragent change
- if ( isset($this->server['HTTP_USER_AGENT'])
- && $this->session['sessionuseragent'] != $this->server['HTTP_USER_AGENT']) {
- $this->log('Security Breach. User Agent changed.', AUTH_LOG_INFO);
- // Check if the User-Agent of the user has changed, if
- // so we assume a man in the middle attack and log him out
- $this->expired = true;
- $this->status = AUTH_SECURITY_BREACH;
- $this->logout();
- return false;
- }
-
- // Check challenge cookie here, if challengecookieold is not set
- // this is the first time and check is skipped
- // TODO when user open two pages similtaneuly (open in new window,open
- // in tab) auth breach is caused find out a way around that if possible
- if ( isset($this->session['challengecookieold'])
- && $this->session['challengecookieold'] != $this->cookie['authchallenge']) {
- $this->log('Security Breach. Challenge Cookie mismatch.', AUTH_LOG_INFO);
- $this->expired = true;
- $this->status = AUTH_SECURITY_BREACH;
- $this->logout();
- $this->login();
- return false;
- }
- }
-
- if (is_callable($this->checkAuthCallback)) {
- $this->log('Calling checkAuthCallback ('.$this->checkAuthCallback.').', AUTH_LOG_DEBUG);
- $checkCallback = call_user_func_array($this->checkAuthCallback, array($this->username, &$this));
- if ($checkCallback == false) {
- $this->log('checkAuthCallback failed.', AUTH_LOG_INFO);
- $this->expired = true;
- $this->status = AUTH_CALLBACK_ABORT;
- $this->logout();
- return false;
- }
- }
-
- $this->log('Session OK.', AUTH_LOG_INFO);
- return true;
- }
- }
- $this->log('Unable to locate session storage.', AUTH_LOG_DEBUG);
- return false;
- }
-
- // }}}
- // {{{ staticCheckAuth() [static]
-
- /**
- * Statically checks if there is a session with valid auth information.
- *
- * @access public
- * @see checkAuth
- * @return boolean Whether or not the user is authenticated.
- * @static
- */
- function staticCheckAuth($options = null)
- {
- static $staticAuth;
- if(!isset($staticAuth)) {
- $staticAuth = new Auth('null', $options);
- }
- $staticAuth->log('Auth::staticCheckAuth() called', AUTH_LOG_DEBUG);
- return $staticAuth->checkAuth();
- }
-
- // }}}
- // {{{ getAuth()
-
- /**
- * Has the user been authenticated?
- *
- * @access public
- * @return bool True if the user is logged in, otherwise false.
- */
- function getAuth()
- {
- $this->log('Auth::getAuth() called.', AUTH_LOG_DEBUG);
- return $this->checkAuth();
- }
-
- // }}}
- // {{{ logout()
-
- /**
- * Logout function
- *
- * This function clears any auth tokens in the currently
- * active session and executes the logout callback function,
- * if any
- *
- * @access public
- * @return void
- */
- function logout()
- {
- $this->log('Auth::logout() called.', AUTH_LOG_DEBUG);
-
- if (is_callable($this->logoutCallback) && isset($this->session['username'])) {
- $this->log('Calling logoutCallback ('.$this->logoutCallback.').', AUTH_LOG_DEBUG);
- call_user_func_array($this->logoutCallback, array($this->session['username'], &$this));
- }
-
- $this->username = '';
- $this->password = '';
-
- $this->session = null;
- }
-
- // }}}
- // {{{ updateIdle()
-
- /**
- * Update the idletime
- *
- * @access private
- * @return void
- */
- function updateIdle()
- {
- $this->session['idle'] = time();
- }
-
- // }}}
- // {{{ getUsername()
-
- /**
- * Get the username
- *
- * @return string
- * @access public
- */
- function getUsername()
- {
- if (isset($this->session['username'])) {
- return($this->session['username']);
- }
- return('');
- }
-
- // }}}
- // {{{ getStatus()
-
- /**
- * Get the current status
- *
- * @return string
- * @access public
- */
- function getStatus()
- {
- return $this->status;
- }
-
- // }}}
- // {{{ getPostUsernameField()
-
- /**
- * Gets the post varible used for the username
- *
- * @return string
- * @access public
- */
- function getPostUsernameField()
- {
- return($this->_postUsername);
- }
-
- // }}}
- // {{{ getPostPasswordField()
-
- /**
- * Gets the post varible used for the username
- *
- * @return string
- * @access public
- */
- function getPostPasswordField()
- {
- return($this->_postPassword);
- }
-
- // }}}
- // {{{ sessionValidThru()
-
- /**
- * Returns the time up to the session is valid
- *
- * @access public
- * @return integer
- */
- function sessionValidThru()
- {
- if (!isset($this->session['idle'])) {
- return 0;
- }
- if ($this->idle == 0) {
- return 0;
- }
- return ($this->session['idle'] + $this->idle);
- }
-
- // }}}
- // {{{ listUsers()
-
- /**
- * List all users that are currently available in the storage
- * container
- *
- * @access public
- * @return array
- */
- function listUsers()
- {
- $this->log('Auth::listUsers() called.', AUTH_LOG_DEBUG);
- $this->_loadStorage();
- return $this->storage->listUsers();
- }
-
- // }}}
- // {{{ addUser()
-
- /**
- * Add user to the storage container
- *
- * @access public
- * @param string Username
- * @param string Password
- * @param mixed Additional parameters
- * @return mixed True on success, PEAR error object on error
- * and AUTH_METHOD_NOT_SUPPORTED otherwise.
- */
- function addUser($username, $password, $additional = '')
- {
- $this->log('Auth::addUser() called.', AUTH_LOG_DEBUG);
- $this->_loadStorage();
- return $this->storage->addUser($username, $password, $additional);
- }
-
- // }}}
- // {{{ removeUser()
-
- /**
- * Remove user from the storage container
- *
- * @access public
- * @param string Username
- * @return mixed True on success, PEAR error object on error
- * and AUTH_METHOD_NOT_SUPPORTED otherwise.
- */
- function removeUser($username)
- {
- $this->log('Auth::removeUser() called.', AUTH_LOG_DEBUG);
- $this->_loadStorage();
- return $this->storage->removeUser($username);
- }
-
- // }}}
- // {{{ changePassword()
-
- /**
- * Change password for user in the storage container
- *
- * @access public
- * @param string Username
- * @param string The new password
- * @return mixed True on success, PEAR error object on error
- * and AUTH_METHOD_NOT_SUPPORTED otherwise.
- */
- function changePassword($username, $password)
- {
- $this->log('Auth::changePassword() called', AUTH_LOG_DEBUG);
- $this->_loadStorage();
- return $this->storage->changePassword($username, $password);
- }
-
- // }}}
- // {{{ log()
-
- /**
- * Log a message from the Auth system
- *
- * @access public
- * @param string The message to log
- * @param string The log level to log the message under. See the Log documentation for more info.
- * @return boolean
- */
- function log($message, $level = AUTH_LOG_DEBUG)
- {
- if (!$this->enableLogging) return false;
-
- $this->_loadLogger();
-
- $this->logger->log('AUTH: '.$message, $level);
- }
-
- // }}}
- // {{{ _loadLogger()
-
- /**
- * Load Log object if not already loaded
- *
- * Suspend logger instantiation to make Auth lighter to use
- * for calls which do not require logging
- *
- * @return bool True if the logger is loaded, false if the logger
- * is already loaded
- * @access private
- */
- function _loadLogger()
- {
- if(is_null($this->logger)) {
- if (!class_exists('Log')) {
- include_once 'Log.php';
- }
- $this->logger =& Log::singleton('null',
- null,
- 'auth['.getmypid().']',
- array(),
- AUTH_LOG_DEBUG);
- return(true);
- }
- return(false);
- }
-
- // }}}
- // {{{ attachLogObserver()
-
- /**
- * Attach an Observer to the Auth Log Source
- *
- * @param object Log_Observer A Log Observer instance
- * @return boolean
- */
- function attachLogObserver(&$observer) {
-
- $this->_loadLogger();
-
- return $this->logger->attach($observer);
-
- }
-
- // }}}
-
-}
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */
-
-/**
- * Anonymous authentication support
- *
- * PHP versions 4 and 5
- *
- * LICENSE: This source file is subject to version 3.01 of the PHP license
- * that is available through the world-wide-web at the following URI:
- * http://www.php.net/license/3_01.txt. If you did not receive a copy of
- * the PHP License and are unable to obtain it through the web, please
- * send a note to license@php.net so we can mail you a copy immediately.
- *
- * @category Authentication
- * @package Auth
- * @author Yavor Shahpasov <yavo@netsmart.com.cy>
- * @author Adam Ashley <aashley@php.net>
- * @copyright 2001-2006 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version CVS: $Id: Anonymous.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- * @link http://pear.php.net/package/Auth
- * @since File available since Release 1.3.0
- */
-
-/**
- * Include Auth package
- */
-require_once 'Auth.php';
-
-/**
- * Anonymous Authentication
- *
- * This class provides anonymous authentication if username and password
- * were not supplied
- *
- * @category Authentication
- * @package Auth
- * @author Yavor Shahpasov <yavo@netsmart.com.cy>
- * @author Adam Ashley <aashley@php.net>
- * @copyright 2001-2006 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version Release: 1.5.4 File: $Revision: 1.1.1.1 $
- * @link http://pear.php.net/package/Auth
- * @since Class available since Release 1.3.0
- */
-class Auth_Anonymous extends Auth
-{
-
- // {{{ properties
-
- /**
- * Whether to allow anonymous authentication
- *
- * @var boolean
- */
- var $allow_anonymous = true;
-
- /**
- * Username to use for anonymous user
- *
- * @var string
- */
- var $anonymous_username = 'anonymous';
-
- // }}}
- // {{{ Auth_Anonymous() [constructor]
-
- /**
- * Pass all parameters to Parent Auth class
- *
- * Set up the storage driver.
- *
- * @param string Type of the storage driver
- * @param mixed Additional options for the storage driver
- * (example: if you are using DB as the storage
- * driver, you have to pass the dsn string here)
- *
- * @param string Name of the function that creates the login form
- * @param boolean Should the login form be displayed if neccessary?
- * @return void
- * @see Auth::Auth()
- */
- function Auth_Anonymous($storageDriver, $options = '', $loginFunction = '', $showLogin = true) {
- parent::Auth($storageDriver, $options, $loginFunction, $showLogin);
- }
-
- // }}}
- // {{{ login()
-
- /**
- * Login function
- *
- * If no username & password is passed then login as the username
- * provided in $this->anonymous_username else call standard login()
- * function.
- *
- * @return void
- * @access private
- * @see Auth::login()
- */
- function login() {
- if ( $this->allow_anonymous
- && empty($this->username)
- && empty($this->password) ) {
- $this->setAuth($this->anonymous_username);
- if (is_callable($this->loginCallback)) {
- call_user_func_array($this->loginCallback, array($this->username, $this) );
- }
- } else {
- // Call normal login system
- parent::login();
- }
- }
-
- // }}}
- // {{{ forceLogin()
-
- /**
- * Force the user to login
- *
- * Calling this function forces the user to provide a real username and
- * password before continuing.
- *
- * @return void
- */
- function forceLogin() {
- $this->allow_anonymous = false;
- if( !empty($this->session['username']) && $this->session['username'] == $this->anonymous_username ) {
- $this->logout();
- }
- }
-
- // }}}
-
-}
-
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */
-
-/**
- * Provide compatibility with previous Auth include location.
- *
- * PHP versions 4 and 5
- *
- * LICENSE: This source file is subject to version 3.01 of the PHP license
- * that is available through the world-wide-web at the following URI:
- * http://www.php.net/license/3_01.txt. If you did not receive a copy of
- * the PHP License and are unable to obtain it through the web, please
- * send a note to license@php.net so we can mail you a copy immediately.
- *
- * @category Authentication
- * @package Auth
- * @author Martin Jansen <mj@php.net>
- * @copyright 2001-2006 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version CVS: $Id: Auth.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- * @link http://pear.php.net/package/Auth
- * @deprecated File deprecated since Release 1.2.0
- */
-
-/**
- * Include Auth package
- */
-require_once 'Auth.php';
-
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * A framework for authentication and authorization in PHP applications
- *
- * LiveUser_Admin is meant to be used with the LiveUser package.
- * It is composed of all the classes necessary to administrate
- * data used by LiveUser.
- *
- * You'll be able to add/edit/delete/get things like:
- * * Rights
- * * Users
- * * Groups
- * * Areas
- * * Applications
- * * Subgroups
- * * ImpliedRights
- *
- * And all other entities within LiveUser.
- *
- * At the moment we support the following storage containers:
- * * DB
- * * MDB
- * * MDB2
- *
- * But it takes no time to write up your own storage container,
- * so if you like to use native mysql functions straight, then it's possible
- * to do so in under a hour!
- *
- * PHP version 4 and 5
- *
- * LICENSE: This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library 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
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
- * MA 02111-1307 USA
- *
- *
- * @category authentication
- * @package LiveUser_Admin
- * @author Markus Wolff <wolff@21st.de>
- * @author Helgi Þormar Þorbjörnsson <dufuz@php.net>
- * @author Lukas Smith <smith@pooteeweet.org>
- * @author Arnaud Limbourg <arnaud@php.net>
- * @author Christian Dickmann <dickmann@php.net>
- * @author Matt Scifo <mscifo@php.net>
- * @author Bjoern Kraus <krausbn@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version CVS: $Id: Common.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- * @link http://pear.php.net/LiveUser_Admin
- */
-
-/**
- * Base class for authentication backends.
- *
- * @category authentication
- * @package LiveUser_Admin
- * @author Lukas Smith <smith@pooteeweet.org>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version Release: @package_version@
- * @link http://pear.php.net/LiveUser_Admin
- */
-class LiveUser_Admin_Auth_Common
-{
- /**
- * Error stack
- *
- * @var object PEAR_ErrorStack
- * @access public
- */
- var $stack = null;
-
- /**
- * Storage Container
- *
- * @var LiveUser_Admin_Storage
- * @access private
- */
- var $_storage = null;
-
- /**
- * Key (method names), with array lists of selectable tables for the given method
- *
- * @var array
- * @access public
- */
- var $selectable_tables = array(
- 'getUsers' => array('users'),
- );
-
- /**
- * Set posible encryption modes.
- *
- * @access private
- * @var array
- */
- var $encryptionModes = array(
- 'MD5' => 'MD5',
- 'RC4' => 'RC4',
- 'PLAIN' => 'PLAIN',
- 'SHA1' => 'SHA1'
- );
-
- /**
- * Defines the algorithm used for encrypting/decrypting
- * passwords. Default: "MD5".
- *
- * @access private
- * @var string
- */
- var $passwordEncryptionMode = 'MD5';
-
- /**
- * Defines the secret to use for encryption if needed
- *
- * @access protected
- * @var string
- */
- var $secret;
-
- /**
- * The name associated with this auth container. The name is used
- * when adding users from this container to the reference table
- * in the permission container. This way it is possible to see
- * from which auth container the user data is coming from.
- *
- * @var string
- * @access public
- */
- var $containerName = null;
-
- /**
- * Class constructor. Feel free to override in backend subclasses.
- *
- * @access protected
- */
- function LiveUser_Admin_Auth_Common()
- {
- $this->stack = &PEAR_ErrorStack::singleton('LiveUser_Admin');
- }
-
- /**
- * Initialize the storage container
- *
- * @access public
- * @param array contains configuration of the container
- * @param string name of container
- * @return bool true on success or false on failure
- */
- function init(&$conf, $containerName)
- {
- $this->containerName = $containerName;
- if (!array_key_exists('storage', $conf)) {
- $this->stack->push(LIVEUSER_ADMIN_ERROR, 'exception',
- array('msg' => 'Missing storage configuration array'));
- return false;
- }
-
- if (is_array($conf)) {
- $keys = array_keys($conf);
- foreach ($keys as $key) {
- if (isset($this->$key)) {
- $this->$key =& $conf[$key];
- }
- }
- }
-
- $storageConf = array();
- $storageConf[$conf['type']] =& $conf['storage'];
- $this->_storage = LiveUser::storageFactory($storageConf, 'LiveUser_Admin_Auth_');
- if ($this->_storage === false) {
- $this->stack->push(LIVEUSER_ADMIN_ERROR, 'exception',
- array('msg' => 'Could not instanciate auth storage container: '.$conf['type']));
- return false;
- }
-
- return true;
- }
-
- /**
- * Decrypts a password so that it can be compared with the user input.
- * Uses the algorithm defined in the passwordEncryptionMode property.
- *
- * @param string the encrypted password
- * @return string the decrypted password
- *
- * @access public
- */
- function decryptPW($encryptedPW)
- {
- return LiveUser::decryptPW($encryptedPW, $this->passwordEncryptionMode, $this->secret);
- }
-
- /**
- * Encrypts a password for storage in a backend container.
- * Uses the algorithm defined in the passwordEncryptionMode property.
- *
- * @param string encryption type
- * @return string the encrypted password
- *
- * @access public
- */
- function encryptPW($plainPW)
- {
- return LiveUser::encryptPW($plainPW, $this->passwordEncryptionMode, $this->secret);
- }
-
- /**
- * Add a user
- *
- * @param array containing atleast the key-value-pairs of all required
- * columns in the users table
- * @return int|bool false on error, true (or new id) on success
- *
- * @access public
- */
- function addUser($data)
- {
- // todo: does this work?
- if (array_key_exists('passwd', $data)) {
- $data['passwd'] = $this->encryptPW($data['passwd']);
- }
- $result = $this->_storage->insert('users', $data);
- // todo: notify observer
- return $result;
- }
-
- /**
- * Update a user
- *
- * @param array containing the key value pairs of columns to update
- * @param array key values pairs (value may be a string or an array)
- * This will construct the WHERE clause of your update
- * Be careful, if you leave this blank no WHERE clause
- * will be used and all users will be affected by the update
- * @return int|bool false on error, the affected rows on success
- *
- * @access public
- */
- function updateUser($data, $filters)
- {
- if (array_key_exists('passwd', $data)) {
- $data['passwd'] = $this->encryptPW($data['passwd']);
- }
- $result = $this->_storage->update('users', $data, $filters);
- // todo: notify observer
- return $result;
- }
-
- /**
- * Remove a user
- *
- * @param array key values pairs (value may be a string or an array)
- * This will construct the WHERE clause of your update
- * Be careful, if you leave this blank no WHERE clause
- * will be used and all users will be affected by the update
- * @return int|bool false on error, the affected rows on success
- *
- * @access public
- */
- function removeUser($filters)
- {
- $result = $this->_storage->delete('users', $filters);
- // todo: notify observer
- return $result;
- }
-
- /**
- * Fetches users
- *
- * @param array containing key-value pairs for:
- * 'fields' - ordered array containing the fields to fetch
- * if empty all fields from the user table are fetched
- * 'filters' - key values pairs (value may be a string or an array)
- * 'orders' - key value pairs (values 'ASC' or 'DESC')
- * 'rekey' - if set to true, returned array will have the
- * first column as its first dimension
- * 'group' - if set to true and $rekey is set to true, then
- * all values with the same first column will be
- * wrapped in an array
- * 'limit' - number of rows to select
- * 'offset' - first row to select
- * 'select' - determines what query method to use:
- * 'one' -> queryOne, 'row' -> queryRow,
- * 'col' -> queryCol, 'all' ->queryAll (default)
- * 'selectable_tables' - array list of tables that may be
- * joined to in this query, the first element is
- * the root table from which the joins are done
- * @return bool|array false on failure or array with selected data
- *
- * @access public
- */
- function getUsers($params = array())
- {
- $selectable_tables = array();
- if (array_key_exists('selectable_tables', $params)) {
- $selectable_tables = $params['selectable_tables'];
- } elseif (array_key_exists('getUsers', $this->selectable_tables)) {
- $selectable_tables = $this->selectable_tables['getUsers'];
- }
- $root_table = reset($selectable_tables);
-
- $params = LiveUser_Admin_Storage::setSelectDefaultParams($params);
-
- return $this->_storage->select($params['select'], $params['fields'],
- $params['filters'], $params['orders'], $params['rekey'], $params['group'],
- $params['limit'], $params['offset'], $root_table, $selectable_tables);
- }
-
- /**
- * properly disconnect from resources
- *
- * @access public
- */
- function disconnect()
- {
- $this->_storage->disconnect();
- }
-}
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */
-
-/**
- * Auth Controller
- *
- * PHP versions 4 and 5
- *
- * LICENSE: This source file is subject to version 3.01 of the PHP license
- * that is available through the world-wide-web at the following URI:
- * http://www.php.net/license/3_01.txt. If you did not receive a copy of
- * the PHP License and are unable to obtain it through the web, please
- * send a note to license@php.net so we can mail you a copy immediately.
- *
- * @category Authentication
- * @package Auth
- * @author Yavor Shahpasov <yavo@netsmart.com.cy>
- * @author Adam Ashley <aashley@php.net>
- * @copyright 2001-2006 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version CVS: $Id: Controller.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- * @link http://pear.php.net/package/Auth
- * @since File available since Release 1.3.0
- */
-
-/**
- * Controlls access to a group of php access
- * and redirects to a predefined login page as
- * needed
- *
- * In all pages
- * <code>
- * include_once('Auth.php');
- * include_once('Auth/Controller.php');
- * $_auth = new Auth('File', 'passwd');
- * $authController = new Auth_Controller($_auth, 'login.php', 'index.php');
- * $authController->start();
- * </code>
- *
- * In login.php
- * <code>
- * include_once('Auth.php');
- * include_once('Auth/Controller.php');
- * $_auth = new Auth('File', 'passwd');
- * $authController = new Auth_Controller($_auth, 'login.php', 'index.php');
- * $authController->start();
- * if( $authController->isAuthorised() ){
- * $authController->redirectBack();
- * }
- * </code>
- *
- * @category Authentication
- * @author Yavor Shahpasov <yavo@netsmart.com.cy>
- * @author Adam Ashley <aashley@php.net>
- * @copyright 2001-2006 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version Release: 1.5.4 File: $Revision: 1.1.1.1 $
- * @link http://pear.php.net/package/Auth
- * @since Class available since Release 1.3.0
- */
-class Auth_Controller
-{
-
- // {{{ properties
-
- /**
- * The Auth instance this controller is managing
- *
- * @var object Auth
- */
- var $auth = null;
-
- /**
- * The login URL
- * @var string
- * */
- var $login = null;
-
- /**
- * The default index page to use when the caller page is not set
- *
- * @var string
- */
- var $default = null;
-
- /**
- * If this is set to true after a succesfull login the
- * Auth_Controller::redirectBack() is invoked automatically
- *
- * @var boolean
- */
- var $autoRedirectBack = false;
-
- // }}}
- // {{{ Auth_Controller() [constructor]
-
- /**
- * Constructor
- *
- * @param Auth An auth instance
- * @param string The login page
- * @param string The default page to go to if return page is not set
- * @param array Some rules about which urls need to be sent to the login page
- * @return void
- * @todo Add a list of urls which need redirection
- */
- function Auth_Controller(&$auth_obj, $login='login.php', $default='index.php', $accessList=array())
- {
- $this->auth =& $auth_obj;
- $this->_loginPage = $login;
- $this->_defaultPage = $default;
- @session_start();
- if (!empty($_GET['return']) && $_GET['return'] && !strstr($_GET['return'], $this->_loginPage)) {
- $this->auth->setAuthData('returnUrl', $_GET['return']);
- }
-
- if(!empty($_GET['authstatus']) && $this->auth->status == '') {
- $this->auth->status = $_GET['authstatus'];
- }
- }
-
- // }}}
- // {{{ setAutoRedirectBack()
-
- /**
- * Enables auto redirection when login is done
- *
- * @param bool Sets the autoRedirectBack flag to this
- * @see Auth_Controller::autoRedirectBack
- * @return void
- */
- function setAutoRedirectBack($flag = true)
- {
- $this->autoRedirectBack = $flag;
- }
-
- // }}}
- // {{{ redirectBack()
-
- /**
- * Redirects Back to the calling page
- *
- * @return void
- */
- function redirectBack()
- {
- // If redirectback go there
- // else go to the default page
-
- $returnUrl = $this->auth->getAuthData('returnUrl');
- if(!$returnUrl) {
- $returnUrl = $this->_defaultPage;
- }
-
- // Add some entropy to the return to make it unique
- // avoind problems with cached pages and proxies
- if(strpos($returnUrl, '?') === false) {
- $returnUrl .= '?';
- }
- $returnUrl .= uniqid('');
-
- // Track the auth status
- if($this->auth->status != '') {
- $url .= '&authstatus='.$this->auth->status;
- }
- header('Location:'.$returnUrl);
- print("You could not be redirected to <a href=\"$returnUrl\">$returnUrl</a>");
- }
-
- // }}}
- // {{{ redirectLogin()
-
- /**
- * Redirects to the login Page if not authorised
- *
- * put return page on the query or in auth
- *
- * @return void
- */
- function redirectLogin()
- {
- // Go to the login Page
-
- // For Auth, put some check to avoid infinite redirects, this should at least exclude
- // the login page
-
- $url = $this->_loginPage;
- if(strpos($url, '?') === false) {
- $url .= '?';
- }
-
- if(!strstr($_SERVER['PHP_SELF'], $this->_loginPage)) {
- $url .= 'return='.urlencode($_SERVER['PHP_SELF']);
- }
-
- // Track the auth status
- if($this->auth->status != '') {
- $url .= '&authstatus='.$this->auth->status;
- }
-
- header('Location:'.$url);
- print("You could not be redirected to <a href=\"$url\">$url</a>");
- }
-
- // }}}
- // {{{ start()
-
- /**
- * Starts the Auth Procedure
- *
- * If the page requires login the user is redirected to the login page
- * otherwise the Auth::start is called to initialize Auth
- *
- * @return void
- * @todo Implement an access list which specifies which urls/pages need login and which do not
- */
- function start()
- {
- // Check the accessList here
- // ACL should be a list of urls with allow/deny
- // If allow set allowLogin to false
- // Some wild card matching should be implemented ?,*
- if(!strstr($_SERVER['PHP_SELF'], $this->_loginPage) && !$this->auth->checkAuth()) {
- $this->redirectLogin();
- } else {
- $this->auth->start();
- // Logged on and on login page
- if(strstr($_SERVER['PHP_SELF'], $this->_loginPage) && $this->auth->checkAuth()){
- $this->autoRedirectBack ?
- $this->redirectBack() :
- null ;
- }
- }
-
-
- }
-
- // }}}
- // {{{ isAuthorised()
-
- /**
- * Checks is the user is logged on
- * @see Auth::checkAuth()
- */
- function isAuthorised()
- {
- return($this->auth->checkAuth());
- }
-
- // }}}
- // {{{ checkAuth()
-
- /**
- * Proxy call to auth
- * @see Auth::checkAuth()
- */
- function checkAuth()
- {
- return($this->auth->checkAuth());
- }
-
- // }}}
- // {{{ logout()
-
- /**
- * Proxy call to auth
- * @see Auth::logout()
- */
- function logout()
- {
- return($this->auth->logout());
- }
-
- // }}}
- // {{{ getUsername()
-
- /**
- * Proxy call to auth
- * @see Auth::getUsername()
- */
- function getUsername()
- {
- return($this->auth->getUsername());
- }
-
- // }}}
- // {{{ getStatus()
-
- /**
- * Proxy call to auth
- * @see Auth::getStatus()
- */
- function getStatus()
- {
- return($this->auth->getStatus());
- }
-
- // }}}
-
-}
-
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * A framework for authentication and authorization in PHP applications
- *
- * LiveUser_Admin is meant to be used with the LiveUser package.
- * It is composed of all the classes necessary to administrate
- * data used by LiveUser.
- *
- * You'll be able to add/edit/delete/get things like:
- * * Rights
- * * Users
- * * Groups
- * * Areas
- * * Applications
- * * Subgroups
- * * ImpliedRights
- *
- * And all other entities within LiveUser.
- *
- * At the moment we support the following storage containers:
- * * DB
- * * MDB
- * * MDB2
- *
- * But it takes no time to write up your own storage container,
- * so if you like to use native mysql functions straight, then it's possible
- * to do so in under a hour!
- *
- * PHP version 4 and 5
- *
- * LICENSE: This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library 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
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
- * MA 02111-1307 USA
- *
- *
- * @category authentication
- * @package LiveUser_Admin
- * @author Markus Wolff <wolff@21st.de>
- * @author Helgi Þormar Þorbjörnsson <dufuz@php.net>
- * @author Lukas Smith <smith@pooteeweet.org>
- * @author Arnaud Limbourg <arnaud@php.net>
- * @author Christian Dickmann <dickmann@php.net>
- * @author Matt Scifo <mscifo@php.net>
- * @author Bjoern Kraus <krausbn@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version CVS: $Id: DB.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- * @link http://pear.php.net/LiveUser_Admin
- */
-
-/**
- * DB admin container for maintaining Auth/DB
- *
- * @package LiveUser
- * @category authentication
- */
-
-/**
- * Require parent class definition and PEAR::DB class.
- */
-require_once 'LiveUser/Admin/Auth/Common.php';
-
-/**
- * This is a PEAR::DB backend container driver for the LiveUser Admin auth class.
- * It does not contain any logic and simply extends the common driver
- *
- * @category authentication
- * @package LiveUser_Admin
- * @author Bjoern Kraus <krausbn@php.net>
- * @author Lukas Smith <smith@pooteeweet.org>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version Release: @package_version@
- * @link http://pear.php.net/LiveUser_Admin
- */
-class LiveUser_Admin_Auth_DB extends LiveUser_Admin_Auth_Common
-{
-}
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * A framework for authentication and authorization in PHP applications
- *
- * LiveUser_Admin is meant to be used with the LiveUser package.
- * It is composed of all the classes necessary to administrate
- * data used by LiveUser.
- *
- * You'll be able to add/edit/delete/get things like:
- * * Rights
- * * Users
- * * Groups
- * * Areas
- * * Applications
- * * Subgroups
- * * ImpliedRights
- *
- * And all other entities within LiveUser.
- *
- * At the moment we support the following storage containers:
- * * DB
- * * MDB
- * * MDB2
- *
- * But it takes no time to write up your own storage container,
- * so if you like to use native mysql functions straight, then it's possible
- * to do so in under a hour!
- *
- * PHP version 4 and 5
- *
- * LICENSE: This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library 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
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
- * MA 02111-1307 USA
- *
- *
- * @category authentication
- * @package LiveUser_Admin
- * @author Markus Wolff <wolff@21st.de>
- * @author Helgi Þormar Þorbjörnsson <dufuz@php.net>
- * @author Lukas Smith <smith@pooteeweet.org>
- * @author Arnaud Limbourg <arnaud@php.net>
- * @author Christian Dickmann <dickmann@php.net>
- * @author Matt Scifo <mscifo@php.net>
- * @author Bjoern Kraus <krausbn@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version CVS: $Id: MDB.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- * @link http://pear.php.net/LiveUser_Admin
- */
-/**
- * MDB admin container for maintaining Auth/MDB
- *
- * @package LiveUser
- * @category authentication
- */
-
-/**
- * Require parent class definition and PEAR::MDB class.
- */
-require_once 'LiveUser/Admin/Auth/Common.php';
-
-/**
- * This is a PEAR::MDB backend container driver for the LiveUser Admin auth class.
- * It does not contain any logic and simply extends the common driver
- *
- * @category authentication
- * @package LiveUser_Admin
- * @author Lukas Smith <smith@pooteeweet.org>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version Release: @package_version@
- * @link http://pear.php.net/LiveUser_Admin
- */
-class LiveUser_Admin_Auth_MDB extends LiveUser_Admin_Auth_Common
-{
-}
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * A framework for authentication and authorization in PHP applications
- *
- * LiveUser_Admin is meant to be used with the LiveUser package.
- * It is composed of all the classes necessary to administrate
- * data used by LiveUser.
- *
- * You'll be able to add/edit/delete/get things like:
- * * Rights
- * * Users
- * * Groups
- * * Areas
- * * Applications
- * * Subgroups
- * * ImpliedRights
- *
- * And all other entities within LiveUser.
- *
- * At the moment we support the following storage containers:
- * * DB
- * * MDB
- * * MDB2
- *
- * But it takes no time to write up your own storage container,
- * so if you like to use native mysql functions straight, then it's possible
- * to do so in under a hour!
- *
- * PHP version 4 and 5
- *
- * LICENSE: This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library 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
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
- * MA 02111-1307 USA
- *
- *
- * @category authentication
- * @package LiveUser_Admin
- * @author Markus Wolff <wolff@21st.de>
- * @author Helgi Þormar Þorbjörnsson <dufuz@php.net>
- * @author Lukas Smith <smith@pooteeweet.org>
- * @author Arnaud Limbourg <arnaud@php.net>
- * @author Christian Dickmann <dickmann@php.net>
- * @author Matt Scifo <mscifo@php.net>
- * @author Bjoern Kraus <krausbn@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version CVS: $Id: MDB2.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- * @link http://pear.php.net/LiveUser_Admin
- */
-
-/**
- * Require parent class definition and PEAR::MDB2 class.
- */
-require_once 'LiveUser/Admin/Auth/Common.php';
-
-/**
- * This is a PEAR::MDB2 backend container driver for the LiveUser Admin auth class.
- * It does not contain any logic and simply extends the common driver
- *
- * @category authentication
- * @package LiveUser_Admin
- * @author Lukas Smith <smith@pooteeweet.org>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version Release: @package_version@
- * @link http://pear.php.net/LiveUser_Admin
- */
-class LiveUser_Admin_Auth_MDB2 extends LiveUser_Admin_Auth_Common
-{
-}
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * A framework for authentication and authorization in PHP applications
- *
- * LiveUser_Admin is meant to be used with the LiveUser package.
- * It is composed of all the classes necessary to administrate
- * data used by LiveUser.
- *
- * You'll be able to add/edit/delete/get things like:
- * * Rights
- * * Users
- * * Groups
- * * Areas
- * * Applications
- * * Subgroups
- * * ImpliedRights
- *
- * And all other entities within LiveUser.
- *
- * At the moment we support the following storage containers:
- * * DB
- * * MDB
- * * MDB2
- *
- * But it takes no time to write up your own storage container,
- * so if you like to use native mysql functions straight, then it's possible
- * to do so in under a hour!
- *
- * PHP version 4 and 5
- *
- * LICENSE: This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library 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
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
- * MA 02111-1307 USA
- *
- *
- * @category authentication
- * @package LiveUser_Admin
- * @author Markus Wolff <wolff@21st.de>
- * @author Helgi Þormar Þorbjörnsson <dufuz@php.net>
- * @author Lukas Smith <smith@pooteeweet.org>
- * @author Arnaud Limbourg <arnaud@php.net>
- * @author Christian Dickmann <dickmann@php.net>
- * @author Matt Scifo <mscifo@php.net>
- * @author Bjoern Kraus <krausbn@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version CVS: $Id: PDO.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- * @link http://pear.php.net/LiveUser_Admin
- */
-
-/**
- * PDO admin container for maintaining Auth/PDO
- *
- * @package LiveUser
- * @category authentication
- */
-
-/**
- * Require parent class definition and PEAR::DB class.
- */
-require_once 'LiveUser/Admin/Auth/Common.php';
-
-/**
- * This is a PECL::PDO backend container driver for the LiveUser Admin auth class.
- * It does not contain any logic and simply extends the common driver
- *
- * @category authentication
- * @package LiveUser_Admin
- * @author Bjoern Kraus <krausbn@php.net>
- * @author Lukas Smith <smith@pooteeweet.org>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version Release: @package_version@
- * @link http://pear.php.net/LiveUser_Admin
- */
-class LiveUser_Admin_Auth_PDO extends LiveUser_Admin_Auth_Common
-{
-}
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * A framework for authentication and authorization in PHP applications
- *
- * LiveUser is an authentication/permission framework designed
- * to be flexible and easily extendable.
- *
- * Since it is impossible to have a
- * "one size fits all" it takes a container
- * approach which should enable it to
- * be versatile enough to meet most needs.
- *
- * PHP version 4 and 5
- *
- * LICENSE: This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library 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
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
- * MA 02111-1307 USA
- *
- *
- * @category authentication
- * @package LiveUser
- * @author Markus Wolff <wolff@21st.de>
- * @author Helgi Þormar Þorbjörnsson <dufuz@php.net>
- * @author Lukas Smith <smith@pooteeweet.org>
- * @author Arnaud Limbourg <arnaud@php.net>
- * @author Pierre-Alain Joye <pajoye@php.net>
- * @author Bjoern Kraus <krausbn@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version CVS: $Id: PEARAuth.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- * @link http://pear.php.net/LiveUser
- */
-
-/**
- * Require parent class definition and PEAR::Auth class.
- */
-require_once 'LiveUser/Auth/Common.php';
-require_once 'Auth.php';
-
-/**
- * PEAR_Auth container for Authentication
- *
- * This is a PEAR::Auth backend driver for the LiveUser class.
- * The general options to setup the PEAR::Auth class can be passed to the constructor.
- * To choose the right auth container and options, you have to set 'container'
- * and 'options' respectively in the storage array.
- *
- * Requirements:
- * - File "LiveUser.php" (contains the parent class "LiveUser")
- * - PEAR::Auth must be installed in your PEAR directory
- * - Array of setup options must be passed to the constructor.
- *
- * @category authentication
- * @package LiveUser
- * @author Bjoern Kraus <krausbn@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version Release: @package_version@
- * @link http://pear.php.net/LiveUser
- */
-class LiveUser_Auth_PEARAuth extends LiveUser_Auth_Common
-{
- /**
- * Contains the PEAR::Auth object.
- *
- * @var Auth
- * @access private
- */
- var $pearAuth = false;
-
- /**
- * Contains name of the auth container
- *
- * @var string
- * @access private
- */
- var $container = false;
-
- /**
- * Contains array options
- *
- * @var array
- * @access private
- */
- var $options = false;
-
- /**
- * Load the storage container
- *
- * @param array array containing the configuration.
- * @param string name of the container that should be used
- * @return bool true on success or false on failure
- *
- * @access public
- */
- function init(&$conf, $containerName)
- {
- parent::init($conf, $containerName);
-
- if (!is_a($this->pearAuth, 'auth') && $this->container) {
- $pearAuth = &new Auth($this->container, $this->options, '', false);
- if (PEAR::isError($pearAuth)) {
- $this->stack->push(LIVEUSER_ERROR_INIT_ERROR, 'error',
- array('container' => 'could not connect: '.$pearAuth->getMessage(),
- 'debug' => $pearAuth->getUserInfo()));
- return false;
- }
- $this->pearAuth =& $pearAuth;
- }
-
- if (!is_a($this->pearAuth, 'auth')) {
- $this->stack->push(LIVEUSER_ERROR_INIT_ERROR, 'error',
- array('container' => 'storage layer configuration missing'));
- return false;
- }
-
- return true;
- }
-
- /**
- * Does nothing
- *
- * @return bool true on success or false on failure
- *
- * @access private
- */
- function _updateUserData()
- {
- return true;
- }
-
- /**
- * Reads user data from the given data source
- * Starts and verifies the PEAR::Auth login process
- *
- * @param string user handle
- * @param string user password
- * @param bool|int if the user data should be read using the auth user id
- * @return bool true on success or false on failure
- *
- * @access public
- */
- function readUserData($handle = '', $passwd = '', $auth_user_id = false)
- {
- $this->pearAuth->username = ($auth_user_id !== false) ? $auth_user_id : $handle;
- $this->pearAuth->password = $passwd;
- $this->pearAuth->start();
-
- if (!$this->pearAuth->getAuth()) {
- return null;
- }
-
- // User was found, read data into class variables and set return value to true
- $this->propertyValues['auth_user_id'] = $this->pearAuth->getUsername();
- $this->propertyValues['handle'] = $this->pearAuth->getUsername();
- $this->propertyValues['passwd'] = $this->encryptPW($this->pearAuth->password);
- if (!array_key_exists('is_active', $this->tables['users']['fields'])) {
- $this->propertyValues['is_active'] = true;
- }
- if (!array_key_exists('lastlogin', $this->tables['users']['fields'])) {
- $this->propertyValues['lastlogin'] = null;
- }
- return true;
- }
-}
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * A framework for authentication and authorization in PHP applications
- *
- * LiveUser is an authentication/permission framework designed
- * to be flexible and easily extendable.
- *
- * Since it is impossible to have a
- * "one size fits all" it takes a container
- * approach which should enable it to
- * be versatile enough to meet most needs.
- *
- * PHP version 4 and 5
- *
- * LICENSE: This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library 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
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
- * MA 02111-1307 USA
- *
- *
- * @category authentication
- * @package LiveUser
- * @author Markus Wolff <wolff@21st.de>
- * @author Helgi Þormar Þorbjörnsson <dufuz@php.net>
- * @author Lukas Smith <smith@pooteeweet.org>
- * @author Arnaud Limbourg <arnaud@php.net>
- * @author Pierre-Alain Joye <pajoye@php.net>
- * @author Bjoern Kraus <krausbn@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version CVS: $Id: Session.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- * @link http://pear.php.net/LiveUser
- */
-
-require_once 'LiveUser/Auth/Common.php';
-
-/**
- * Session based container for Authentication
- *
- * This is a backend driver for a simple session based anonymous LiveUser class.
- *
- * Requirements:
- * - File "LiveUser.php" (contains the parent class "LiveUser")
- *
- * @category authentication
- * @package LiveUser
- * @author Lukas Smith <smith@pooteeweet.org>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version Release: @package_version@
- * @link http://pear.php.net/LiveUser
- */
-class LiveUser_Auth_Session extends LiveUser_Auth_Common
-{
- /**
- * name of the key containing the Session phrase inside the auth session array
- *
- * @var string
- * @access public
- */
- var $sessionKey = 'password';
-
- /**
- * Load the storage container
- *
- * @param array array containing the configuration.
- * @param string name of the container that should be used
- * @return bool true on success or false on failure
- *
- * @access public
- */
- function init(&$conf, $containerName)
- {
- parent::init($conf, $containerName);
-
- return true;
- }
-
- /**
- * Does nothing
- *
- * @return bool true on success or false on failure
- *
- * @access private
- */
- function _updateUserData()
- {
- return true;
- }
-
- /**
- * Reads user data from the given data source
- * Compares $passwd with a string inside the $_SESSION array
- *
- * @param string user handle
- * @param string user password
- * @param bool|int if the user data should be read using the auth user id
- * @return bool true on success or false on failure
- *
- * @access public
- */
- function readUserData($handle = '', $passwd = '', $auth_user_id = false)
- {
- if (!$auth_user_id) {
- if (!is_null($this->tables['users']['fields']['passwd'])) {
- if (!array_key_exists($this->alias['passwd'], $_SESSION)
- || $_SESSION[$this->alias['passwd']] !== $passwd
- ) {
- return false;
- }
- }
- $this->propertyValues = $this->tables['users']['fields'];
- $this->propertyValues['handle'] = $handle;
- $this->propertyValues['passwd'] = $passwd;
- $this->propertyValues['is_active'] = true;
- $this->propertyValues['lastlogin'] = time();
- }
-
- return true;
- }
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * A framework for authentication and permorization in PHP applications
- *
- * LiveUser_Admin is meant to be used with the LiveUser package.
- * It is composed of all the classes necessary to administrate
- * data used by LiveUser.
- *
- * You'll be able to add/edit/delete/get things like:
- * * Rights
- * * Users
- * * Groups
- * * Areas
- * * Applications
- * * Subgroups
- * * ImpliedRights
- *
- * And all other entities within LiveUser.
- *
- * At the moment we support the following storage containers:
- * * DB
- * * MDB
- * * MDB2
- *
- * But it takes no time to write up your own storage container,
- * so if you like to use native mysql functions straight, then it's possible
- * to do so in under a hour!
- *
- * PHP version 4 and 5
- *
- * LICENSE: This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library 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
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
- * MA 02111-1307 USA
- *
- *
- * @category authentication
- * @package LiveUser_Admin
- * @permor Markus Wolff <wolff@21st.de>
- * @permor Helgi Þormar Þorbjörnsson <dufuz@php.net>
- * @permor Lukas Smith <smith@pooteeweet.org>
- * @permor Arnaud Limbourg <arnaud@php.net>
- * @permor Christian Dickmann <dickmann@php.net>
- * @permor Matt Scifo <mscifo@php.net>
- * @permor Bjoern Kraus <krausbn@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version CVS: $Id: DB.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- * @link http://pear.php.net/LiveUser_Admin
- */
-
-/**
- * Require parent class definition.
- */
-require_once 'LiveUser/Admin/Storage/DB.php';
-
-/**
- * This is a PEAR::DB backend storage driver for the LiveUser Admin auth class.
- * All it does is read the Globals.php file and the container and database config on
- *
- * @category authentication
- * @package LiveUser_Admin
- * @permor Lukas Smith <smith@pooteeweet.org>
- * @permor Bjoern Kraus <krausbn@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version Release: @package_version@
- * @link http://pear.php.net/LiveUser_Admin
- */
-class LiveUser_Admin_Auth_Storage_DB extends LiveUser_Admin_Storage_DB
-{
- /**
- * Initializes database storage container.
- *
- * @param array Storage Configuration
- * @return void
- *
- * @access public
- * @uses LiveUser_Admin_Storage_DB::init
- */
- function init(&$storageConf)
- {
- require_once 'LiveUser/Auth/Storage/Globals.php';
- parent::init($storageConf, $GLOBALS['_LiveUser']['auth']);
- }
-}
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * A framework for authentication and authorization in PHP applications
- *
- * LiveUser is an authentication/permission framework designed
- * to be flexible and easily extendable.
- *
- * Since it is impossible to have a
- * "one size fits all" it takes a container
- * approach which should enable it to
- * be versatile enough to meet most needs.
- *
- * PHP version 4 and 5
- *
- * LICENSE: This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library 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
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
- * MA 02111-1307 USA
- *
- *
- * @category authentication
- * @package LiveUser
- * @author Markus Wolff <wolff@21st.de>
- * @author Helgi Þormar Þorbjörnsson <dufuz@php.net>
- * @author Lukas Smith <smith@pooteeweet.org>
- * @author Arnaud Limbourg <arnaud@php.net>
- * @author Pierre-Alain Joye <pajoye@php.net>
- * @author Bjoern Kraus <krausbn@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version CVS: $Id: Globals.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- * @link http://pear.php.net/LiveUser
- */
-
-
-/**
- * This file holds all our default table/fields name/types/relations,
- * if they should be checked and more which are needed by both
- * LiveUser and LiveUser_Admin
- *
- * You can add to those table or modify options via our table/field
- * options in the config.
- */
-
-
-$GLOBALS['_LiveUser']['auth']['tables'] = array(
- 'users' => array(
- 'fields' => array(
- 'auth_user_id' => 'seq',
- 'handle' => 'unique',
- 'passwd' => true,
- ),
- ),
-);
-
-$GLOBALS['_LiveUser']['auth']['fields'] = array(
- 'auth_user_id' => 'text',
- 'handle' => 'text',
- 'passwd' => 'text',
-);
-
-$GLOBALS['_LiveUser']['auth']['alias'] = array(
- 'auth_user_id' => 'auth_user_id',
- 'handle' => 'handle',
- 'passwd' => 'passwd',
- 'users' => 'users',
-);
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * A framework for authentication and authorization in PHP applications
- *
- * LiveUser_Admin is meant to be used with the LiveUser package.
- * It is composed of all the classes necessary to administrate
- * data used by LiveUser.
- *
- * You'll be able to add/edit/delete/get things like:
- * * Rights
- * * Users
- * * Groups
- * * Areas
- * * Applications
- * * Subgroups
- * * ImpliedRights
- *
- * And all other entities within LiveUser.
- *
- * At the moment we support the following storage containers:
- * * DB
- * * MDB
- * * MDB2
- *
- * But it takes no time to write up your own storage container,
- * so if you like to use native mysql functions straight, then it's possible
- * to do so in under a hour!
- *
- * PHP version 4 and 5
- *
- * LICENSE: This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library 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
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
- * MA 02111-1307 USA
- *
- *
- * @category authentication
- * @package LiveUser_Admin
- * @author Markus Wolff <wolff@21st.de>
- * @author Helgi Þormar Þorbjörnsson <dufuz@php.net>
- * @author Lukas Smith <smith@pooteeweet.org>
- * @author Arnaud Limbourg <arnaud@php.net>
- * @author Christian Dickmann <dickmann@php.net>
- * @author Matt Scifo <mscifo@php.net>
- * @author Bjoern Kraus <krausbn@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version CVS: $Id: MDB.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- * @link http://pear.php.net/LiveUser_Admin
- */
-
-
-/**
- * Require parent class definition.
- */
-require_once 'LiveUser/Admin/Storage/MDB.php';
-
-/**
- * This is a PEAR::MDB backend storage driver for the LiveUser Admin auth class.
- * All it does is read the Globals.php file and the container and database config on
- *
- * @category authentication
- * @package LiveUser_Admin
- * @permor Lukas Smith <smith@pooteeweet.org>
- * @permor Bjoern Kraus <krausbn@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version Release: @package_version@
- * @link http://pear.php.net/LiveUser_Admin
- */
-class LiveUser_Admin_Auth_Storage_MDB extends LiveUser_Admin_Storage_MDB
-{
- /**
- * Initializes database storage container.
- *
- * @param array Storage Configuration
- * @return void
- *
- * @access public
- * @uses LiveUser_Admin_Storage_DB::init
- */
- function init(&$storageConf)
- {
- require_once 'LiveUser/Auth/Storage/Globals.php';
- parent::init($storageConf, $GLOBALS['_LiveUser']['auth']);
- }
-}
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * A framework for authentication and authorization in PHP applications
- *
- * LiveUser_Admin is meant to be used with the LiveUser package.
- * It is composed of all the classes necessary to administrate
- * data used by LiveUser.
- *
- * You'll be able to add/edit/delete/get things like:
- * * Rights
- * * Users
- * * Groups
- * * Areas
- * * Applications
- * * Subgroups
- * * ImpliedRights
- *
- * And all other entities within LiveUser.
- *
- * At the moment we support the following storage containers:
- * * DB
- * * MDB
- * * MDB2
- *
- * But it takes no time to write up your own storage container,
- * so if you like to use native mysql functions straight, then it's possible
- * to do so in under a hour!
- *
- * PHP version 4 and 5
- *
- * LICENSE: This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library 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
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
- * MA 02111-1307 USA
- *
- *
- * @category authentication
- * @package LiveUser_Admin
- * @author Markus Wolff <wolff@21st.de>
- * @author Helgi Þormar Þorbjörnsson <dufuz@php.net>
- * @author Lukas Smith <smith@pooteeweet.org>
- * @author Arnaud Limbourg <arnaud@php.net>
- * @author Christian Dickmann <dickmann@php.net>
- * @author Matt Scifo <mscifo@php.net>
- * @author Bjoern Kraus <krausbn@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version CVS: $Id: MDB2.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- * @link http://pear.php.net/LiveUser_Admin
- */
-
-
-/**
- * Require parent class definition.
- */
-require_once 'LiveUser/Admin/Storage/MDB2.php';
-
-/**
- * This is a PEAR::MDB2 backend storage driver for the LiveUser Admin auth class.
- * All it does is read the Globals.php file and the container and database config on
- *
- * @category authentication
- * @package LiveUser_Admin
- * @permor Lukas Smith <smith@pooteeweet.org>
- * @permor Bjoern Kraus <krausbn@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version Release: @package_version@
- * @link http://pear.php.net/LiveUser_Admin
- */
-class LiveUser_Admin_Auth_Storage_MDB2 extends LiveUser_Admin_Storage_MDB2
-{
- /**
- * Initializes database storage container.
- *
- * @param array Storage Configuration
- * @return void
- *
- * @access public
- * @uses LiveUser_Admin_Storage_DB::init
- */
- function init(&$storageConf)
- {
- require_once 'LiveUser/Auth/Storage/Globals.php';
- parent::init($storageConf, $GLOBALS['_LiveUser']['auth']);
- }
-}
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * A framework for authentication and permorization in PHP applications
- *
- * LiveUser_Admin is meant to be used with the LiveUser package.
- * It is composed of all the classes necessary to administrate
- * data used by LiveUser.
- *
- * You'll be able to add/edit/delete/get things like:
- * * Rights
- * * Users
- * * Groups
- * * Areas
- * * Applications
- * * Subgroups
- * * ImpliedRights
- *
- * And all other entities within LiveUser.
- *
- * At the moment we support the following storage containers:
- * * DB
- * * MDB
- * * MDB2
- *
- * But it takes no time to write up your own storage container,
- * so if you like to use native mysql functions straight, then it's possible
- * to do so in under a hour!
- *
- * PHP version 4 and 5
- *
- * LICENSE: This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library 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
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
- * MA 02111-1307 USA
- *
- *
- * @category authentication
- * @package LiveUser_Admin
- * @permor Markus Wolff <wolff@21st.de>
- * @permor Helgi Þormar Þorbjörnsson <dufuz@php.net>
- * @permor Lukas Smith <smith@pooteeweet.org>
- * @permor Arnaud Limbourg <arnaud@php.net>
- * @permor Christian Dickmann <dickmann@php.net>
- * @permor Matt Scifo <mscifo@php.net>
- * @permor Bjoern Kraus <krausbn@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version CVS: $Id: PDO.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- * @link http://pear.php.net/LiveUser_Admin
- */
-
-/**
- * Require parent class definition.
- */
-require_once 'LiveUser/Admin/Storage/PDO.php';
-
-/**
- * This is a PECL::PDO backend storage driver for the LiveUser Admin auth class.
- * All it does is read the Globals.php file and the container and database config on
- *
- * @category authentication
- * @package LiveUser_Admin
- * @permor Lukas Smith <smith@pooteeweet.org>
- * @permor Bjoern Kraus <krausbn@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version Release: @package_version@
- * @link http://pear.php.net/LiveUser_Admin
- */
-class LiveUser_Admin_Auth_Storage_PDO extends LiveUser_Admin_Storage_PDO
-{
- /**
- * Initializes database storage container.
- *
- * @param array Storage Configuration
- * @return void
- *
- * @access public
- * @uses LiveUser_Admin_Storage_PDO::init
- */
- function init(&$storageConf)
- {
- require_once 'LiveUser/Auth/Storage/Globals.php';
- parent::init($storageConf, $GLOBALS['_LiveUser']['auth']);
- }
-}
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * A framework for authentication and authorization in PHP applications
- *
- * LiveUser is an authentication/permission framework designed
- * to be flexible and easily extendable.
- *
- * Since it is impossible to have a
- * "one size fits all" it takes a container
- * approach which should enable it to
- * be versatile enough to meet most needs.
- *
- * PHP version 4 and 5
- *
- * LICENSE: This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library 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
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
- * MA 02111-1307 USA
- *
- *
- * @category authentication
- * @package LiveUser
- * @author Markus Wolff <wolff@21st.de>
- * @author Helgi Þormar Þorbjörnsson <dufuz@php.net>
- * @author Lukas Smith <smith@pooteeweet.org>
- * @author Arnaud Limbourg <arnaud@php.net>
- * @author Pierre-Alain Joye <pajoye@php.net>
- * @author Bjoern Kraus <krausbn@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version CVS: $Id: XML.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- * @link http://pear.php.net/LiveUser
- */
-
-/**
- * Require parent class definition and XML::Tree class.
- */
-require_once 'LiveUser/Auth/Common.php';
-require_once 'XML/Tree.php';
-
-/**
- * XML driver for authentication
- *
- * This is a XML backend driver for the LiveUser class.
- *
- * @category authentication
- * @package LiveUser
- * @author Björn Kraus <krausbn@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version Release: @package_version@
- * @link http://pear.php.net/LiveUser
- */
-class LiveUser_Auth_XML extends LiveUser_Auth_Common
-{
- /**
- * XML file in which the auth data is stored.
- *
- * @var string
- * @access private
- */
- var $file = '';
-
- /**
- * XML::Tree object.
- *
- * @var XML_Tree
- * @access private
- */
- var $tree = false;
-
- /**
- * XML::Tree object of the user logged in.
- *
- * @var XML_Tree
- * @access private
- * @see readUserData()
- */
- var $userObj = null;
-
- /**
- * Load the storage container
- *
- * @param array array containing the configuration.
- * @param string name of the container that should be used
- * @return bool true on success or false on failure
- *
- * @access public
- */
- function init(&$conf, $containerName)
- {
- parent::init($conf, $containerName);
-
- if (!is_file($this->file)) {
- if (!is_file(getenv('DOCUMENT_ROOT') . $this->file)) {
- $this->stack->push(LIVEUSER_ERROR_MISSING_DEPS, 'exception', array(),
- "Perm initialisation failed. Can't find xml file.");
- return false;
- }
- $this->file = getenv('DOCUMENT_ROOT') . $this->file;
- }
-
- $tree =& new XML_Tree($this->file);
- $err =& $tree->getTreeFromFile();
- if (PEAR::isError($err)) {
- $this->stack->push(LIVEUSER_ERROR, 'exception', array(),
- "Perm initialisation failed. Can't get tree from file");
- return false;
- }
- $this->tree =& $tree;
-
- if (!is_a($this->tree, 'xml_tree')) {
- $this->stack->push(LIVEUSER_ERROR_INIT_ERROR, 'error',
- array('container' => 'storage layer configuration missing'));
- return false;
- }
-
- return true;
- }
-
- /**
- * Writes current values for user back to the database.
- *
- * @return bool true on success or false on failure
- *
- * @access private
- */
- function _updateUserData()
- {
- if (!array_key_exists('lastlogin', $this->tables['users']['fields'])) {
- return true;
- }
-
- $index = 0;
- foreach ($this->userObj->children as $value) {
- if ($value->name == $this->alias['lastlogin']) {
- $el =& $this->userObj->getElement(array($index));
- $el->setContent($this->currentLogin);
- }
- $index++;
- }
-
- $success = false;
- do {
- if (!is_writable($this->file)) {
- $errorMsg = 'Auth freeze failure. Cannot write to the xml file';
- break;
- }
- $fp = fopen($this->file, 'wb');
- if (!$fp) {
- $errorMsg = "Auth freeze failure. Failed to open the xml file.";
- break;
- }
- if (!flock($fp, LOCK_EX)) {
- $errorMsg = "Auth freeze failure. Couldn't get an exclusive lock on the file.";
- break;
- }
- if (!fwrite($fp, $this->tree->get())) {
- $errorMsg = "Auth freeze failure. Write error when writing back the file.";
- break;
- }
- @fflush($fp);
- $success = true;
- } while (false);
-
- @flock($fp, LOCK_UN);
- @fclose($fp);
-
- if (!$success) {
- $this->stack->push(LIVEUSER_ERROR, 'exception',
- array(), 'Cannot read XML Auth file: '.$errorMsg);
- }
-
- return $success;
- }
-
- /**
- * Reads user data from the given data source
- * If only $handle is given, it will read the data
- * from the first user with that handle and return
- * true on success.
- * If $handle and $passwd are given, it will try to
- * find the first user with both handle and password
- * matching and return true on success (this allows
- * multiple users having the same handle but different
- * passwords - yep, some people want this).
- * if only an auth_user_id is passed it will try to read the data based on the id
- * If no match is found, false is being returned.
- *
- * @param string user handle
- * @param string user password
- * @param bool|int if the user data should be read using the auth user id
- * @return bool true on success or false on failure
- *
- * @access public
- */
- function readUserData($handle = '', $passwd = '', $auth_user_id = false)
- {
- $success = false;
- $index = 0;
-
- foreach ($this->tree->root->children as $user) {
- $result = array();
- $names = array_flip($this->alias);
- foreach ($user->children as $value) {
- if (array_key_exists($value->name, $names)) {
- $result[$names[$value->name]] = $value->content;
- }
- }
-
- if ($auth_user_id) {
- if (array_key_exists('auth_user_id', $result)
- && $auth_user_id === $result['auth_user_id']
- ) {
- $success = true;
- break;
- }
- } elseif (array_key_exists('handle', $result) && $handle === $result['handle']) {
- if (!is_null($this->tables['users']['fields']['passwd'])) {
- if (array_key_exists('passwd', $result)
- && $this->encryptPW($passwd) === $result['passwd']
- ) {
- $success = true;
- break;
- } elseif (is_string($this->tables['users']['fields']['handle'])) {
- // dont look for any further matching handles
- break;
- }
- } else {
- $success = true;
- break;
- }
- }
-
- $index++;
- }
-
- if (!$success) {
- return null;
- }
-
- $this->propertyValues = $result;
-
- $this->userObj =& $this->tree->root->getElement(array($index));
-
- return true;
- }
-
- /**
- * Properly disconnect from resources
- *
- * @return bool true on success or false on failure
- *
- * @access public
- */
- function disconnect()
- {
- $this->tree = false;
- $this->userObj = null;
- return true;
- }
-}
-?>
+++ /dev/null
-<?php
-
-/**
-* Fast, light and safe Cache Class
-*
-* Cache_Lite is a fast, light and safe cache system. It's optimized
-* for file containers. It is fast and safe (because it uses file
-* locking and/or anti-corruption tests).
-*
-* There are some examples in the 'docs/examples' file
-* Technical choices are described in the 'docs/technical' file
-*
-* Memory Caching is from an original idea of
-* Mike BENOIT <ipso@snappymail.ca>
-*
-* Nota : A chinese documentation (thanks to RainX <china_1982@163.com>) is
-* available at :
-* http://rainx.phpmore.com/manual/cache_lite.html
-*
-* @package Cache_Lite
-* @category Caching
-* @version $Id: Lite.php,v 1.1.1.1 2008/04/28 15:20:46 jamie Exp $
-* @author Fabien MARTY <fab@php.net>
-*/
-
-define('CACHE_LITE_ERROR_RETURN', 1);
-define('CACHE_LITE_ERROR_DIE', 8);
-
-class Cache_Lite
-{
-
- // --- Private properties ---
-
- /**
- * Directory where to put the cache files
- * (make sure to add a trailing slash)
- *
- * @var string $_cacheDir
- */
- var $_cacheDir = '/tmp/';
-
- /**
- * Enable / disable caching
- *
- * (can be very usefull for the debug of cached scripts)
- *
- * @var boolean $_caching
- */
- var $_caching = true;
-
- /**
- * Cache lifetime (in seconds)
- *
- * If null, the cache is valid forever.
- *
- * @var int $_lifeTime
- */
- var $_lifeTime = 3600;
-
- /**
- * Enable / disable fileLocking
- *
- * (can avoid cache corruption under bad circumstances)
- *
- * @var boolean $_fileLocking
- */
- var $_fileLocking = true;
-
- /**
- * Timestamp of the last valid cache
- *
- * @var int $_refreshTime
- */
- var $_refreshTime;
-
- /**
- * File name (with path)
- *
- * @var string $_file
- */
- var $_file;
-
- /**
- * File name (without path)
- *
- * @var string $_fileName
- */
- var $_fileName;
-
- /**
- * Enable / disable write control (the cache is read just after writing to detect corrupt entries)
- *
- * Enable write control will lightly slow the cache writing but not the cache reading
- * Write control can detect some corrupt cache files but maybe it's not a perfect control
- *
- * @var boolean $_writeControl
- */
- var $_writeControl = true;
-
- /**
- * Enable / disable read control
- *
- * If enabled, a control key is embeded in cache file and this key is compared with the one
- * calculated after the reading.
- *
- * @var boolean $_writeControl
- */
- var $_readControl = true;
-
- /**
- * Type of read control (only if read control is enabled)
- *
- * Available values are :
- * 'md5' for a md5 hash control (best but slowest)
- * 'crc32' for a crc32 hash control (lightly less safe but faster, better choice)
- * 'strlen' for a length only test (fastest)
- *
- * @var boolean $_readControlType
- */
- var $_readControlType = 'crc32';
-
- /**
- * Pear error mode (when raiseError is called)
- *
- * (see PEAR doc)
- *
- * @see setToDebug()
- * @var int $_pearErrorMode
- */
- var $_pearErrorMode = CACHE_LITE_ERROR_RETURN;
-
- /**
- * Current cache id
- *
- * @var string $_id
- */
- var $_id;
-
- /**
- * Current cache group
- *
- * @var string $_group
- */
- var $_group;
-
- /**
- * Enable / Disable "Memory Caching"
- *
- * NB : There is no lifetime for memory caching !
- *
- * @var boolean $_memoryCaching
- */
- var $_memoryCaching = false;
-
- /**
- * Enable / Disable "Only Memory Caching"
- * (be carefull, memory caching is "beta quality")
- *
- * @var boolean $_onlyMemoryCaching
- */
- var $_onlyMemoryCaching = false;
-
- /**
- * Memory caching array
- *
- * @var array $_memoryCachingArray
- */
- var $_memoryCachingArray = array();
-
- /**
- * Memory caching counter
- *
- * @var int $memoryCachingCounter
- */
- var $_memoryCachingCounter = 0;
-
- /**
- * Memory caching limit
- *
- * @var int $memoryCachingLimit
- */
- var $_memoryCachingLimit = 1000;
-
- /**
- * File Name protection
- *
- * if set to true, you can use any cache id or group name
- * if set to false, it can be faster but cache ids and group names
- * will be used directly in cache file names so be carefull with
- * special characters...
- *
- * @var boolean $fileNameProtection
- */
- var $_fileNameProtection = true;
-
- /**
- * Enable / disable automatic serialization
- *
- * it can be used to save directly datas which aren't strings
- * (but it's slower)
- *
- * @var boolean $_serialize
- */
- var $_automaticSerialization = false;
-
- /**
- * Disable / Tune the automatic cleaning process
- *
- * The automatic cleaning process destroy too old (for the given life time)
- * cache files when a new cache file is written.
- * 0 => no automatic cache cleaning
- * 1 => systematic cache cleaning
- * x (integer) > 1 => automatic cleaning randomly 1 times on x cache write
- *
- * @var int $_automaticCleaning
- */
- var $_automaticCleaningFactor = 0;
-
- /**
- * Nested directory level
- *
- * Set the hashed directory structure level. 0 means "no hashed directory
- * structure", 1 means "one level of directory", 2 means "two levels"...
- * This option can speed up Cache_Lite only when you have many thousands of
- * cache file. Only specific benchs can help you to choose the perfect value
- * for you. Maybe, 1 or 2 is a good start.
- *
- * @var int $_hashedDirectoryLevel
- */
- var $_hashedDirectoryLevel = 0;
-
- /**
- * Umask for hashed directory structure
- *
- * @var int $_hashedDirectoryUmask
- */
- var $_hashedDirectoryUmask = 0700;
-
- /**
- * API break for error handling in CACHE_LITE_ERROR_RETURN mode
- *
- * In CACHE_LITE_ERROR_RETURN mode, error handling was not good because
- * for example save() method always returned a boolean (a PEAR_Error object
- * would be better in CACHE_LITE_ERROR_RETURN mode). To correct this without
- * breaking the API, this option (false by default) can change this handling.
- *
- * @var boolean
- */
- var $_errorHandlingAPIBreak = false;
-
- // --- Public methods ---
-
- /**
- * Constructor
- *
- * $options is an assoc. Available options are :
- * $options = array(
- * 'cacheDir' => directory where to put the cache files (string),
- * 'caching' => enable / disable caching (boolean),
- * 'lifeTime' => cache lifetime in seconds (int),
- * 'fileLocking' => enable / disable fileLocking (boolean),
- * 'writeControl' => enable / disable write control (boolean),
- * 'readControl' => enable / disable read control (boolean),
- * 'readControlType' => type of read control 'crc32', 'md5', 'strlen' (string),
- * 'pearErrorMode' => pear error mode (when raiseError is called) (cf PEAR doc) (int),
- * 'memoryCaching' => enable / disable memory caching (boolean),
- * 'onlyMemoryCaching' => enable / disable only memory caching (boolean),
- * 'memoryCachingLimit' => max nbr of records to store into memory caching (int),
- * 'fileNameProtection' => enable / disable automatic file name protection (boolean),
- * 'automaticSerialization' => enable / disable automatic serialization (boolean),
- * 'automaticCleaningFactor' => distable / tune automatic cleaning process (int),
- * 'hashedDirectoryLevel' => level of the hashed directory system (int),
- * 'hashedDirectoryUmask' => umask for hashed directory structure (int),
- * 'errorHandlingAPIBreak' => API break for better error handling ? (boolean)
- * );
- *
- * @param array $options options
- * @access public
- */
- function Cache_Lite($options = array(NULL))
- {
- foreach($options as $key => $value) {
- $this->setOption($key, $value);
- }
- }
-
- /**
- * Generic way to set a Cache_Lite option
- *
- * see Cache_Lite constructor for available options
- *
- * @var string $name name of the option
- * @var mixed $value value of the option
- * @access public
- */
- function setOption($name, $value)
- {
- $availableOptions = array('errorHandlingAPIBreak', 'hashedDirectoryUmask', 'hashedDirectoryLevel', 'automaticCleaningFactor', 'automaticSerialization', 'fileNameProtection', 'memoryCaching', 'onlyMemoryCaching', 'memoryCachingLimit', 'cacheDir', 'caching', 'lifeTime', 'fileLocking', 'writeControl', 'readControl', 'readControlType', 'pearErrorMode');
- if (in_array($name, $availableOptions)) {
- $property = '_'.$name;
- $this->$property = $value;
- }
- }
-
- /**
- * Test if a cache is available and (if yes) return it
- *
- * @param string $id cache id
- * @param string $group name of the cache group
- * @param boolean $doNotTestCacheValidity if set to true, the cache validity won't be tested
- * @return string data of the cache (else : false)
- * @access public
- */
- function get($id, $group = 'default', $doNotTestCacheValidity = false)
- {
- $this->_id = $id;
- $this->_group = $group;
- $data = false;
- if ($this->_caching) {
- $this->_setRefreshTime();
- $this->_setFileName($id, $group);
- clearstatcache();
- if ($this->_memoryCaching) {
- if (isset($this->_memoryCachingArray[$this->_file])) {
- if ($this->_automaticSerialization) {
- return unserialize($this->_memoryCachingArray[$this->_file]);
- }
- return $this->_memoryCachingArray[$this->_file];
- }
- if ($this->_onlyMemoryCaching) {
- return false;
- }
- }
- if (($doNotTestCacheValidity) || (is_null($this->_refreshTime))) {
- if (file_exists($this->_file)) {
- $data = $this->_read();
- }
- } else {
- if ((file_exists($this->_file)) && (@filemtime($this->_file) > $this->_refreshTime)) {
- $data = $this->_read();
- }
- }
- if (($data) and ($this->_memoryCaching)) {
- $this->_memoryCacheAdd($data);
- }
- if (($this->_automaticSerialization) and (is_string($data))) {
- $data = unserialize($data);
- }
- return $data;
- }
- return false;
- }
-
- /**
- * Save some data in a cache file
- *
- * @param string $data data to put in cache (can be another type than strings if automaticSerialization is on)
- * @param string $id cache id
- * @param string $group name of the cache group
- * @return boolean true if no problem (else : false or a PEAR_Error object)
- * @access public
- */
- function save($data, $id = NULL, $group = 'default')
- {
- if ($this->_caching) {
- if ($this->_automaticSerialization) {
- $data = serialize($data);
- }
- if (isset($id)) {
- $this->_setFileName($id, $group);
- }
- if ($this->_memoryCaching) {
- $this->_memoryCacheAdd($data);
- if ($this->_onlyMemoryCaching) {
- return true;
- }
- }
- if ($this->_automaticCleaningFactor>0) {
- $rand = rand(1, $this->_automaticCleaningFactor);
- if ($rand==1) {
- $this->clean(false, 'old');
- }
- }
- if ($this->_writeControl) {
- $res = $this->_writeAndControl($data);
- if (is_bool($res)) {
- if ($res) {
- return true;
- }
- // if $res if false, we need to invalidate the cache
- @touch($this->_file, time() - 2*abs($this->_lifeTime));
- return false;
- }
- } else {
- $res = $this->_write($data);
- }
- if (is_object($res)) {
- // $res is a PEAR_Error object
- if (!($this->_errorHandlingAPIBreak)) {
- return false; // we return false (old API)
- }
- }
- return $res;
- }
- return false;
- }
-
- /**
- * Remove a cache file
- *
- * @param string $id cache id
- * @param string $group name of the cache group
- * @return boolean true if no problem
- * @access public
- */
- function remove($id, $group = 'default')
- {
- $this->_setFileName($id, $group);
- if ($this->_memoryCaching) {
- if (isset($this->_memoryCachingArray[$this->_file])) {
- unset($this->_memoryCachingArray[$this->_file]);
- $this->_memoryCachingCounter = $this->_memoryCachingCounter - 1;
- }
- if ($this->_onlyMemoryCaching) {
- return true;
- }
- }
- return $this->_unlink($this->_file);
- }
-
- /**
- * Clean the cache
- *
- * if no group is specified all cache files will be destroyed
- * else only cache files of the specified group will be destroyed
- *
- * @param string $group name of the cache group
- * @param string $mode flush cache mode : 'old', 'ingroup', 'notingroup',
- * 'callback_myFunction'
- * @return boolean true if no problem
- * @access public
- */
- function clean($group = false, $mode = 'ingroup')
- {
- return $this->_cleanDir($this->_cacheDir, $group, $mode);
- }
-
- /**
- * Set to debug mode
- *
- * When an error is found, the script will stop and the message will be displayed
- * (in debug mode only).
- *
- * @access public
- */
- function setToDebug()
- {
- $this->setOption('pearErrorMode', CACHE_LITE_ERROR_DIE);
- }
-
- /**
- * Set a new life time
- *
- * @param int $newLifeTime new life time (in seconds)
- * @access public
- */
- function setLifeTime($newLifeTime)
- {
- $this->_lifeTime = $newLifeTime;
- $this->_setRefreshTime();
- }
-
- /**
- * Save the state of the caching memory array into a cache file cache
- *
- * @param string $id cache id
- * @param string $group name of the cache group
- * @access public
- */
- function saveMemoryCachingState($id, $group = 'default')
- {
- if ($this->_caching) {
- $array = array(
- 'counter' => $this->_memoryCachingCounter,
- 'array' => $this->_memoryCachingArray
- );
- $data = serialize($array);
- $this->save($data, $id, $group);
- }
- }
-
- /**
- * Load the state of the caching memory array from a given cache file cache
- *
- * @param string $id cache id
- * @param string $group name of the cache group
- * @param boolean $doNotTestCacheValidity if set to true, the cache validity won't be tested
- * @access public
- */
- function getMemoryCachingState($id, $group = 'default', $doNotTestCacheValidity = false)
- {
- if ($this->_caching) {
- if ($data = $this->get($id, $group, $doNotTestCacheValidity)) {
- $array = unserialize($data);
- $this->_memoryCachingCounter = $array['counter'];
- $this->_memoryCachingArray = $array['array'];
- }
- }
- }
-
- /**
- * Return the cache last modification time
- *
- * BE CAREFUL : THIS METHOD IS FOR HACKING ONLY !
- *
- * @return int last modification time
- */
- function lastModified()
- {
- return @filemtime($this->_file);
- }
-
- /**
- * Trigger a PEAR error
- *
- * To improve performances, the PEAR.php file is included dynamically.
- * The file is so included only when an error is triggered. So, in most
- * cases, the file isn't included and perfs are much better.
- *
- * @param string $msg error message
- * @param int $code error code
- * @access public
- */
- function raiseError($msg, $code)
- {
- include_once('PEAR.php');
- return PEAR::raiseError($msg, $code, $this->_pearErrorMode);
- }
-
- /**
- * Extend the life of a valid cache file
- *
- * see http://pear.php.net/bugs/bug.php?id=6681
- *
- * @access public
- */
- function extendLife()
- {
- @touch($this->_file);
- }
-
- // --- Private methods ---
-
- /**
- * Compute & set the refresh time
- *
- * @access private
- */
- function _setRefreshTime()
- {
- if (is_null($this->_lifeTime)) {
- $this->_refreshTime = null;
- } else {
- $this->_refreshTime = time() - $this->_lifeTime;
- }
- }
-
- /**
- * Remove a file
- *
- * @param string $file complete file path and name
- * @return boolean true if no problem
- * @access private
- */
- function _unlink($file)
- {
- if (!@unlink($file)) {
- return $this->raiseError('Cache_Lite : Unable to remove cache !', -3);
- }
- return true;
- }
-
- /**
- * Recursive function for cleaning cache file in the given directory
- *
- * @param string $dir directory complete path (with a trailing slash)
- * @param string $group name of the cache group
- * @param string $mode flush cache mode : 'old', 'ingroup', 'notingroup',
- 'callback_myFunction'
- * @return boolean true if no problem
- * @access private
- */
- function _cleanDir($dir, $group = false, $mode = 'ingroup')
- {
- if ($this->_fileNameProtection) {
- $motif = ($group) ? 'cache_'.md5($group).'_' : 'cache_';
- } else {
- $motif = ($group) ? 'cache_'.$group.'_' : 'cache_';
- }
- if ($this->_memoryCaching) {
- foreach($this->_memoryCachingArray as $key => $v) {
- if (strpos($key, $motif) !== false) {
- unset($this->_memoryCachingArray[$key]);
- $this->_memoryCachingCounter = $this->_memoryCachingCounter - 1;
- }
- }
- if ($this->_onlyMemoryCaching) {
- return true;
- }
- }
- if (!($dh = opendir($dir))) {
- return $this->raiseError('Cache_Lite : Unable to open cache directory !', -4);
- }
- $result = true;
- while ($file = readdir($dh)) {
- if (($file != '.') && ($file != '..')) {
- if (substr($file, 0, 6)=='cache_') {
- $file2 = $dir . $file;
- if (is_file($file2)) {
- switch (substr($mode, 0, 9)) {
- case 'old':
- // files older than lifeTime get deleted from cache
- if (!is_null($this->_lifeTime)) {
- if ((mktime() - @filemtime($file2)) > $this->_lifeTime) {
- $result = ($result and ($this->_unlink($file2)));
- }
- }
- break;
- case 'notingrou':
- if (strpos($file2, $motif) === false) {
- $result = ($result and ($this->_unlink($file2)));
- }
- break;
- case 'callback_':
- $func = substr($mode, 9, strlen($mode) - 9);
- if ($func($file2, $group)) {
- $result = ($result and ($this->_unlink($file2)));
- }
- break;
- case 'ingroup':
- default:
- if (strpos($file2, $motif) !== false) {
- $result = ($result and ($this->_unlink($file2)));
- }
- break;
- }
- }
- if ((is_dir($file2)) and ($this->_hashedDirectoryLevel>0)) {
- $result = ($result and ($this->_cleanDir($file2 . '/', $group, $mode)));
- }
- }
- }
- }
- return $result;
- }
-
- /**
- * Add some date in the memory caching array
- *
- * @param string $data data to cache
- * @access private
- */
- function _memoryCacheAdd($data)
- {
- $this->_memoryCachingArray[$this->_file] = $data;
- if ($this->_memoryCachingCounter >= $this->_memoryCachingLimit) {
- list($key, ) = each($this->_memoryCachingArray);
- unset($this->_memoryCachingArray[$key]);
- } else {
- $this->_memoryCachingCounter = $this->_memoryCachingCounter + 1;
- }
- }
-
- /**
- * Make a file name (with path)
- *
- * @param string $id cache id
- * @param string $group name of the group
- * @access private
- */
- function _setFileName($id, $group)
- {
-
- if ($this->_fileNameProtection) {
- $suffix = 'cache_'.md5($group).'_'.md5($id);
- } else {
- $suffix = 'cache_'.$group.'_'.$id;
- }
- $root = $this->_cacheDir;
- if ($this->_hashedDirectoryLevel>0) {
- $hash = md5($suffix);
- for ($i=0 ; $i<$this->_hashedDirectoryLevel ; $i++) {
- $root = $root . 'cache_' . substr($hash, 0, $i + 1) . '/';
- }
- }
- $this->_fileName = $suffix;
- $this->_file = $root.$suffix;
- }
-
- /**
- * Read the cache file and return the content
- *
- * @return string content of the cache file (else : false or a PEAR_Error object)
- * @access private
- */
- function _read()
- {
- $fp = @fopen($this->_file, "rb");
- if ($this->_fileLocking) @flock($fp, LOCK_SH);
- if ($fp) {
- clearstatcache();
- $length = @filesize($this->_file);
- $mqr = get_magic_quotes_runtime();
- set_magic_quotes_runtime(0);
- if ($this->_readControl) {
- $hashControl = @fread($fp, 32);
- $length = $length - 32;
- }
- if ($length) {
- $data = @fread($fp, $length);
- } else {
- $data = '';
- }
- set_magic_quotes_runtime($mqr);
- if ($this->_fileLocking) @flock($fp, LOCK_UN);
- @fclose($fp);
- if ($this->_readControl) {
- $hashData = $this->_hash($data, $this->_readControlType);
- if ($hashData != $hashControl) {
- if (!(is_null($this->_lifeTime))) {
- @touch($this->_file, time() - 2*abs($this->_lifeTime));
- } else {
- @unlink($this->_file);
- }
- return false;
- }
- }
- return $data;
- }
- return $this->raiseError('Cache_Lite : Unable to read cache !', -2);
- }
-
- /**
- * Write the given data in the cache file
- *
- * @param string $data data to put in cache
- * @return boolean true if ok (a PEAR_Error object else)
- * @access private
- */
- function _write($data)
- {
- if ($this->_hashedDirectoryLevel > 0) {
- $hash = md5($this->_fileName);
- $root = $this->_cacheDir;
- for ($i=0 ; $i<$this->_hashedDirectoryLevel ; $i++) {
- $root = $root . 'cache_' . substr($hash, 0, $i + 1) . '/';
- if (!(@is_dir($root))) {
- @mkdir($root, $this->_hashedDirectoryUmask);
- }
- }
- }
- $fp = @fopen($this->_file, "wb");
- if ($fp) {
- if ($this->_fileLocking) @flock($fp, LOCK_EX);
- if ($this->_readControl) {
- @fwrite($fp, $this->_hash($data, $this->_readControlType), 32);
- }
- $mqr = get_magic_quotes_runtime();
- set_magic_quotes_runtime(0);
- @fwrite($fp, $data);
- set_magic_quotes_runtime($mqr);
- if ($this->_fileLocking) @flock($fp, LOCK_UN);
- @fclose($fp);
- return true;
- }
- return $this->raiseError('Cache_Lite : Unable to write cache file : '.$this->_file, -1);
- }
-
- /**
- * Write the given data in the cache file and control it just after to avoir corrupted cache entries
- *
- * @param string $data data to put in cache
- * @return boolean true if the test is ok (else : false or a PEAR_Error object)
- * @access private
- */
- function _writeAndControl($data)
- {
- $result = $this->_write($data);
- if (is_object($result)) {
- return $result; # We return the PEAR_Error object
- }
- $dataRead = $this->_read();
- if (is_object($dataRead)) {
- return $dataRead; # We return the PEAR_Error object
- }
- if ((is_bool($dataRead)) && (!$dataRead)) {
- return false;
- }
- return ($dataRead==$data);
- }
-
- /**
- * Make a control key with the string containing datas
- *
- * @param string $data data
- * @param string $controlType type of control 'md5', 'crc32' or 'strlen'
- * @return string control key
- * @access private
- */
- function _hash($data, $controlType)
- {
- switch ($controlType) {
- case 'md5':
- return md5($data);
- case 'crc32':
- return sprintf('% 32d', crc32($data));
- case 'strlen':
- return sprintf('% 32d', strlen($data));
- default:
- return $this->raiseError('Unknown controlType ! (available values are only \'md5\', \'crc32\', \'strlen\')', -5);
- }
- }
-
-}
-
-?>
+++ /dev/null
-<?php
-
-/**
-* This class extends Cache_Lite and offers a cache system driven by a master file
-*
-* With this class, cache validity is only dependent of a given file. Cache files
-* are valid only if they are older than the master file. It's a perfect way for
-* caching templates results (if the template file is newer than the cache, cache
-* must be rebuild...) or for config classes...
-* There are some examples in the 'docs/examples' file
-* Technical choices are described in the 'docs/technical' file
-*
-* @package Cache_Lite
-* @version $Id: File.php,v 1.1.1.1 2008/04/28 15:20:46 jamie Exp $
-* @author Fabien MARTY <fab@php.net>
-*/
-
-require_once('Cache/Lite.php');
-
-class Cache_Lite_File extends Cache_Lite
-{
-
- // --- Private properties ---
-
- /**
- * Complete path of the file used for controlling the cache lifetime
- *
- * @var string $_masterFile
- */
- var $_masterFile = '';
-
- /**
- * Masterfile mtime
- *
- * @var int $_masterFile_mtime
- */
- var $_masterFile_mtime = 0;
-
- // --- Public methods ----
-
- /**
- * Constructor
- *
- * $options is an assoc. To have a look at availables options,
- * see the constructor of the Cache_Lite class in 'Cache_Lite.php'
- *
- * Comparing to Cache_Lite constructor, there is another option :
- * $options = array(
- * (...) see Cache_Lite constructor
- * 'masterFile' => complete path of the file used for controlling the cache lifetime(string)
- * );
- *
- * @param array $options options
- * @access public
- */
- function Cache_Lite_File($options = array(NULL))
- {
- $options['lifetime'] = 0;
- $this->Cache_Lite($options);
- if (isset($options['masterFile'])) {
- $this->_masterFile = $options['masterFile'];
- } else {
- return $this->raiseError('Cache_Lite_File : masterFile option must be set !');
- }
- if (!($this->_masterFile_mtime = @filemtime($this->_masterFile))) {
- return $this->raiseError('Cache_Lite_File : Unable to read masterFile : '.$this->_masterFile, -3);
- }
- }
-
- /**
- * Test if a cache is available and (if yes) return it
- *
- * @param string $id cache id
- * @param string $group name of the cache group
- * @return string data of the cache (or false if no cache available)
- * @access public
- */
- function get($id, $group = 'default')
- {
- if ($data = parent::get($id, $group, true)) {
- if ($filemtime = $this->lastModified()) {
- if ($filemtime > $this->_masterFile_mtime) {
- return $data;
- }
- }
- }
- return false;
- }
-
-}
-
-?>
+++ /dev/null
-<?php
-
-/**
-* This class extends Cache_Lite and can be used to cache the result and output of functions/methods
-*
-* This class is completly inspired from Sebastian Bergmann's
-* PEAR/Cache_Function class. This is only an adaptation to
-* Cache_Lite
-*
-* There are some examples in the 'docs/examples' file
-* Technical choices are described in the 'docs/technical' file
-*
-* @package Cache_Lite
-* @version $Id: Function.php,v 1.1.1.1 2008/04/28 15:20:46 jamie Exp $
-* @author Sebastian BERGMANN <sb@sebastian-bergmann.de>
-* @author Fabien MARTY <fab@php.net>
-*/
-
-require_once('Cache/Lite.php');
-
-class Cache_Lite_Function extends Cache_Lite
-{
-
- // --- Private properties ---
-
- /**
- * Default cache group for function caching
- *
- * @var string $_defaultGroup
- */
- var $_defaultGroup = 'Cache_Lite_Function';
-
- /**
- * Don't cache the method call when its output contains the string "NOCACHE"
- *
- * if set to true, the output of the method will never be displayed (because the output is used
- * to control the cache)
- *
- * @var boolean $_dontCacheWhenTheOutputContainsNOCACHE
- */
- var $_dontCacheWhenTheOutputContainsNOCACHE = false;
-
- /**
- * Don't cache the method call when its result is false
- *
- * @var boolean $_dontCacheWhenTheResultIsFalse
- */
- var $_dontCacheWhenTheResultIsFalse = false;
-
- /**
- * Don't cache the method call when its result is null
- *
- * @var boolean $_dontCacheWhenTheResultIsNull
- */
- var $_dontCacheWhenTheResultIsNull = false;
-
- /**
- * Debug the Cache_Lite_Function caching process
- *
- * @var boolean $_debugCacheLiteFunction
- */
- var $_debugCacheLiteFunction = false;
-
- // --- Public methods ----
-
- /**
- * Constructor
- *
- * $options is an assoc. To have a look at availables options,
- * see the constructor of the Cache_Lite class in 'Cache_Lite.php'
- *
- * Comparing to Cache_Lite constructor, there is another option :
- * $options = array(
- * (...) see Cache_Lite constructor
- * 'debugCacheLiteFunction' => (bool) debug the caching process,
- * 'defaultGroup' => default cache group for function caching (string),
- * 'dontCacheWhenTheOutputContainsNOCACHE' => (bool) don't cache when the function output contains "NOCACHE",
- * 'dontCacheWhenTheResultIsFalse' => (bool) don't cache when the function result is false,
- * 'dontCacheWhenTheResultIsNull' => (bool don't cache when the function result is null
- * );
- *
- * @param array $options options
- * @access public
- */
- function Cache_Lite_Function($options = array(NULL))
- {
- $availableOptions = array('debugCacheLiteFunction', 'defaultGroup', 'dontCacheWhenTheOutputContainsNOCACHE', 'dontCacheWhenTheResultIsFalse', 'dontCacheWhenTheResultIsNull');
- while (list($name, $value) = each($options)) {
- if (in_array($name, $availableOptions)) {
- $property = '_'.$name;
- $this->$property = $value;
- }
- }
- reset($options);
- $this->Cache_Lite($options);
- }
-
- /**
- * Calls a cacheable function or method (or not if there is already a cache for it)
- *
- * Arguments of this method are read with func_get_args. So it doesn't appear
- * in the function definition. Synopsis :
- * call('functionName', $arg1, $arg2, ...)
- * (arg1, arg2... are arguments of 'functionName')
- *
- * @return mixed result of the function/method
- * @access public
- */
- function call()
- {
- $arguments = func_get_args();
- $id = $this->_makeId($arguments);
- $data = $this->get($id, $this->_defaultGroup);
- if ($data !== false) {
- if ($this->_debugCacheLiteFunction) {
- echo "Cache hit !\n";
- }
- $array = unserialize($data);
- $output = $array['output'];
- $result = $array['result'];
- } else {
- if ($this->_debugCacheLiteFunction) {
- echo "Cache missed !\n";
- }
- ob_start();
- ob_implicit_flush(false);
- $target = array_shift($arguments);
- if (is_array($target)) {
- // in this case, $target is for example array($obj, 'method')
- $object = $target[0];
- $method = $target[1];
- $result = call_user_func_array(array(&$object, $method), $arguments);
- } else {
- if (strstr($target, '::')) { // classname::staticMethod
- list($class, $method) = explode('::', $target);
- $result = call_user_func_array(array($class, $method), $arguments);
- } else if (strstr($target, '->')) { // object->method
- // use a stupid name ($objet_123456789 because) of problems where the object
- // name is the same as this var name
- list($object_123456789, $method) = explode('->', $target);
- global $$object_123456789;
- $result = call_user_func_array(array($$object_123456789, $method), $arguments);
- } else { // function
- $result = call_user_func_array($target, $arguments);
- }
- }
- $output = ob_get_contents();
- ob_end_clean();
- if ($this->_dontCacheWhenTheResultIsFalse) {
- if ((is_bool($result)) && (!($result))) {
- echo($output);
- return $result;
- }
- }
- if ($this->_dontCacheWhenTheResultIsNull) {
- if (is_null($result)) {
- echo($output);
- return $result;
- }
- }
- if ($this->_dontCacheWhenTheOutputContainsNOCACHE) {
- if (strpos($output, 'NOCACHE') > -1) {
- return $result;
- }
- }
- $array['output'] = $output;
- $array['result'] = $result;
- $this->save(serialize($array), $id, $this->_defaultGroup);
- }
- echo($output);
- return $result;
- }
-
- /**
- * Drop a cache file
- *
- * Arguments of this method are read with func_get_args. So it doesn't appear
- * in the function definition. Synopsis :
- * remove('functionName', $arg1, $arg2, ...)
- * (arg1, arg2... are arguments of 'functionName')
- *
- * @return boolean true if no problem
- * @access public
- */
- function drop()
- {
- $id = $this->_makeId(func_get_args());
- return $this->remove($id, $this->_defaultGroup);
- }
-
- /**
- * Make an id for the cache
- *
- * @var array result of func_get_args for the call() or the remove() method
- * @return string id
- * @access private
- */
- function _makeId($arguments)
- {
- $id = serialize($arguments); // Generate a cache id
- if (!$this->_fileNameProtection) {
- $id = md5($id);
- // if fileNameProtection is set to false, then the id has to be hashed
- // because it's a very bad file name in most cases
- }
- return $id;
- }
-
-}
-
-?>
+++ /dev/null
-<?php
-
-/**
-* This class extends Cache_Lite and uses output buffering to get the data to cache.
-*
-* There are some examples in the 'docs/examples' file
-* Technical choices are described in the 'docs/technical' file
-*
-* @package Cache_Lite
-* @version $Id: Output.php,v 1.1.1.1 2008/04/28 15:20:46 jamie Exp $
-* @author Fabien MARTY <fab@php.net>
-*/
-
-require_once('Cache/Lite.php');
-
-class Cache_Lite_Output extends Cache_Lite
-{
-
- // --- Public methods ---
-
- /**
- * Constructor
- *
- * $options is an assoc. To have a look at availables options,
- * see the constructor of the Cache_Lite class in 'Cache_Lite.php'
- *
- * @param array $options options
- * @access public
- */
- function Cache_Lite_Output($options)
- {
- $this->Cache_Lite($options);
- }
-
- /**
- * Start the cache
- *
- * @param string $id cache id
- * @param string $group name of the cache group
- * @param boolean $doNotTestCacheValidity if set to true, the cache validity won't be tested
- * @return boolean true if the cache is hit (false else)
- * @access public
- */
- function start($id, $group = 'default', $doNotTestCacheValidity = false)
- {
- $data = $this->get($id, $group, $doNotTestCacheValidity);
- if ($data !== false) {
- echo($data);
- return true;
- }
- ob_start();
- ob_implicit_flush(false);
- return false;
- }
-
- /**
- * Stop the cache
- *
- * @access public
- */
- function end()
- {
- $data = ob_get_contents();
- ob_end_clean();
- $this->save($data, $this->_id, $this->_group);
- echo($data);
- }
-
-}
-
-
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Harry Fuecks <hfuecks@phppatterns.com> |
-// | Lorenzo Alberton <l dot alberton at quipo dot it> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Calendar.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
-//
-/**
- * @package Calendar
- * @version $Id: Calendar.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- */
-
-/**
- * Allows Calendar include path to be redefined
- */
-if (!defined('CALENDAR_ROOT')) {
- define('CALENDAR_ROOT', 'Calendar'.DIRECTORY_SEPARATOR);
-}
-
-/**
- * Constant which defines the calculation engine to use
- */
-if (!defined('CALENDAR_ENGINE')) {
- define('CALENDAR_ENGINE', 'UnixTS');
-}
-
-/**
- * Define Calendar Month states
- */
-define('CALENDAR_USE_MONTH', 1);
-define('CALENDAR_USE_MONTH_WEEKDAYS', 2);
-define('CALENDAR_USE_MONTH_WEEKS', 3);
-
-/**
- * Contains a factory method to return a Singleton instance of a class
- * implementing the Calendar_Engine_Interface.<br>
- * <b>Note:</b> this class must be modified to "register" alternative
- * Calendar_Engines. The engine used can be controlled with the constant
- * CALENDAR_ENGINE
- * @see Calendar_Engine_Interface
- * @package Calendar
- * @access protected
- */
-class Calendar_Engine_Factory
-{
- /**
- * Returns an instance of the engine
- * @return object instance of a calendar calculation engine
- * @access protected
- */
- function & getEngine()
- {
- static $engine = false;
- switch (CALENDAR_ENGINE) {
- case 'PearDate':
- $class = 'Calendar_Engine_PearDate';
- break;
- case 'UnixTS':
- default:
- $class = 'Calendar_Engine_UnixTS';
- break;
- }
- if (!$engine) {
- if (!class_exists($class)) {
- require_once CALENDAR_ROOT.'Engine'.DIRECTORY_SEPARATOR.CALENDAR_ENGINE.'.php';
- }
- $engine = new $class;
- }
- return $engine;
- }
-}
-
-/**
- * Base class for Calendar API. This class should not be instantiated
- * directly.
- * @abstract
- * @package Calendar
- */
-class Calendar
-{
- /**
- * Instance of class implementing calendar engine interface
- * @var object
- * @access private
- */
- var $cE;
-
- /**
- * Instance of Calendar_Validator (lazy initialized when isValid() or
- * getValidor() is called
- * @var Calendar_Validator
- * @access private
- */
- var $validator;
-
- /**
- * Year for this calendar object e.g. 2003
- * @access private
- * @var int
- */
- var $year;
-
- /**
- * Month for this calendar object e.g. 9
- * @access private
- * @var int
- */
- var $month;
-
- /**
- * Day of month for this calendar object e.g. 23
- * @access private
- * @var int
- */
- var $day;
-
- /**
- * Hour of day for this calendar object e.g. 13
- * @access private
- * @var int
- */
- var $hour;
-
- /**
- * Minute of hour this calendar object e.g. 46
- * @access private
- * @var int
- */
- var $minute;
-
- /**
- * Second of minute this calendar object e.g. 34
- * @access private
- * @var int
- */
- var $second;
-
- /**
- * Marks this calendar object as selected (e.g. 'today')
- * @access private
- * @var boolean
- */
- var $selected = false;
-
- /**
- * Collection of child calendar objects created from subclasses
- * of Calendar. Type depends on the object which created them.
- * @access private
- * @var array
- */
- var $children = array();
-
- /**
- * Constructs the Calendar
- * @param int year
- * @param int month
- * @param int day
- * @param int hour
- * @param int minute
- * @param int second
- * @access protected
- */
- function Calendar($y = 2000, $m = 1, $d = 1, $h = 0, $i = 0, $s = 0)
- {
- static $cE = null;
- if (!isset($cE)) {
- $cE = & Calendar_Engine_Factory::getEngine();
- }
- $this->cE = & $cE;
- $this->year = (int)$y;
- $this->month = (int)$m;
- $this->day = (int)$d;
- $this->hour = (int)$h;
- $this->minute = (int)$i;
- $this->second = (int)$s;
- }
-
- /**
- * Defines the calendar by a timestamp (Unix or ISO-8601), replacing values
- * passed to the constructor
- * @param int|string Unix or ISO-8601 timestamp
- * @return void
- * @access public
- */
- function setTimestamp($ts)
- {
- $this->year = $this->cE->stampToYear($ts);
- $this->month = $this->cE->stampToMonth($ts);
- $this->day = $this->cE->stampToDay($ts);
- $this->hour = $this->cE->stampToHour($ts);
- $this->minute = $this->cE->stampToMinute($ts);
- $this->second = $this->cE->stampToSecond($ts);
- }
-
- /**
- * Returns a timestamp from the current date / time values. Format of
- * timestamp depends on Calendar_Engine implementation being used
- * @return int|string timestamp
- * @access public
- */
- function getTimestamp()
- {
- return $this->cE->dateToStamp(
- $this->year, $this->month, $this->day,
- $this->hour, $this->minute, $this->second);
- }
-
- /**
- * Defines calendar object as selected (e.g. for today)
- * @param boolean state whether Calendar subclass
- * @return void
- * @access public
- */
- function setSelected($state = true)
- {
- $this->selected = $state;
- }
-
- /**
- * True if the calendar subclass object is selected (e.g. today)
- * @return boolean
- * @access public
- */
- function isSelected()
- {
- return $this->selected;
- }
-
- /**
- * Adjusts the date (helper method)
- * @return void
- * @access public
- */
- function adjust()
- {
- $stamp = $this->getTimeStamp();
- $this->year = $this->cE->stampToYear($stamp);
- $this->month = $this->cE->stampToMonth($stamp);
- $this->day = $this->cE->stampToDay($stamp);
- $this->hour = $this->cE->stampToHour($stamp);
- $this->minute = $this->cE->stampToMinute($stamp);
- $this->second = $this->cE->stampToSecond($stamp);
- }
-
- /**
- * Returns the date as an associative array (helper method)
- * @param mixed timestamp (leave empty for current timestamp)
- * @return array
- * @access public
- */
- function toArray($stamp=null)
- {
- if (is_null($stamp)) {
- $stamp = $this->getTimeStamp();
- }
- return array(
- 'year' => $this->cE->stampToYear($stamp),
- 'month' => $this->cE->stampToMonth($stamp),
- 'day' => $this->cE->stampToDay($stamp),
- 'hour' => $this->cE->stampToHour($stamp),
- 'minute' => $this->cE->stampToMinute($stamp),
- 'second' => $this->cE->stampToSecond($stamp)
- );
- }
-
- /**
- * Returns the value as an associative array (helper method)
- * @param string type of date object that return value represents
- * @param string $format ['int' | 'array' | 'timestamp' | 'object']
- * @param mixed timestamp (depending on Calendar engine being used)
- * @param int integer default value (i.e. give me the answer quick)
- * @return mixed
- * @access private
- */
- function returnValue($returnType, $format, $stamp, $default)
- {
- switch (strtolower($format)) {
- case 'int':
- return $default;
- case 'array':
- return $this->toArray($stamp);
- break;
- case 'object':
- require_once CALENDAR_ROOT.'Factory.php';
- return Calendar_Factory::createByTimestamp($returnType,$stamp);
- break;
- case 'timestamp':
- default:
- return $stamp;
- break;
- }
- }
-
- /**
- * Abstract method for building the children of a calendar object.
- * Implemented by Calendar subclasses
- * @param array containing Calendar objects to select (optional)
- * @return boolean
- * @access public
- * @abstract
- */
- function build($sDates = array())
- {
- require_once 'PEAR.php';
- PEAR::raiseError(
- 'Calendar::build is abstract', null, PEAR_ERROR_TRIGGER,
- E_USER_NOTICE, 'Calendar::build()');
- return false;
- }
-
- /**
- * Abstract method for selected data objects called from build
- * @param array
- * @return boolean
- * @access public
- * @abstract
- */
- function setSelection($sDates)
- {
- require_once 'PEAR.php';
- PEAR::raiseError(
- 'Calendar::setSelection is abstract', null, PEAR_ERROR_TRIGGER,
- E_USER_NOTICE, 'Calendar::setSelection()');
- return false;
- }
-
- /**
- * Iterator method for fetching child Calendar subclass objects
- * (e.g. a minute from an hour object). On reaching the end of
- * the collection, returns false and resets the collection for
- * further iteratations.
- * @return mixed either an object subclass of Calendar or false
- * @access public
- */
- function fetch()
- {
- $child = each($this->children);
- if ($child) {
- return $child['value'];
- } else {
- reset($this->children);
- return false;
- }
- }
-
- /**
- * Fetches all child from the current collection of children
- * @return array
- * @access public
- */
- function fetchAll()
- {
- return $this->children;
- }
-
- /**
- * Get the number Calendar subclass objects stored in the internal
- * collection.
- * @return int
- * @access public
- */
- function size()
- {
- return count($this->children);
- }
-
- /**
- * Determine whether this date is valid, with the bounds determined by
- * the Calendar_Engine. The call is passed on to
- * Calendar_Validator::isValid
- * @return boolean
- * @access public
- */
- function isValid()
- {
- $validator = & $this->getValidator();
- return $validator->isValid();
- }
-
- /**
- * Returns an instance of Calendar_Validator
- * @return Calendar_Validator
- * @access public
- */
- function & getValidator()
- {
- if (!isset($this->validator)) {
- require_once CALENDAR_ROOT.'Validator.php';
- $this->validator = & new Calendar_Validator($this);
- }
- return $this->validator;
- }
-
- /**
- * Returns a reference to the current Calendar_Engine being used. Useful
- * for Calendar_Table_Helper and Calendar_Validator
- * @return object implementing Calendar_Engine_Inteface
- * @access protected
- */
- function & getEngine()
- {
- return $this->cE;
- }
-
- /**
- * Set the CALENDAR_FIRST_DAY_OF_WEEK constant to the $firstDay value
- * if the constant is not set yet.
- * @throws E_USER_WARNING this method throws a WARNING if the
- * CALENDAR_FIRST_DAY_OF_WEEK constant is already defined and
- * the $firstDay parameter is set to a different value
- * @param integer $firstDay first day of the week (0=sunday, 1=monday, ...)
- * @return integer
- * @access protected
- */
- function defineFirstDayOfWeek($firstDay = null)
- {
- if (defined('CALENDAR_FIRST_DAY_OF_WEEK')) {
- if (!is_null($firstDay) && ($firstDay != CALENDAR_FIRST_DAY_OF_WEEK)) {
- $msg = 'CALENDAR_FIRST_DAY_OF_WEEK constant already defined.'
- .' The $firstDay parameter will be ignored.';
- trigger_error($msg, E_USER_WARNING);
- }
- return CALENDAR_FIRST_DAY_OF_WEEK;
- }
- if (is_null($firstDay)) {
- $firstDay = $this->cE->getFirstDayOfWeek(
- $this->thisYear(),
- $this->thisMonth(),
- $this->thisDay()
- );
- }
- define ('CALENDAR_FIRST_DAY_OF_WEEK', $firstDay);
- return CALENDAR_FIRST_DAY_OF_WEEK;
- }
-
- /**
- * Returns the value for the previous year
- * @param string return value format ['int' | 'timestamp' | 'object' | 'array']
- * @return int e.g. 2002 or timestamp
- * @access public
- */
- function prevYear($format = 'int')
- {
- $ts = $this->cE->dateToStamp($this->year-1, 1, 1, 0, 0, 0);
- return $this->returnValue('Year', $format, $ts, $this->year-1);
- }
-
- /**
- * Returns the value for this year
- * @param string return value format ['int' | 'timestamp' | 'object' | 'array']
- * @return int e.g. 2003 or timestamp
- * @access public
- */
- function thisYear($format = 'int')
- {
- $ts = $this->cE->dateToStamp($this->year, 1, 1, 0, 0, 0);
- return $this->returnValue('Year', $format, $ts, $this->year);
- }
-
- /**
- * Returns the value for next year
- * @param string return value format ['int' | 'timestamp' | 'object' | 'array']
- * @return int e.g. 2004 or timestamp
- * @access public
- */
- function nextYear($format = 'int')
- {
- $ts = $this->cE->dateToStamp($this->year+1, 1, 1, 0, 0, 0);
- return $this->returnValue('Year', $format, $ts, $this->year+1);
- }
-
- /**
- * Returns the value for the previous month
- * @param string return value format ['int' | 'timestamp' | 'object' | 'array']
- * @return int e.g. 4 or Unix timestamp
- * @access public
- */
- function prevMonth($format = 'int')
- {
- $ts = $this->cE->dateToStamp($this->year, $this->month-1, 1, 0, 0, 0);
- return $this->returnValue('Month', $format, $ts, $this->cE->stampToMonth($ts));
- }
-
- /**
- * Returns the value for this month
- * @param string return value format ['int' | 'timestamp' | 'object' | 'array']
- * @return int e.g. 5 or timestamp
- * @access public
- */
- function thisMonth($format = 'int')
- {
- $ts = $this->cE->dateToStamp($this->year, $this->month, 1, 0, 0, 0);
- return $this->returnValue('Month', $format, $ts, $this->month);
- }
-
- /**
- * Returns the value for next month
- * @param string return value format ['int' | 'timestamp' | 'object' | 'array']
- * @return int e.g. 6 or timestamp
- * @access public
- */
- function nextMonth($format = 'int')
- {
- $ts = $this->cE->dateToStamp($this->year, $this->month+1, 1, 0, 0, 0);
- return $this->returnValue('Month', $format, $ts, $this->cE->stampToMonth($ts));
- }
-
- /**
- * Returns the value for the previous day
- * @param string return value format ['int' | 'timestamp' | 'object' | 'array']
- * @return int e.g. 10 or timestamp
- * @access public
- */
- function prevDay($format = 'int')
- {
- $ts = $this->cE->dateToStamp(
- $this->year, $this->month, $this->day-1, 0, 0, 0);
- return $this->returnValue('Day', $format, $ts, $this->cE->stampToDay($ts));
- }
-
- /**
- * Returns the value for this day
- * @param string return value format ['int' | 'timestamp' | 'object' | 'array']
- * @return int e.g. 11 or timestamp
- * @access public
- */
- function thisDay($format = 'int')
- {
- $ts = $this->cE->dateToStamp(
- $this->year, $this->month, $this->day, 0, 0, 0);
- return $this->returnValue('Day', $format, $ts, $this->day);
- }
-
- /**
- * Returns the value for the next day
- * @param string return value format ['int' | 'timestamp' | 'object' | 'array']
- * @return int e.g. 12 or timestamp
- * @access public
- */
- function nextDay($format = 'int')
- {
- $ts = $this->cE->dateToStamp(
- $this->year, $this->month, $this->day+1, 0, 0, 0);
- return $this->returnValue('Day', $format, $ts, $this->cE->stampToDay($ts));
- }
-
- /**
- * Returns the value for the previous hour
- * @param string return value format ['int' | 'timestamp' | 'object' | 'array']
- * @return int e.g. 13 or timestamp
- * @access public
- */
- function prevHour($format = 'int')
- {
- $ts = $this->cE->dateToStamp(
- $this->year, $this->month, $this->day, $this->hour-1, 0, 0);
- return $this->returnValue('Hour', $format, $ts, $this->cE->stampToHour($ts));
- }
-
- /**
- * Returns the value for this hour
- * @param string return value format ['int' | 'timestamp' | 'object' | 'array']
- * @return int e.g. 14 or timestamp
- * @access public
- */
- function thisHour($format = 'int')
- {
- $ts = $this->cE->dateToStamp(
- $this->year, $this->month, $this->day, $this->hour, 0, 0);
- return $this->returnValue('Hour', $format, $ts, $this->hour);
- }
-
- /**
- * Returns the value for the next hour
- * @param string return value format ['int' | 'timestamp' | 'object' | 'array']
- * @return int e.g. 14 or timestamp
- * @access public
- */
- function nextHour($format = 'int')
- {
- $ts = $this->cE->dateToStamp(
- $this->year, $this->month, $this->day, $this->hour+1, 0, 0);
- return $this->returnValue('Hour', $format, $ts, $this->cE->stampToHour($ts));
- }
-
- /**
- * Returns the value for the previous minute
- * @param string return value format ['int' | 'timestamp' | 'object' | 'array']
- * @return int e.g. 23 or timestamp
- * @access public
- */
- function prevMinute($format = 'int')
- {
- $ts = $this->cE->dateToStamp(
- $this->year, $this->month, $this->day,
- $this->hour, $this->minute-1, 0);
- return $this->returnValue('Minute', $format, $ts, $this->cE->stampToMinute($ts));
- }
-
- /**
- * Returns the value for this minute
- * @param string return value format ['int' | 'timestamp' | 'object' | 'array']
- * @return int e.g. 24 or timestamp
- * @access public
- */
- function thisMinute($format = 'int')
- {
- $ts = $this->cE->dateToStamp(
- $this->year, $this->month, $this->day,
- $this->hour, $this->minute, 0);
- return $this->returnValue('Minute', $format, $ts, $this->minute);
- }
-
- /**
- * Returns the value for the next minute
- * @param string return value format ['int' | 'timestamp' | 'object' | 'array']
- * @return int e.g. 25 or timestamp
- * @access public
- */
- function nextMinute($format = 'int')
- {
- $ts = $this->cE->dateToStamp(
- $this->year, $this->month, $this->day,
- $this->hour, $this->minute+1, 0);
- return $this->returnValue('Minute', $format, $ts, $this->cE->stampToMinute($ts));
- }
-
- /**
- * Returns the value for the previous second
- * @param string return value format ['int' | 'timestamp' | 'object' | 'array']
- * @return int e.g. 43 or timestamp
- * @access public
- */
- function prevSecond($format = 'int')
- {
- $ts = $this->cE->dateToStamp(
- $this->year, $this->month, $this->day,
- $this->hour, $this->minute, $this->second-1);
- return $this->returnValue('Second', $format, $ts, $this->cE->stampToSecond($ts));
- }
-
- /**
- * Returns the value for this second
- * @param string return value format ['int' | 'timestamp' | 'object' | 'array']
- * @return int e.g. 44 or timestamp
- * @access public
- */
- function thisSecond($format = 'int')
- {
- $ts = $this->cE->dateToStamp(
- $this->year, $this->month, $this->day,
- $this->hour, $this->minute, $this->second);
- return $this->returnValue('Second', $format, $ts, $this->second);
- }
-
- /**
- * Returns the value for the next second
- * @param string return value format ['int' | 'timestamp' | 'object' | 'array']
- * @return int e.g. 45 or timestamp
- * @access public
- */
- function nextSecond($format = 'int')
- {
- $ts = $this->cE->dateToStamp(
- $this->year, $this->month, $this->day,
- $this->hour, $this->minute, $this->second+1);
- return $this->returnValue('Second', $format, $ts, $this->cE->stampToSecond($ts));
- }
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Harry Fuecks <hfuecks@phppatterns.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Day.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
-//
-/**
- * @package Calendar
- * @version $Id: Day.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- */
-
-/**
- * Allows Calendar include path to be redefined
- * @ignore
- */
-if (!defined('CALENDAR_ROOT')) {
- define('CALENDAR_ROOT', 'Calendar'.DIRECTORY_SEPARATOR);
-}
-
-/**
- * Load Calendar base class
- */
-require_once CALENDAR_ROOT.'Calendar.php';
-
-/**
- * Represents a Day and builds Hours.
- * <code>
- * require_once 'Calendar'.DIRECTORY_SEPARATOR.'Day.php';
- * $Day = & new Calendar_Day(2003, 10, 21); // Oct 21st 2003
- * while ($Hour = & $Day->fetch()) {
- * echo $Hour->thisHour().'<br />';
- * }
- * </code>
- * @package Calendar
- * @access public
- */
-class Calendar_Day extends Calendar
-{
- /**
- * Marks the Day at the beginning of a week
- * @access private
- * @var boolean
- */
- var $first = false;
-
- /**
- * Marks the Day at the end of a week
- * @access private
- * @var boolean
- */
- var $last = false;
-
-
- /**
- * Used for tabular calendars
- * @access private
- * @var boolean
- */
- var $empty = false;
-
- /**
- * Constructs Calendar_Day
- * @param int year e.g. 2003
- * @param int month e.g. 8
- * @param int day e.g. 15
- * @access public
- */
- function Calendar_Day($y, $m, $d)
- {
- Calendar::Calendar($y, $m, $d);
- }
-
- /**
- * Builds the Hours of the Day
- * @param array (optional) Caledar_Hour objects representing selected dates
- * @return boolean
- * @access public
- */
- function build($sDates = array())
- {
- require_once CALENDAR_ROOT.'Hour.php';
-
- $hID = $this->cE->getHoursInDay($this->year, $this->month, $this->day);
- for ($i=0; $i < $hID; $i++) {
- $this->children[$i]=
- new Calendar_Hour($this->year, $this->month, $this->day, $i);
- }
- if (count($sDates) > 0) {
- $this->setSelection($sDates);
- }
- return true;
- }
-
- /**
- * Called from build()
- * @param array
- * @return void
- * @access private
- */
- function setSelection($sDates)
- {
- foreach ($sDates as $sDate) {
- if ($this->year == $sDate->thisYear()
- && $this->month == $sDate->thisMonth()
- && $this->day == $sDate->thisDay())
- {
- $key = (int)$sDate->thisHour();
- if (isset($this->children[$key])) {
- $sDate->setSelected();
- $this->children[$key] = $sDate;
- }
- }
- }
- }
-
- /**
- * Defines Day object as first in a week
- * Only used by Calendar_Month_Weekdays::build()
- * @param boolean state
- * @return void
- * @access private
- */
- function setFirst ($state = true)
- {
- $this->first = $state;
- }
-
- /**
- * Defines Day object as last in a week
- * Used only following Calendar_Month_Weekdays::build()
- * @param boolean state
- * @return void
- * @access private
- */
- function setLast($state = true)
- {
- $this->last = $state;
- }
-
- /**
- * Returns true if Day object is first in a Week
- * Only relevant when Day is created by Calendar_Month_Weekdays::build()
- * @return boolean
- * @access public
- */
- function isFirst() {
- return $this->first;
- }
-
- /**
- * Returns true if Day object is last in a Week
- * Only relevant when Day is created by Calendar_Month_Weekdays::build()
- * @return boolean
- * @access public
- */
- function isLast()
- {
- return $this->last;
- }
-
- /**
- * Defines Day object as empty
- * Only used by Calendar_Month_Weekdays::build()
- * @param boolean state
- * @return void
- * @access private
- */
- function setEmpty ($state = true)
- {
- $this->empty = $state;
- }
-
- /**
- * @return boolean
- * @access public
- */
- function isEmpty()
- {
- return $this->empty;
- }
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Harry Fuecks <hfuecks@phppatterns.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Decorator.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
-//
-/**
- * @package Calendar
- * @version $Id: Decorator.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- */
-/**
- * Decorates any calendar class.
- * Create a subclass of this class for your own "decoration".
- * Used for "selections"
- * <code>
- * class DayDecorator extends Calendar_Decorator
- * {
- * function thisDay($format = 'int')
- * {
-.* $day = parent::thisDay('timestamp');
-.* return date('D', $day);
- * }
- * }
- * $Day = & new Calendar_Day(2003, 10, 25);
- * $DayDecorator = & new DayDecorator($Day);
- * echo $DayDecorator->thisDay(); // Outputs "Sat"
- * </code>
- * @abstract
- * @package Calendar
- */
-class Calendar_Decorator
-{
- /**
- * Subclass of Calendar being decorated
- * @var object
- * @access private
- */
- var $calendar;
-
- /**
- * Constructs the Calendar_Decorator
- * @param object subclass to Calendar to decorate
- */
- function Calendar_Decorator(& $calendar)
- {
- $this->calendar = & $calendar;
- }
-
- /**
- * Defines the calendar by a Unix timestamp, replacing values
- * passed to the constructor
- * @param int Unix timestamp
- * @return void
- * @access public
- */
- function setTimestamp($ts)
- {
- $this->calendar->setTimestamp($ts);
- }
-
- /**
- * Returns a timestamp from the current date / time values. Format of
- * timestamp depends on Calendar_Engine implementation being used
- * @return int timestamp
- * @access public
- */
- function getTimestamp()
- {
- return $this->calendar->getTimeStamp();
- }
-
- /**
- * Defines calendar object as selected (e.g. for today)
- * @param boolean state whether Calendar subclass
- * @return void
- * @access public
- */
- function setSelected($state = true)
- {
- $this->calendar->setSelected($state = true);
- }
-
- /**
- * True if the calendar subclass object is selected (e.g. today)
- * @return boolean
- * @access public
- */
- function isSelected()
- {
- return $this->calendar->isSelected();
- }
-
- /**
- * Adjusts the date (helper method)
- * @return void
- * @access public
- */
- function adjust()
- {
- $this->calendar->adjust();
- }
-
- /**
- * Returns the date as an associative array (helper method)
- * @param mixed timestamp (leave empty for current timestamp)
- * @return array
- * @access public
- */
- function toArray($stamp=null)
- {
- return $this->calendar->toArray($stamp);
- }
-
- /**
- * Returns the value as an associative array (helper method)
- * @param string type of date object that return value represents
- * @param string $format ['int' | 'array' | 'timestamp' | 'object']
- * @param mixed timestamp (depending on Calendar engine being used)
- * @param int integer default value (i.e. give me the answer quick)
- * @return mixed
- * @access private
- */
- function returnValue($returnType, $format, $stamp, $default)
- {
- return $this->calendar->returnValue($returnType, $format, $stamp, $default);
- }
-
- /**
- * Defines Day object as first in a week
- * Only used by Calendar_Month_Weekdays::build()
- * @param boolean state
- * @return void
- * @access private
- */
- function setFirst ($state = true)
- {
- if ( method_exists($this->calendar,'setFirst') ) {
- $this->calendar->setFirst($state);
- }
- }
-
- /**
- * Defines Day object as last in a week
- * Used only following Calendar_Month_Weekdays::build()
- * @param boolean state
- * @return void
- * @access private
- */
- function setLast($state = true)
- {
- if ( method_exists($this->calendar,'setLast') ) {
- $this->calendar->setLast($state);
- }
- }
-
- /**
- * Returns true if Day object is first in a Week
- * Only relevant when Day is created by Calendar_Month_Weekdays::build()
- * @return boolean
- * @access public
- */
- function isFirst() {
- if ( method_exists($this->calendar,'isFirst') ) {
- return $this->calendar->isFirst();
- }
- }
-
- /**
- * Returns true if Day object is last in a Week
- * Only relevant when Day is created by Calendar_Month_Weekdays::build()
- * @return boolean
- * @access public
- */
- function isLast()
- {
- if ( method_exists($this->calendar,'isLast') ) {
- return $this->calendar->isLast();
- }
- }
-
- /**
- * Defines Day object as empty
- * Only used by Calendar_Month_Weekdays::build()
- * @param boolean state
- * @return void
- * @access private
- */
- function setEmpty ($state = true)
- {
- if ( method_exists($this->calendar,'setEmpty') ) {
- $this->calendar->setEmpty($state);
- }
- }
-
- /**
- * @return boolean
- * @access public
- */
- function isEmpty()
- {
- if ( method_exists($this->calendar,'isEmpty') ) {
- return $this->calendar->isEmpty();
- }
- }
-
- /**
- * Build the children
- * @param array containing Calendar objects to select (optional)
- * @return boolean
- * @access public
- * @abstract
- */
- function build($sDates = array())
- {
- $this->calendar->build($sDates);
- }
-
- /**
- * Iterator method for fetching child Calendar subclass objects
- * (e.g. a minute from an hour object). On reaching the end of
- * the collection, returns false and resets the collection for
- * further iteratations.
- * @return mixed either an object subclass of Calendar or false
- * @access public
- */
- function fetch()
- {
- return $this->calendar->fetch();
- }
-
- /**
- * Fetches all child from the current collection of children
- * @return array
- * @access public
- */
- function fetchAll()
- {
- return $this->calendar->fetchAll();
- }
-
- /**
- * Get the number Calendar subclass objects stored in the internal
- * collection.
- * @return int
- * @access public
- */
- function size()
- {
- return $this->calendar->size();
- }
-
- /**
- * Determine whether this date is valid, with the bounds determined by
- * the Calendar_Engine. The call is passed on to
- * Calendar_Validator::isValid
- * @return boolean
- * @access public
- */
- function isValid()
- {
- return $this->calendar->isValid();
- }
-
- /**
- * Returns an instance of Calendar_Validator
- * @return Calendar_Validator
- * @access public
- */
- function & getValidator()
- {
- $validator = $this->calendar->getValidator();
- return $validator;
- }
-
- /**
- * Returns a reference to the current Calendar_Engine being used. Useful
- * for Calendar_Table_Helper and Calendar_Validator
- * @return object implementing Calendar_Engine_Inteface
- * @access private
- */
- function & getEngine()
- {
- return $this->calendar->getEngine();
- }
-
- /**
- * Returns the value for the previous year
- * @param string return value format ['int' | 'timestamp' | 'object' | 'array']
- * @return int e.g. 2002 or timestamp
- * @access public
- */
- function prevYear($format = 'int')
- {
- return $this->calendar->prevYear($format);
- }
-
- /**
- * Returns the value for this year
- * @param string return value format ['int' | 'timestamp' | 'object' | 'array']
- * @return int e.g. 2003 or timestamp
- * @access public
- */
- function thisYear($format = 'int')
- {
- return $this->calendar->thisYear($format);
- }
-
- /**
- * Returns the value for next year
- * @param string return value format ['int' | 'timestamp' | 'object' | 'array']
- * @return int e.g. 2004 or timestamp
- * @access public
- */
- function nextYear($format = 'int')
- {
- return $this->calendar->nextYear($format);
- }
-
- /**
- * Returns the value for the previous month
- * @param string return value format ['int' | 'timestamp' | 'object' | 'array']
- * @return int e.g. 4 or Unix timestamp
- * @access public
- */
- function prevMonth($format = 'int')
- {
- return $this->calendar->prevMonth($format);
- }
-
- /**
- * Returns the value for this month
- * @param string return value format ['int' | 'timestamp' | 'object' | 'array']
- * @return int e.g. 5 or timestamp
- * @access public
- */
- function thisMonth($format = 'int')
- {
- return $this->calendar->thisMonth($format);
- }
-
- /**
- * Returns the value for next month
- * @param string return value format ['int' | 'timestamp' | 'object' | 'array']
- * @return int e.g. 6 or timestamp
- * @access public
- */
- function nextMonth($format = 'int')
- {
- return $this->calendar->nextMonth($format);
- }
-
- /**
- * Returns the value for the previous week
- * @param string return value format ['int' | 'timestamp' | 'object' | 'array']
- * @return int e.g. 4 or Unix timestamp
- * @access public
- */
- function prevWeek($format = 'n_in_month')
- {
- if ( method_exists($this->calendar,'prevWeek') ) {
- return $this->calendar->prevWeek($format);
- } else {
- require_once 'PEAR.php';
- PEAR::raiseError(
- 'Cannot call prevWeek on Calendar object of type: '.
- get_class($this->calendar), 133, PEAR_ERROR_TRIGGER,
- E_USER_NOTICE, 'Calendar_Decorator::prevWeek()');
- return false;
- }
- }
-
- /**
- * Returns the value for this week
- * @param string return value format ['int' | 'timestamp' | 'object' | 'array']
- * @return int e.g. 5 or timestamp
- * @access public
- */
- function thisWeek($format = 'n_in_month')
- {
- if ( method_exists($this->calendar,'thisWeek') ) {
- return $this->calendar->thisWeek($format);
- } else {
- require_once 'PEAR.php';
- PEAR::raiseError(
- 'Cannot call thisWeek on Calendar object of type: '.
- get_class($this->calendar), 133, PEAR_ERROR_TRIGGER,
- E_USER_NOTICE, 'Calendar_Decorator::thisWeek()');
- return false;
- }
- }
-
- /**
- * Returns the value for next week
- * @param string return value format ['int' | 'timestamp' | 'object' | 'array']
- * @return int e.g. 6 or timestamp
- * @access public
- */
- function nextWeek($format = 'n_in_month')
- {
- if ( method_exists($this->calendar,'nextWeek') ) {
- return $this->calendar->nextWeek($format);
- } else {
- require_once 'PEAR.php';
- PEAR::raiseError(
- 'Cannot call thisWeek on Calendar object of type: '.
- get_class($this->calendar), 133, PEAR_ERROR_TRIGGER,
- E_USER_NOTICE, 'Calendar_Decorator::nextWeek()');
- return false;
- }
- }
-
- /**
- * Returns the value for the previous day
- * @param string return value format ['int' | 'timestamp' | 'object' | 'array']
- * @return int e.g. 10 or timestamp
- * @access public
- */
- function prevDay($format = 'int') {
- return $this->calendar->prevDay($format);
- }
-
- /**
- * Returns the value for this day
- * @param string return value format ['int' | 'timestamp' | 'object' | 'array']
- * @return int e.g. 11 or timestamp
- * @access public
- */
- function thisDay($format = 'int')
- {
- return $this->calendar->thisDay($format);
- }
-
- /**
- * Returns the value for the next day
- * @param string return value format ['int' | 'timestamp' | 'object' | 'array']
- * @return int e.g. 12 or timestamp
- * @access public
- */
- function nextDay($format = 'int')
- {
- return $this->calendar->nextDay($format);
- }
-
- /**
- * Returns the value for the previous hour
- * @param string return value format ['int' | 'timestamp' | 'object' | 'array']
- * @return int e.g. 13 or timestamp
- * @access public
- */
- function prevHour($format = 'int')
- {
- return $this->calendar->prevHour($format);
- }
-
- /**
- * Returns the value for this hour
- * @param string return value format ['int' | 'timestamp' | 'object' | 'array']
- * @return int e.g. 14 or timestamp
- * @access public
- */
- function thisHour($format = 'int')
- {
- return $this->calendar->thisHour($format);
- }
-
- /**
- * Returns the value for the next hour
- * @param string return value format ['int' | 'timestamp' | 'object' | 'array']
- * @return int e.g. 14 or timestamp
- * @access public
- */
- function nextHour($format = 'int')
- {
- return $this->calendar->nextHour($format);
- }
-
- /**
- * Returns the value for the previous minute
- * @param string return value format ['int' | 'timestamp' | 'object' | 'array']
- * @return int e.g. 23 or timestamp
- * @access public
- */
- function prevMinute($format = 'int')
- {
- return $this->calendar->prevMinute($format);
- }
-
- /**
- * Returns the value for this minute
- * @param string return value format ['int' | 'timestamp' | 'object' | 'array']
- * @return int e.g. 24 or timestamp
- * @access public
- */
- function thisMinute($format = 'int')
- {
- return $this->calendar->thisMinute($format);
- }
-
- /**
- * Returns the value for the next minute
- * @param string return value format ['int' | 'timestamp' | 'object' | 'array']
- * @return int e.g. 25 or timestamp
- * @access public
- */
- function nextMinute($format = 'int')
- {
- return $this->calendar->nextMinute($format);
- }
-
- /**
- * Returns the value for the previous second
- * @param string return value format ['int' | 'timestamp' | 'object' | 'array']
- * @return int e.g. 43 or timestamp
- * @access public
- */
- function prevSecond($format = 'int')
- {
- return $this->calendar->prevSecond($format);
- }
-
- /**
- * Returns the value for this second
- * @param string return value format ['int' | 'timestamp' | 'object' | 'array']
- * @return int e.g. 44 or timestamp
- * @access public
- */
- function thisSecond($format = 'int')
- {
- return $this->calendar->thisSecond($format);
- }
-
- /**
- * Returns the value for the next second
- * @param string return value format ['int' | 'timestamp' | 'object' | 'array']
- * @return int e.g. 45 or timestamp
- * @access public
- */
- function nextSecond($format = 'int')
- {
- return $this->calendar->nextSecond($format);
- }
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Harry Fuecks <hfuecks@phppatterns.com> |
-// | Lorenzo Alberton <l dot alberton at quipo dot it> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Textual.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
-//
-/**
- * @package Calendar
- * @version $Id: Textual.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- */
-
-/**
- * Allows Calendar include path to be redefined
- * @ignore
- */
-if (!defined('CALENDAR_ROOT')) {
- define('CALENDAR_ROOT', 'Calendar'.DIRECTORY_SEPARATOR);
-}
-
-/**
- * Load Calendar decorator base class
- */
-require_once CALENDAR_ROOT.'Decorator.php';
-
-/**
- * Load the Uri utility
- */
-require_once CALENDAR_ROOT.'Util'.DIRECTORY_SEPARATOR.'Textual.php';
-
-/**
- * Decorator to help with fetching textual representations of months and
- * days of the week.
- * <b>Note:</b> for performance you should prefer Calendar_Util_Textual unless you
- * have a specific need to use a decorator
- * @package Calendar
- * @access public
- */
-class Calendar_Decorator_Textual extends Calendar_Decorator
-{
- /**
- * Constructs Calendar_Decorator_Textual
- * @param object subclass of Calendar
- * @access public
- */
- function Calendar_Decorator_Textual(&$Calendar)
- {
- parent::Calendar_Decorator($Calendar);
- }
-
- /**
- * Returns an array of 12 month names (first index = 1)
- * @param string (optional) format of returned months (one,two,short or long)
- * @return array
- * @access public
- * @static
- */
- function monthNames($format='long')
- {
- return Calendar_Util_Textual::monthNames($format);
- }
-
- /**
- * Returns an array of 7 week day names (first index = 0)
- * @param string (optional) format of returned days (one,two,short or long)
- * @return array
- * @access public
- * @static
- */
- function weekdayNames($format='long')
- {
- return Calendar_Util_Textual::weekdayNames($format);
- }
-
- /**
- * Returns textual representation of the previous month of the decorated calendar object
- * @param string (optional) format of returned months (one,two,short or long)
- * @return string
- * @access public
- */
- function prevMonthName($format='long')
- {
- return Calendar_Util_Textual::prevMonthName($this->calendar,$format);
- }
-
- /**
- * Returns textual representation of the month of the decorated calendar object
- * @param string (optional) format of returned months (one,two,short or long)
- * @return string
- * @access public
- */
- function thisMonthName($format='long')
- {
- return Calendar_Util_Textual::thisMonthName($this->calendar,$format);
- }
-
- /**
- * Returns textual representation of the next month of the decorated calendar object
- * @param string (optional) format of returned months (one,two,short or long)
- * @return string
- * @access public
- */
- function nextMonthName($format='long')
- {
- return Calendar_Util_Textual::nextMonthName($this->calendar,$format);
- }
-
- /**
- * Returns textual representation of the previous day of week of the decorated calendar object
- * @param string (optional) format of returned months (one,two,short or long)
- * @return string
- * @access public
- */
- function prevDayName($format='long')
- {
- return Calendar_Util_Textual::prevDayName($this->calendar,$format);
- }
-
- /**
- * Returns textual representation of the day of week of the decorated calendar object
- * @param string (optional) format of returned months (one,two,short or long)
- * @return string
- * @access public
- */
- function thisDayName($format='long')
- {
- return Calendar_Util_Textual::thisDayName($this->calendar,$format);
- }
-
- /**
- * Returns textual representation of the next day of week of the decorated calendar object
- * @param string (optional) format of returned months (one,two,short or long)
- * @return string
- * @access public
- */
- function nextDayName($format='long')
- {
- return Calendar_Util_Textual::nextDayName($this->calendar,$format);
- }
-
- /**
- * Returns the days of the week using the order defined in the decorated
- * calendar object. Only useful for Calendar_Month_Weekdays, Calendar_Month_Weeks
- * and Calendar_Week. Otherwise the returned array will begin on Sunday
- * @param string (optional) format of returned months (one,two,short or long)
- * @return array ordered array of week day names
- * @access public
- */
- function orderedWeekdays($format='long')
- {
- return Calendar_Util_Textual::orderedWeekdays($this->calendar,$format);
- }
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Harry Fuecks <hfuecks@phppatterns.com> |
-// | Lorenzo Alberton <l dot alberton at quipo dot it> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Uri.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
-//
-/**
- * @package Calendar
- * @version $Id: Uri.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- */
-
-/**
- * Allows Calendar include path to be redefined
- * @ignore
- */
-if (!defined('CALENDAR_ROOT')) {
- define('CALENDAR_ROOT', 'Calendar'.DIRECTORY_SEPARATOR);
-}
-
-/**
- * Load Calendar decorator base class
- */
-require_once CALENDAR_ROOT.'Decorator.php';
-
-/**
- * Load the Uri utility
- */
-require_once CALENDAR_ROOT.'Util'.DIRECTORY_SEPARATOR.'Uri.php';
-
-/**
- * Decorator to help with building HTML links for navigating the calendar<br />
- * <b>Note:</b> for performance you should prefer Calendar_Util_Uri unless you
- * have a specific need to use a decorator
- * <code>
- * $Day = new Calendar_Day(2003, 10, 23);
- * $Uri = & new Calendar_Decorator_Uri($Day);
- * $Uri->setFragments('year', 'month', 'day');
- * echo $Uri->getPrev(); // Displays year=2003&month=10&day=22
- * </code>
- * @see Calendar_Util_Uri
- * @package Calendar
- * @access public
- */
-class Calendar_Decorator_Uri extends Calendar_Decorator
-{
-
- /**
- * @var Calendar_Util_Uri
- * @access private
- */
- var $Uri;
-
- /**
- * Constructs Calendar_Decorator_Uri
- * @param object subclass of Calendar
- * @access public
- */
- function Calendar_Decorator_Uri(&$Calendar)
- {
- parent::Calendar_Decorator($Calendar);
- }
-
- /**
- * Sets the URI fragment names
- * @param string URI fragment for year
- * @param string (optional) URI fragment for month
- * @param string (optional) URI fragment for day
- * @param string (optional) URI fragment for hour
- * @param string (optional) URI fragment for minute
- * @param string (optional) URI fragment for second
- * @return void
- * @access public
- */
- function setFragments($y, $m=null, $d=null, $h=null, $i=null, $s=null) {
- $this->Uri = & new Calendar_Util_Uri($y, $m, $d, $h, $i, $s);
- }
-
- /**
- * Sets the separator string between fragments
- * @param string separator e.g. /
- * @return void
- * @access public
- */
- function setSeparator($separator)
- {
- $this->Uri->separator = $separator;
- }
-
- /**
- * Puts Uri decorator into "scalar mode" - URI variable names are not
- * returned
- * @param boolean (optional)
- * @return void
- * @access public
- */
- function setScalar($state=true)
- {
- $this->Uri->scalar = $state;
- }
-
- /**
- * Gets the URI string for the previous calendar unit
- * @param string calendar unit to fetch uri for (year,month,week or day etc)
- * @return string
- * @access public
- */
- function prev($method)
- {
- return $this->Uri->prev($this, $method);
- }
-
- /**
- * Gets the URI string for the current calendar unit
- * @param string calendar unit to fetch uri for (year,month,week or day etc)
- * @return string
- * @access public
- */
- function this($method)
- {
- return $this->Uri->this($this, $method);
- }
-
- /**
- * Gets the URI string for the next calendar unit
- * @param string calendar unit to fetch uri for (year,month,week or day etc)
- * @return string
- * @access public
- */
- function next($method)
- {
- return $this->Uri->next($this, $method);
- }
-
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Harry Fuecks <hfuecks@phppatterns.com> |
-// | Lorenzo Alberton <l dot alberton at quipo dot it> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Weekday.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
-//
-/**
- * @package Calendar
- * @version $Id: Weekday.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- */
-
-/**
- * Allows Calendar include path to be redefined
- * @ignore
- */
-if (!defined('CALENDAR_ROOT')) {
- define('CALENDAR_ROOT', 'Calendar'.DIRECTORY_SEPARATOR);
-}
-
-/**
- * Load Calendar decorator base class
- */
-require_once CALENDAR_ROOT.'Decorator.php';
-
-/**
- * Load a Calendar_Day
- */
-require_once CALENDAR_ROOT.'Day.php';
-/**
- * Decorator for fetching the day of the week
- * <code>
- * $Day = new Calendar_Day(2003, 10, 23);
- * $Weekday = & new Calendar_Decorator_Weekday($Day);
- * $Weekday->setFirstDay(0); // Set first day of week to Sunday (default Mon)
- * echo $Weekday->thisWeekDay(); // Displays 5 - fifth day of week relative to Sun
- * </code>
- * @package Calendar
- * @access public
- */
-class Calendar_Decorator_Weekday extends Calendar_Decorator
-{
- /**
- * First day of week
- * @var int (default = 1 for Monday)
- * @access private
- */
- var $firstDay = 1;
-
- /**
- * Constructs Calendar_Decorator_Weekday
- * @param object subclass of Calendar
- * @access public
- */
- function Calendar_Decorator_Weekday(& $Calendar)
- {
- parent::Calendar_Decorator($Calendar);
- }
-
- /**
- * Sets the first day of the week (0 = Sunday, 1 = Monday (default) etc)
- * @param int first day of week
- * @return void
- * @access public
- */
- function setFirstDay($firstDay) {
- $this->firstDay = (int)$firstDay;
- }
-
- /**
- * Returns the previous weekday
- * @param string (default = 'int') return value format
- * @return int numeric day of week or timestamp
- * @access public
- */
- function prevWeekDay($format = 'int')
- {
- $ts = $this->calendar->prevDay('timestamp');
- $Day = new Calendar_Day(2000,1,1);
- $Day->setTimeStamp($ts);
- $day = $this->calendar->cE->getDayOfWeek($Day->thisYear(),$Day->thisMonth(),$Day->thisDay());
- $day = $this->adjustWeekScale($day);
- return $this->returnValue('Day', $format, $ts, $day);
- }
-
- /**
- * Returns the current weekday
- * @param string (default = 'int') return value format
- * @return int numeric day of week or timestamp
- * @access public
- */
- function thisWeekDay($format = 'int')
- {
- $ts = $this->calendar->thisDay('timestamp');
- $day = $this->calendar->cE->getDayOfWeek($this->calendar->year,$this->calendar->month,$this->calendar->day);
- $day = $this->adjustWeekScale($day);
- return $this->returnValue('Day', $format, $ts, $day);
- }
-
- /**
- * Returns the next weekday
- * @param string (default = 'int') return value format
- * @return int numeric day of week or timestamp
- * @access public
- */
- function nextWeekDay($format = 'int')
- {
- $ts = $this->calendar->nextDay('timestamp');
- $Day = new Calendar_Day(2000,1,1);
- $Day->setTimeStamp($ts);
- $day = $this->calendar->cE->getDayOfWeek($Day->thisYear(),$Day->thisMonth(),$Day->thisDay());
- $day = $this->adjustWeekScale($day);
- return $this->returnValue('Day', $format, $ts, $day);
- }
-
- /**
- * Adjusts the day of the week relative to the first day of the week
- * @param int day of week calendar from Calendar_Engine
- * @return int day of week adjusted to first day
- * @access private
- */
- function adjustWeekScale($dayOfWeek) {
- $dayOfWeek = $dayOfWeek - $this->firstDay;
- if ( $dayOfWeek >= 0 ) {
- return $dayOfWeek;
- } else {
- return $this->calendar->cE->getDaysInWeek(
- $this->calendar->year,$this->calendar->month,$this->calendar->day
- ) + $dayOfWeek;
- }
- }
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Harry Fuecks <hfuecks@phppatterns.com> |
-// | Lorenzo Alberton <l dot alberton at quipo dot it> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Wrapper.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
-//
-/**
- * @package Calendar
- * @version $Id: Wrapper.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- */
-
-/**
- * Allows Calendar include path to be redefined
- * @ignore
- */
-if (!defined('CALENDAR_ROOT')) {
- define('CALENDAR_ROOT', 'Calendar'.DIRECTORY_SEPARATOR);
-}
-
-/**
- * Load Calendar decorator base class
- */
-require_once CALENDAR_ROOT.'Decorator.php';
-
-/**
- * Decorator to help with wrapping built children in another decorator
- * @package Calendar
- * @access public
- */
-class Calendar_Decorator_Wrapper extends Calendar_Decorator
-{
- /**
- * Constructs Calendar_Decorator_Wrapper
- * @param object subclass of Calendar
- * @access public
- */
- function Calendar_Decorator_Wrapper(&$Calendar)
- {
- parent::Calendar_Decorator($Calendar);
- }
-
- /**
- * Wraps objects returned from fetch in the named Decorator class
- * @param string name of Decorator class to wrap with
- * @return object instance of named decorator
- * @access public
- */
- function & fetch($decorator)
- {
- $Calendar = parent::fetch();
- if ($Calendar) {
- $ret =& new $decorator($Calendar);
- } else {
- $ret = false;
- }
- return $ret;
- }
-
- /**
- * Wraps the returned calendar objects from fetchAll in the named decorator
- * @param string name of Decorator class to wrap with
- * @return array
- * @access public
- */
- function fetchAll($decorator)
- {
- $children = parent::fetchAll();
- foreach ($children as $key => $Calendar) {
- $children[$key] = & new $decorator($Calendar);
- }
- return $children;
- }
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Harry Fuecks <hfuecks@phppatterns.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Interface.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
-//
-/**
- * @package Calendar
- * @version $Id: Interface.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- */
-/**
- * The methods the classes implementing the Calendar_Engine must implement.
- * Note this class is not used but simply to help development
- * @package Calendar
- * @access protected
- */
-class Calendar_Engine_Interface
-{
- /**
- * Provides a mechansim to make sure parsing of timestamps
- * into human dates is only performed once per timestamp.
- * Typically called "internally" by methods like stampToYear.
- * Return value can vary, depending on the specific implementation
- * @param int timestamp (depending on implementation)
- * @return mixed
- * @access protected
- */
- function stampCollection($stamp)
- {
- }
-
- /**
- * Returns a numeric year given a timestamp
- * @param int timestamp (depending on implementation)
- * @return int year (e.g. 2003)
- * @access protected
- */
- function stampToYear($stamp)
- {
- }
-
- /**
- * Returns a numeric month given a timestamp
- * @param int timestamp (depending on implementation)
- * @return int month (e.g. 9)
- * @access protected
- */
- function stampToMonth($stamp)
- {
- }
-
- /**
- * Returns a numeric day given a timestamp
- * @param int timestamp (depending on implementation)
- * @return int day (e.g. 15)
- * @access protected
- */
- function stampToDay($stamp)
- {
- }
-
- /**
- * Returns a numeric hour given a timestamp
- * @param int timestamp (depending on implementation)
- * @return int hour (e.g. 13)
- * @access protected
- */
- function stampToHour($stamp)
- {
- }
-
- /**
- * Returns a numeric minute given a timestamp
- * @param int timestamp (depending on implementation)
- * @return int minute (e.g. 34)
- * @access protected
- */
- function stampToMinute($stamp)
- {
- }
-
- /**
- * Returns a numeric second given a timestamp
- * @param int timestamp (depending on implementation)
- * @return int second (e.g. 51)
- * @access protected
- */
- function stampToSecond($stamp)
- {
- }
-
- /**
- * Returns a timestamp. Can be worth "caching" generated
- * timestamps in a static variable, identified by the
- * params this method accepts, to timestamp will only
- * be calculated once.
- * @param int year (e.g. 2003)
- * @param int month (e.g. 9)
- * @param int day (e.g. 13)
- * @param int hour (e.g. 13)
- * @param int minute (e.g. 34)
- * @param int second (e.g. 53)
- * @return int (depends on implementation)
- * @access protected
- */
- function dateToStamp($y,$m,$d,$h,$i,$s)
- {
- }
-
- /**
- * The upper limit on years that the Calendar Engine can work with
- * @return int (e.g. 2037)
- * @access protected
- */
- function getMaxYears()
- {
- }
-
- /**
- * The lower limit on years that the Calendar Engine can work with
- * @return int (e.g 1902)
- * @access protected
- */
- function getMinYears()
- {
- }
-
- /**
- * Returns the number of months in a year
- * @param int (optional) year to get months for
- * @return int (e.g. 12)
- * @access protected
- */
- function getMonthsInYear($y=null)
- {
- }
-
- /**
- * Returns the number of days in a month, given year and month
- * @param int year (e.g. 2003)
- * @param int month (e.g. 9)
- * @return int days in month
- * @access protected
- */
- function getDaysInMonth($y, $m)
- {
- }
-
- /**
- * Returns numeric representation of the day of the week in a month,
- * given year and month
- * @param int year (e.g. 2003)
- * @param int month (e.g. 9)
- * @return int
- * @access protected
- */
- function getFirstDayInMonth ($y, $m)
- {
- }
-
- /**
- * Returns the number of days in a week
- * @param int year (2003)
- * @param int month (9)
- * @param int day (4)
- * @return int (e.g. 7)
- * @access protected
- */
- function getDaysInWeek($y=NULL, $m=NULL, $d=NULL)
- {
- }
-
- /**
- * Returns the number of the week in the year (ISO-8601), given a date
- * @param int year (2003)
- * @param int month (9)
- * @param int day (4)
- * @return int week number
- * @access protected
- */
- function getWeekNInYear($y, $m, $d)
- {
- }
-
- /**
- * Returns the number of the week in the month, given a date
- * @param int year (2003)
- * @param int month (9)
- * @param int day (4)
- * @param int first day of the week (default: 1 - monday)
- * @return int week number
- * @access protected
- */
- function getWeekNInMonth($y, $m, $d, $firstDay=1)
- {
- }
-
- /**
- * Returns the number of weeks in the month
- * @param int year (2003)
- * @param int month (9)
- * @param int first day of the week (default: 1 - monday)
- * @return int weeks number
- * @access protected
- */
- function getWeeksInMonth($y, $m)
- {
- }
-
- /**
- * Returns the number of the day of the week (0=sunday, 1=monday...)
- * @param int year (2003)
- * @param int month (9)
- * @param int day (4)
- * @return int weekday number
- * @access protected
- */
- function getDayOfWeek($y, $m, $d)
- {
- }
-
- /**
- * Returns the numeric values of the days of the week.
- * @param int year (2003)
- * @param int month (9)
- * @param int day (4)
- * @return array list of numeric values of days in week, beginning 0
- * @access protected
- */
- function getWeekDays($y=NULL, $m=NULL, $d=NULL)
- {
- }
-
- /**
- * Returns the default first day of the week as an integer. Must be a
- * member of the array returned from getWeekDays
- * @param int year (2003)
- * @param int month (9)
- * @param int day (4)
- * @return int (e.g. 1 for Monday)
- * @see getWeekDays
- * @access protected
- */
- function getFirstDayOfWeek($y=NULL, $m=NULL, $d=NULL)
- {
- }
-
- /**
- * Returns the number of hours in a day<br>
- * @param int (optional) day to get hours for
- * @return int (e.g. 24)
- * @access protected
- */
- function getHoursInDay($y=null,$m=null,$d=null)
- {
- }
-
- /**
- * Returns the number of minutes in an hour
- * @param int (optional) hour to get minutes for
- * @return int
- * @access protected
- */
- function getMinutesInHour($y=null,$m=null,$d=null,$h=null)
- {
- }
-
- /**
- * Returns the number of seconds in a minutes
- * @param int (optional) minute to get seconds for
- * @return int
- * @access protected
- */
- function getSecondsInMinute($y=null,$m=null,$d=null,$h=null,$i=null)
- {
- }
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Lorenzo Alberton <l dot alberton at quipo dot it> |
-// +----------------------------------------------------------------------+
-//
-// $Id: PearDate.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
-//
-/**
- * @package Calendar
- * @version $Id: PearDate.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- */
-/**
- * Load PEAR::Date class
- */
-require_once 'Date.php';
-
-/**
- * Performs calendar calculations based on the PEAR::Date class
- * Timestamps are in the ISO-8601 format (YYYY-MM-DD HH:MM:SS)
- * @package Calendar
- * @access protected
- */
-class Calendar_Engine_PearDate /* implements Calendar_Engine_Interface */
-{
- /**
- * Makes sure a given timestamp is only ever parsed once
- * Uses a static variable to prevent date() being used twice
- * for a date which is already known
- * @param mixed Any timestamp format recognized by Pear::Date
- * @return object Pear::Date object
- * @access protected
- */
- function stampCollection($stamp)
- {
- static $stamps = array();
- if (!isset($stamps[$stamp])) {
- $stamps[$stamp] = new Date($stamp);
- }
- return $stamps[$stamp];
- }
-
- /**
- * Returns a numeric year given a iso-8601 datetime
- * @param string iso-8601 datetime (YYYY-MM-DD HH:MM:SS)
- * @return int year (e.g. 2003)
- * @access protected
- */
- function stampToYear($stamp)
- {
- $date = Calendar_Engine_PearDate::stampCollection($stamp);
- return (int)$date->year;
- }
-
- /**
- * Returns a numeric month given a iso-8601 datetime
- * @param string iso-8601 datetime (YYYY-MM-DD HH:MM:SS)
- * @return int month (e.g. 9)
- * @access protected
- */
- function stampToMonth($stamp)
- {
- $date = Calendar_Engine_PearDate::stampCollection($stamp);
- return (int)$date->month;
- }
-
- /**
- * Returns a numeric day given a iso-8601 datetime
- * @param string iso-8601 datetime (YYYY-MM-DD HH:MM:SS)
- * @return int day (e.g. 15)
- * @access protected
- */
- function stampToDay($stamp)
- {
- $date = Calendar_Engine_PearDate::stampCollection($stamp);
- return (int)$date->day;
- }
-
- /**
- * Returns a numeric hour given a iso-8601 datetime
- * @param string iso-8601 datetime (YYYY-MM-DD HH:MM:SS)
- * @return int hour (e.g. 13)
- * @access protected
- */
- function stampToHour($stamp)
- {
- $date = Calendar_Engine_PearDate::stampCollection($stamp);
- return (int)$date->hour;
- }
-
- /**
- * Returns a numeric minute given a iso-8601 datetime
- * @param string iso-8601 datetime (YYYY-MM-DD HH:MM:SS)
- * @return int minute (e.g. 34)
- * @access protected
- */
- function stampToMinute($stamp)
- {
- $date = Calendar_Engine_PearDate::stampCollection($stamp);
- return (int)$date->minute;
- }
-
- /**
- * Returns a numeric second given a iso-8601 datetime
- * @param string iso-8601 datetime (YYYY-MM-DD HH:MM:SS)
- * @return int second (e.g. 51)
- * @access protected
- */
- function stampToSecond($stamp)
- {
- $date = Calendar_Engine_PearDate::stampCollection($stamp);
- return (int)$date->second;
- }
-
- /**
- * Returns a iso-8601 datetime
- * @param int year (2003)
- * @param int month (9)
- * @param int day (13)
- * @param int hour (13)
- * @param int minute (34)
- * @param int second (53)
- * @return string iso-8601 datetime
- * @access protected
- */
- function dateToStamp($y, $m, $d, $h=0, $i=0, $s=0)
- {
- $r = array();
- Calendar_Engine_PearDate::adjustDate($y, $m, $d, $h, $i, $s);
- $key = $y.$m.$d.$h.$i.$s;
- if (!isset($r[$key])) {
- $r[$key] = sprintf("%04d-%02d-%02d %02d:%02d:%02d",
- $y, $m, $d, $h, $i, $s);
- }
- return $r[$key];
- }
-
- /**
- * Set the correct date values (useful for math operations on dates)
- * @param int year (2003)
- * @param int month (9)
- * @param int day (13)
- * @param int hour (13)
- * @param int minute (34)
- * @param int second (53)
- * @access protected
- */
- function adjustDate(&$y, &$m, &$d, &$h, &$i, &$s)
- {
- if ($s < 0) {
- $m -= floor($s / 60);
- $s = -$s % 60;
- }
- if ($s > 60) {
- $m += floor($s / 60);
- $s %= 60;
- }
- if ($i < 0) {
- $h -= floor($i / 60);
- $i = -$i % 60;
- }
- if ($i > 60) {
- $h += floor($i / 60);
- $i %= 60;
- }
- if ($h < 0) {
- $d -= floor($h / 24);
- $h = -$h % 24;
- }
- if ($h > 24) {
- $d += floor($h / 24);
- $h %= 24;
- }
- for(; $m < 1; $y--, $m+=12);
- for(; $m > 12; $y++, $m-=12);
-
- while ($d < 1) {
- if ($m > 1) {
- $m--;
- } else {
- $m = 12;
- $y--;
- }
- $d += Date_Calc::daysInMonth($m, $y);
- }
- for ($max_days = Date_Calc::daysInMonth($m, $y); $d > $max_days; ) {
- $d -= $max_days;
- if ($m < 12) {
- $m++;
- } else {
- $m = 1;
- $y++;
- }
- }
- }
-
- /**
- * The upper limit on years that the Calendar Engine can work with
- * @return int 9999
- * @access protected
- */
- function getMaxYears()
- {
- return 9999;
- }
-
- /**
- * The lower limit on years that the Calendar Engine can work with
- * @return int 0
- * @access protected
- */
- function getMinYears()
- {
- return 0;
- }
-
- /**
- * Returns the number of months in a year
- * @return int (12)
- * @access protected
- */
- function getMonthsInYear($y=null)
- {
- return 12;
- }
-
- /**
- * Returns the number of days in a month, given year and month
- * @param int year (2003)
- * @param int month (9)
- * @return int days in month
- * @access protected
- */
- function getDaysInMonth($y, $m)
- {
- return (int)Date_Calc::daysInMonth($m, $y);
- }
-
- /**
- * Returns numeric representation of the day of the week in a month,
- * given year and month
- * @param int year (2003)
- * @param int month (9)
- * @return int from 0 to 7
- * @access protected
- */
- function getFirstDayInMonth($y, $m)
- {
- return (int)Date_Calc::dayOfWeek(1, $m, $y);
- }
-
- /**
- * Returns the number of days in a week
- * @param int year (2003)
- * @param int month (9)
- * @param int day (4)
- * @return int (7)
- * @access protected
- */
- function getDaysInWeek($y=NULL, $m=NULL, $d=NULL)
- {
- return 7;
- }
-
- /**
- * Returns the number of the week in the year (ISO-8601), given a date
- * @param int year (2003)
- * @param int month (9)
- * @param int day (4)
- * @return int week number
- * @access protected
- */
- function getWeekNInYear($y, $m, $d)
- {
- return Date_Calc::weekOfYear($d, $m, $y); //beware, Date_Calc doesn't follow ISO-8601 standard!
- }
-
- /**
- * Returns the number of the week in the month, given a date
- * @param int year (2003)
- * @param int month (9)
- * @param int day (4)
- * @param int first day of the week (default: monday)
- * @return int week number
- * @access protected
- */
- function getWeekNInMonth($y, $m, $d, $firstDay=1)
- {
- $weekEnd = ($firstDay == 0) ? $this->getDaysInWeek()-1 : $firstDay-1;
- $end_of_week = (int)Date_Calc::nextDayOfWeek($weekEnd, 1, $m, $y, '%e', true);
- $w = 1;
- while ($d > $end_of_week) {
- ++$w;
- $end_of_week += $this->getDaysInWeek();
- }
- return $w;
- }
-
- /**
- * Returns the number of weeks in the month
- * @param int year (2003)
- * @param int month (9)
- * @param int first day of the week (default: monday)
- * @return int weeks number
- * @access protected
- */
- function getWeeksInMonth($y, $m, $firstDay=1)
- {
- $FDOM = Date_Calc::firstOfMonthWeekday($m, $y);
- if ($FDOM == 0) {
- $FDOM = $this->getDaysInWeek();
- }
- if ($FDOM > $firstDay) {
- $daysInTheFirstWeek = $this->getDaysInWeek() - $FDOM + $firstDay;
- $weeks = 1;
- } else {
- $daysInTheFirstWeek = $firstDay - $FDOM;
- $weeks = 0;
- }
- $daysInTheFirstWeek %= $this->getDaysInWeek();
- return (int)(ceil(($this->getDaysInMonth($y, $m) - $daysInTheFirstWeek) /
- $this->getDaysInWeek()) + $weeks);
- }
-
- /**
- * Returns the number of the day of the week (0=sunday, 1=monday...)
- * @param int year (2003)
- * @param int month (9)
- * @param int day (4)
- * @return int weekday number
- * @access protected
- */
- function getDayOfWeek($y, $m, $d)
- {
- return Date_Calc::dayOfWeek($d, $m, $y);
- }
-
- /**
- * Returns a list of integer days of the week beginning 0
- * @param int year (2003)
- * @param int month (9)
- * @param int day (4)
- * @return array (0, 1, 2, 3, 4, 5, 6) 1 = Monday
- * @access protected
- */
- function getWeekDays($y=NULL, $m=NULL, $d=NULL)
- {
- return array(0, 1, 2, 3, 4, 5, 6);
- }
-
- /**
- * Returns the default first day of the week
- * @param int year (2003)
- * @param int month (9)
- * @param int day (4)
- * @return int (default 1 = Monday)
- * @access protected
- */
- function getFirstDayOfWeek($y=NULL, $m=NULL, $d=NULL)
- {
- return 1;
- }
-
- /**
- * Returns the number of hours in a day
- * @return int (24)
- * @access protected
- */
- function getHoursInDay($y=null,$m=null,$d=null)
- {
- return 24;
- }
-
- /**
- * Returns the number of minutes in an hour
- * @return int (60)
- * @access protected
- */
- function getMinutesInHour($y=null,$m=null,$d=null,$h=null)
- {
- return 60;
- }
-
- /**
- * Returns the number of seconds in a minutes
- * @return int (60)
- * @access protected
- */
- function getSecondsInMinute($y=null,$m=null,$d=null,$h=null,$i=null)
- {
- return 60;
- }
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Harry Fuecks <hfuecks@phppatterns.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: UnixTS.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
-//
-/**
- * @package Calendar
- * @version $Id: UnixTS.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- */
-/**
- * Performs calendar calculations based on the PHP date() function and
- * Unix timestamps (using PHP's mktime() function).
- * @package Calendar
- * @access protected
- */
-class Calendar_Engine_UnixTS /* implements Calendar_Engine_Interface */
-{
- /**
- * Makes sure a given timestamp is only ever parsed once
- * <pre>
- * array (
- * [0] => year (e.g 2003),
- * [1] => month (e.g 9),
- * [2] => day (e.g 6),
- * [3] => hour (e.g 14),
- * [4] => minute (e.g 34),
- * [5] => second (e.g 45),
- * [6] => num days in month (e.g. 31),
- * [7] => week in year (e.g. 50),
- * [8] => day in week (e.g. 0 for Sunday)
- * )
- * </pre>
- * Uses a static variable to prevent date() being used twice
- * for a date which is already known
- * @param int Unix timestamp
- * @return array
- * @access protected
- */
- function stampCollection($stamp)
- {
- static $stamps = array();
- if ( !isset($stamps[$stamp]) ) {
- $date = @date('Y n j H i s t W w',$stamp);
- $stamps[$stamp] = sscanf($date, "%d %d %d %d %d %d %d %d %d");
- }
- return $stamps[$stamp];
- }
-
- /**
- * Returns a numeric year given a timestamp
- * @param int Unix timestamp
- * @return int year (e.g. 2003)
- * @access protected
- */
- function stampToYear($stamp)
- {
- $date = Calendar_Engine_UnixTS::stampCollection($stamp);
- return (int)$date[0];
- }
-
- /**
- * Returns a numeric month given a timestamp
- * @param int Unix timestamp
- * @return int month (e.g. 9)
- * @access protected
- */
- function stampToMonth($stamp)
- {
- $date = Calendar_Engine_UnixTS::stampCollection($stamp);
- return (int)$date[1];
- }
-
- /**
- * Returns a numeric day given a timestamp
- * @param int Unix timestamp
- * @return int day (e.g. 15)
- * @access protected
- */
- function stampToDay($stamp)
- {
- $date = Calendar_Engine_UnixTS::stampCollection($stamp);
- return (int)$date[2];
- }
-
- /**
- * Returns a numeric hour given a timestamp
- * @param int Unix timestamp
- * @return int hour (e.g. 13)
- * @access protected
- */
- function stampToHour($stamp)
- {
- $date = Calendar_Engine_UnixTS::stampCollection($stamp);
- return (int)$date[3];
- }
-
- /**
- * Returns a numeric minute given a timestamp
- * @param int Unix timestamp
- * @return int minute (e.g. 34)
- * @access protected
- */
- function stampToMinute($stamp)
- {
- $date = Calendar_Engine_UnixTS::stampCollection($stamp);
- return (int)$date[4];
- }
-
- /**
- * Returns a numeric second given a timestamp
- * @param int Unix timestamp
- * @return int second (e.g. 51)
- * @access protected
- */
- function stampToSecond($stamp)
- {
- $date = Calendar_Engine_UnixTS::stampCollection($stamp);
- return (int)$date[5];
- }
-
- /**
- * Returns a timestamp
- * @param int year (2003)
- * @param int month (9)
- * @param int day (13)
- * @param int hour (13)
- * @param int minute (34)
- * @param int second (53)
- * @return int Unix timestamp
- * @access protected
- */
- function dateToStamp($y, $m, $d, $h=0, $i=0, $s=0)
- {
- static $dates = array();
- if ( !isset($dates[$y][$m][$d][$h][$i][$s]) ) {
- $dates[$y][$m][$d][$h][$i][$s] = @mktime($h, $i, $s, $m, $d, $y);
- }
- return $dates[$y][$m][$d][$h][$i][$s];
- }
-
- /**
- * The upper limit on years that the Calendar Engine can work with
- * @return int (2037)
- * @access protected
- */
- function getMaxYears()
- {
- return 2037;
- }
-
- /**
- * The lower limit on years that the Calendar Engine can work with
- * @return int (1970 if it's Windows and 1902 for all other OSs)
- * @access protected
- */
- function getMinYears()
- {
- return $min = strpos(PHP_OS, 'WIN') === false ? 1902 : 1970;
- }
-
- /**
- * Returns the number of months in a year
- * @return int (12)
- * @access protected
- */
- function getMonthsInYear($y=null)
- {
- return 12;
- }
-
- /**
- * Returns the number of days in a month, given year and month
- * @param int year (2003)
- * @param int month (9)
- * @return int days in month
- * @access protected
- */
- function getDaysInMonth($y, $m)
- {
- $stamp = Calendar_Engine_UnixTS::dateToStamp($y,$m,1);
- $date = Calendar_Engine_UnixTS::stampCollection($stamp);
- return $date[6];
- }
-
- /**
- * Returns numeric representation of the day of the week in a month,
- * given year and month
- * @param int year (2003)
- * @param int month (9)
- * @return int from 0 to 6
- * @access protected
- */
- function getFirstDayInMonth($y, $m)
- {
- $stamp = Calendar_Engine_UnixTS::dateToStamp($y,$m,1);
- $date = Calendar_Engine_UnixTS::stampCollection($stamp);
- return $date[8];
- }
-
- /**
- * Returns the number of days in a week
- * @param int year (2003)
- * @param int month (9)
- * @param int day (4)
- * @return int (7)
- * @access protected
- */
- function getDaysInWeek($y=NULL, $m=NULL, $d=NULL)
- {
- return 7;
- }
-
- /**
- * Returns the number of the week in the year (ISO-8601), given a date
- * @param int year (2003)
- * @param int month (9)
- * @param int day (4)
- * @return int week number
- * @access protected
- */
- function getWeekNInYear($y, $m, $d)
- {
- $stamp = Calendar_Engine_UnixTS::dateToStamp($y,$m,$d);
- $date = Calendar_Engine_UnixTS::stampCollection($stamp);
- return $date[7];
- }
-
- /**
- * Returns the number of the week in the month, given a date
- * @param int year (2003)
- * @param int month (9)
- * @param int day (4)
- * @param int first day of the week (default: monday)
- * @return int week number
- * @access protected
- */
- function getWeekNInMonth($y, $m, $d, $firstDay=1)
- {
- $weekEnd = ($firstDay == 0) ? $this->getDaysInWeek()-1 : $firstDay-1;
- $end_of_week = 1;
- while (@date('w', @mktime(0, 0, 0, $m, $end_of_week, $y)) != $weekEnd) {
- ++$end_of_week; //find first weekend of the month
- }
- $w = 1;
- while ($d > $end_of_week) {
- ++$w;
- $end_of_week += $this->getDaysInWeek();
- }
- return $w;
- }
-
- /**
- * Returns the number of weeks in the month
- * @param int year (2003)
- * @param int month (9)
- * @param int first day of the week (default: monday)
- * @return int weeks number
- * @access protected
- */
- function getWeeksInMonth($y, $m, $firstDay=1)
- {
- $FDOM = $this->getFirstDayInMonth($y, $m);
- if ($FDOM == 0) {
- $FDOM = $this->getDaysInWeek();
- }
- if ($FDOM > $firstDay) {
- $daysInTheFirstWeek = $this->getDaysInWeek() - $FDOM + $firstDay;
- $weeks = 1;
- } else {
- $daysInTheFirstWeek = $firstDay - $FDOM;
- $weeks = 0;
- }
- $daysInTheFirstWeek %= $this->getDaysInWeek();
- return (int)(ceil(($this->getDaysInMonth($y, $m) - $daysInTheFirstWeek) /
- $this->getDaysInWeek()) + $weeks);
- }
-
- /**
- * Returns the number of the day of the week (0=sunday, 1=monday...)
- * @param int year (2003)
- * @param int month (9)
- * @param int day (4)
- * @return int weekday number
- * @access protected
- */
- function getDayOfWeek($y, $m, $d)
- {
- $stamp = Calendar_Engine_UnixTS::dateToStamp($y,$m,$d);
- $date = Calendar_Engine_UnixTS::stampCollection($stamp);
- return $date[8];
- }
-
- /**
- * Returns a list of integer days of the week beginning 0
- * @param int year (2003)
- * @param int month (9)
- * @param int day (4)
- * @return array (0,1,2,3,4,5,6) 1 = Monday
- * @access protected
- */
- function getWeekDays($y=NULL, $m=NULL, $d=NULL)
- {
- return array(0, 1, 2, 3, 4, 5, 6);
- }
-
- /**
- * Returns the default first day of the week
- * @param int year (2003)
- * @param int month (9)
- * @param int day (4)
- * @return int (default 1 = Monday)
- * @access protected
- */
- function getFirstDayOfWeek($y=NULL, $m=NULL, $d=NULL)
- {
- return 1;
- }
-
- /**
- * Returns the number of hours in a day
- * @return int (24)
- * @access protected
- */
- function getHoursInDay($y=null,$m=null,$d=null)
- {
- return 24;
- }
-
- /**
- * Returns the number of minutes in an hour
- * @return int (60)
- * @access protected
- */
- function getMinutesInHour($y=null,$m=null,$d=null,$h=null)
- {
- return 60;
- }
-
- /**
- * Returns the number of seconds in a minutes
- * @return int (60)
- * @access protected
- */
- function getSecondsInMinute($y=null,$m=null,$d=null,$h=null,$i=null)
- {
- return 60;
- }
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Harry Fuecks <hfuecks@phppatterns.com> |
-// | Lorenzo Alberton <l dot alberton at quipo dot it> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Factory.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
-//
-/**
- * @package Calendar
- * @version $Id: Factory.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- */
-
-/**
- * Allows Calendar include path to be redefined
- * @ignore
- */
-if (!defined('CALENDAR_ROOT')) {
- define('CALENDAR_ROOT', 'Calendar'.DIRECTORY_SEPARATOR);
-}
-
-/**
- * Load Calendar base class
- */
-require_once CALENDAR_ROOT.'Calendar.php';
-
-/**
- * Contains a factory method to return a Singleton instance of a class
- * implementing the Calendar_Engine_Interface.<br>
- * For Month objects, to control type of month returned, use CALENDAR_MONTH_STATE
- * constact e.g.;
- * <code>
- * require_once 'Calendar/Factory.php';
- * define ('CALENDAR_MONTH_STATE',CALENDAR_USE_MONTH_WEEKDAYS); // Use Calendar_Month_Weekdays
- * // define ('CALENDAR_MONTH_STATE',CALENDAR_USE_MONTH_WEEKS); // Use Calendar_Month_Weeks
- * // define ('CALENDAR_MONTH_STATE',CALENDAR_USE_MONTH); // Use Calendar_Month
- * </code>
- * It defaults to building Calendar_Month objects.<br>
- * Use the constract CALENDAR_FIRST_DAY_OF_WEEK to control the first day of the week
- * for Month or Week objects (e.g. 0 = Sunday, 6 = Saturday)
- * @package Calendar
- * @access protected
- */
-class Calendar_Factory
-{
- /**
- * Creates a calendar object given the type and units
- * @param string class of calendar object to create
- * @param int year
- * @param int month
- * @param int day
- * @param int hour
- * @param int minute
- * @param int second
- * @return object subclass of Calendar
- * @access public
- * @static
- */
- function create($type, $y = 2000, $m = 1, $d = 1, $h = 0, $i = 0, $s = 0)
- {
- $firstDay = defined('CALENDAR_FIRST_DAY_OF_WEEK') ? CALENDAR_FIRST_DAY_OF_WEEK : 1;
- switch ($type) {
- case 'Day':
- require_once CALENDAR_ROOT.'Day.php';
- return new Calendar_Day($y,$m,$d);
- case 'Month':
- // Set default state for which month type to build
- if (!defined('CALENDAR_MONTH_STATE')) {
- define('CALENDAR_MONTH_STATE', CALENDAR_USE_MONTH);
- }
- switch (CALENDAR_MONTH_STATE) {
- case CALENDAR_USE_MONTH_WEEKDAYS:
- require_once CALENDAR_ROOT.'Month/Weekdays.php';
- $class = 'Calendar_Month_Weekdays';
- break;
- case CALENDAR_USE_MONTH_WEEKS:
- require_once CALENDAR_ROOT.'Month/Weeks.php';
- $class = 'Calendar_Month_Weeks';
- break;
- case CALENDAR_USE_MONTH:
- default:
- require_once CALENDAR_ROOT.'Month.php';
- $class = 'Calendar_Month';
- break;
- }
- return new $class($y, $m, $firstDay);
- case 'Week':
- require_once CALENDAR_ROOT.'Week.php';
- return new Calendar_Week($y, $m, $d, $firstDay);
- case 'Hour':
- require_once CALENDAR_ROOT.'Hour.php';
- return new Calendar_Hour($y, $m, $d, $h);
- case 'Minute':
- require_once CALENDAR_ROOT.'Minute.php';
- return new Calendar_Minute($y, $m, $d, $h, $i);
- case 'Second':
- require_once CALENDAR_ROOT.'Second.php';
- return new Calendar_Second($y,$m,$d,$h,$i,$s);
- case 'Year':
- require_once CALENDAR_ROOT.'Year.php';
- return new Calendar_Year($y);
- default:
- require_once 'PEAR.php';
- PEAR::raiseError(
- 'Calendar_Factory::create() unrecognised type: '.$type, null, PEAR_ERROR_TRIGGER,
- E_USER_NOTICE, 'Calendar_Factory::create()');
- return false;
- }
- }
- /**
- * Creates an instance of a calendar object, given a type and timestamp
- * @param string type of object to create
- * @param mixed timestamp (depending on Calendar engine being used)
- * @return object subclass of Calendar
- * @access public
- * @static
- */
- function & createByTimestamp($type, $stamp)
- {
- $cE = & Calendar_Engine_Factory::getEngine();
- $y = $cE->stampToYear($stamp);
- $m = $cE->stampToMonth($stamp);
- $d = $cE->stampToDay($stamp);
- $h = $cE->stampToHour($stamp);
- $i = $cE->stampToMinute($stamp);
- $s = $cE->stampToSecond($stamp);
- $cal = Calendar_Factory::create($type, $y, $m, $d, $h, $i, $s);
- return $cal;
- }
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Harry Fuecks <hfuecks@phppatterns.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Hour.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
-//
-/**
- * @package Calendar
- * @version $Id: Hour.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- */
-
-/**
- * Allows Calendar include path to be redefined
- * @ignore
- */
-if (!defined('CALENDAR_ROOT')) {
- define('CALENDAR_ROOT', 'Calendar'.DIRECTORY_SEPARATOR);
-}
-
-/**
- * Load Calendar base class
- */
-require_once CALENDAR_ROOT.'Calendar.php';
-
-/**
- * Represents an Hour and builds Minutes
- * <code>
- * require_once 'Calendar'.DIRECTORY_SEPARATOR.'Hour.php';
- * $Hour = & new Calendar_Hour(2003, 10, 21, 15); // Oct 21st 2003, 3pm
- * $Hour->build(); // Build Calendar_Minute objects
- * while ($Minute = & $Hour->fetch()) {
- * echo $Minute->thisMinute().'<br />';
- * }
- * </code>
- * @package Calendar
- * @access public
- */
-class Calendar_Hour extends Calendar
-{
- /**
- * Constructs Calendar_Hour
- * @param int year e.g. 2003
- * @param int month e.g. 5
- * @param int day e.g. 11
- * @param int hour e.g. 13
- * @access public
- */
- function Calendar_Hour($y, $m, $d, $h)
- {
- Calendar::Calendar($y, $m, $d, $h);
- }
-
- /**
- * Builds the Minutes in the Hour
- * @param array (optional) Calendar_Minute objects representing selected dates
- * @return boolean
- * @access public
- */
- function build($sDates=array())
- {
- require_once CALENDAR_ROOT.'Minute.php';
- $mIH = $this->cE->getMinutesInHour($this->year, $this->month, $this->day,
- $this->hour);
- for ($i=0; $i < $mIH; $i++) {
- $this->children[$i]=
- new Calendar_Minute($this->year, $this->month, $this->day,
- $this->hour, $i);
- }
- if (count($sDates) > 0) {
- $this->setSelection($sDates);
- }
- return true;
- }
-
- /**
- * Called from build()
- * @param array
- * @return void
- * @access private
- */
- function setSelection($sDates)
- {
- foreach ($sDates as $sDate) {
- if ($this->year == $sDate->thisYear()
- && $this->month == $sDate->thisMonth()
- && $this->day == $sDate->thisDay()
- && $this->hour == $sDate->thisHour())
- {
- $key = (int)$sDate->thisMinute();
- if (isset($this->children[$key])) {
- $sDate->setSelected();
- $this->children[$key] = $sDate;
- }
- }
- }
- }
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Harry Fuecks <hfuecks@phppatterns.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Minute.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
-//
-/**
- * @package Calendar
- * @version $Id: Minute.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- */
-
-/**
- * Allows Calendar include path to be redefined
- * @ignore
- */
-if (!defined('CALENDAR_ROOT')) {
- define('CALENDAR_ROOT', 'Calendar'.DIRECTORY_SEPARATOR);
-}
-
-/**
- * Load Calendar base class
- */
-require_once CALENDAR_ROOT.'Calendar.php';
-
-/**
- * Represents a Minute and builds Seconds
- * <code>
- * require_once 'Calendar'.DIRECTORY_SEPARATOR.'Minute.php';
- * $Minute = & new Calendar_Minute(2003, 10, 21, 15, 31); // Oct 21st 2003, 3:31pm
- * $Minute->build(); // Build Calendar_Second objects
- * while ($Second = & $Minute->fetch()) {
- * echo $Second->thisSecond().'<br />';
- * }
- * </code>
- * @package Calendar
- * @access public
- */
-class Calendar_Minute extends Calendar
-{
- /**
- * Constructs Minute
- * @param int year e.g. 2003
- * @param int month e.g. 5
- * @param int day e.g. 11
- * @param int hour e.g. 13
- * @param int minute e.g. 31
- * @access public
- */
- function Calendar_Minute($y, $m, $d, $h, $i)
- {
- Calendar::Calendar($y, $m, $d, $h, $i);
- }
-
- /**
- * Builds the Calendar_Second objects
- * @param array (optional) Calendar_Second objects representing selected dates
- * @return boolean
- * @access public
- */
- function build($sDates=array())
- {
- require_once CALENDAR_ROOT.'Second.php';
- $sIM = $this->cE->getSecondsInMinute($this->year, $this->month,
- $this->day, $this->hour, $this->minute);
- for ($i=0; $i < $sIM; $i++) {
- $this->children[$i] = new Calendar_Second($this->year, $this->month,
- $this->day, $this->hour, $this->minute, $i);
- }
- if (count($sDates) > 0) {
- $this->setSelection($sDates);
- }
- return true;
- }
-
- /**
- * Called from build()
- * @param array
- * @return void
- * @access private
- */
- function setSelection($sDates)
- {
- foreach ($sDates as $sDate) {
- if ($this->year == $sDate->thisYear()
- && $this->month == $sDate->thisMonth()
- && $this->day == $sDate->thisDay()
- && $this->hour == $sDate->thisHour()
- && $this->minute == $sDate->thisMinute())
- {
- $key = (int)$sDate->thisSecond();
- if (isset($this->children[$key])) {
- $sDate->setSelected();
- $this->children[$key] = $sDate;
- }
- }
- }
- }
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Harry Fuecks <hfuecks@phppatterns.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Month.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
-//
-/**
- * @package Calendar
- * @version $Id: Month.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- */
-
-/**
- * Allows Calendar include path to be redefined
- * @ignore
- */
-if (!defined('CALENDAR_ROOT')) {
- define('CALENDAR_ROOT', 'Calendar'.DIRECTORY_SEPARATOR);
-}
-
-/**
- * Load Calendar base class
- */
-require_once CALENDAR_ROOT.'Calendar.php';
-
-/**
- * Represents a Month and builds Days
- * <code>
- * require_once 'Calendar/Month.php';
- * $Month = & new Calendar_Month(2003, 10); // Oct 2003
- * $Month->build(); // Build Calendar_Day objects
- * while ($Day = & $Month->fetch()) {
- * echo $Day->thisDay().'<br />';
- * }
- * </code>
- * @package Calendar
- * @access public
- */
-class Calendar_Month extends Calendar
-{
- /**
- * Constructs Calendar_Month
- * @param int $y year e.g. 2003
- * @param int $m month e.g. 5
- * @param int $firstDay first day of the week [optional]
- * @access public
- */
- function Calendar_Month($y, $m, $firstDay=null)
- {
- Calendar::Calendar($y, $m);
- $this->firstDay = $this->defineFirstDayOfWeek($firstDay);
- }
-
- /**
- * Builds Day objects for this Month. Creates as many Calendar_Day objects
- * as there are days in the month
- * @param array (optional) Calendar_Day objects representing selected dates
- * @return boolean
- * @access public
- */
- function build($sDates=array())
- {
- require_once CALENDAR_ROOT.'Day.php';
- $daysInMonth = $this->cE->getDaysInMonth($this->year, $this->month);
- for ($i=1; $i<=$daysInMonth; $i++) {
- $this->children[$i] = new Calendar_Day($this->year, $this->month, $i);
- }
- if (count($sDates) > 0) {
- $this->setSelection($sDates);
- }
- return true;
- }
-
- /**
- * Called from build()
- * @param array
- * @return void
- * @access private
- */
- function setSelection($sDates)
- {
- foreach ($sDates as $sDate) {
- if ($this->year == $sDate->thisYear()
- && $this->month == $sDate->thisMonth()
- ) {
- $key = $sDate->thisDay();
- if (isset($this->children[$key])) {
- $sDate->setSelected();
- $class = strtolower(get_class($sDate));
- if ($class == 'calendar_day' || $class == 'calendar_decorator') {
- $sDate->setFirst($this->children[$key]->isFirst());
- $sDate->setLast($this->children[$key]->isLast());
- }
- $this->children[$key] = $sDate;
- }
- }
- }
- }
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Harry Fuecks <hfuecks@phppatterns.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Weekdays.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
-//
-/**
- * @package Calendar
- * @version $Id: Weekdays.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- */
-
-/**
- * Allows Calendar include path to be redefined
- * @ignore
- */
-if (!defined('CALENDAR_ROOT')) {
- define('CALENDAR_ROOT', 'Calendar'.DIRECTORY_SEPARATOR);
-}
-
-/**
- * Load Calendar base class
- */
-require_once CALENDAR_ROOT.'Calendar.php';
-
-/**
- * Load base month
- */
-require_once CALENDAR_ROOT.'Month.php';
-
-/**
- * Represents a Month and builds Days in tabular form<br>
- * <code>
- * require_once 'Calendar/Month/Weekdays.php';
- * $Month = & new Calendar_Month_Weekdays(2003, 10); // Oct 2003
- * $Month->build(); // Build Calendar_Day objects
- * while ($Day = & $Month->fetch()) {
- * if ($Day->isFirst()) {
- * echo '<tr>';
- * }
- * if ($Day->isEmpty()) {
- * echo '<td> </td>';
- * } else {
- * echo '<td>'.$Day->thisDay().'</td>';
- * }
- * if ($Day->isLast()) {
- * echo '</tr>';
- * }
- * }
- * </code>
- * @package Calendar
- * @access public
- */
-class Calendar_Month_Weekdays extends Calendar_Month
-{
- /**
- * Instance of Calendar_Table_Helper
- * @var Calendar_Table_Helper
- * @access private
- */
- var $tableHelper;
-
- /**
- * First day of the week
- * @access private
- * @var string
- */
- var $firstDay;
-
- /**
- * Constructs Calendar_Month_Weekdays
- * @param int year e.g. 2003
- * @param int month e.g. 5
- * @param int (optional) first day of week (e.g. 0 for Sunday, 2 for Tuesday etc.)
- * @access public
- */
- function Calendar_Month_Weekdays($y, $m, $firstDay=null)
- {
- Calendar_Month::Calendar_Month($y, $m, $firstDay);
- }
-
- /**
- * Builds Day objects in tabular form, to allow display of calendar month
- * with empty cells if the first day of the week does not fall on the first
- * day of the month.
- * @see Calendar_Day::isEmpty()
- * @see Calendar_Day_Base::isFirst()
- * @see Calendar_Day_Base::isLast()
- * @param array (optional) Calendar_Day objects representing selected dates
- * @return boolean
- * @access public
- */
- function build($sDates=array())
- {
- require_once CALENDAR_ROOT.'Table/Helper.php';
- $this->tableHelper = & new Calendar_Table_Helper($this, $this->firstDay);
- Calendar_Month::build($sDates);
- $this->buildEmptyDaysBefore();
- $this->shiftDays();
- $this->buildEmptyDaysAfter();
- $this->setWeekMarkers();
- return true;
- }
-
- /**
- * Prepends empty days before the real days in the month
- * @return void
- * @access private
- */
- function buildEmptyDaysBefore()
- {
- $eBefore = $this->tableHelper->getEmptyDaysBefore();
- for ($i=0; $i < $eBefore; $i++) {
- $stamp = $this->cE->dateToStamp($this->year, $this->month, -$i);
- $Day = new Calendar_Day(
- $this->cE->stampToYear($stamp),
- $this->cE->stampToMonth($stamp),
- $this->cE->stampToDay($stamp));
- $Day->setEmpty();
- $Day->adjust();
- array_unshift($this->children, $Day);
- }
- }
-
- /**
- * Shifts the array of children forward, if necessary
- * @return void
- * @access private
- */
- function shiftDays()
- {
- if (isset ($this->children[0])) {
- array_unshift($this->children, null);
- unset($this->children[0]);
- }
- }
-
- /**
- * Appends empty days after the real days in the month
- * @return void
- * @access private
- */
- function buildEmptyDaysAfter()
- {
- $eAfter = $this->tableHelper->getEmptyDaysAfter();
- $sDOM = $this->tableHelper->getNumTableDaysInMonth();
- for ($i = 1; $i <= $sDOM-$eAfter; $i++) {
- $Day = new Calendar_Day($this->year, $this->month+1, $i);
- $Day->setEmpty();
- $Day->adjust();
- array_push($this->children, $Day);
- }
- }
-
- /**
- * Sets the "markers" for the beginning and of a of week, in the
- * built Calendar_Day children
- * @return void
- * @access private
- */
- function setWeekMarkers()
- {
- $dIW = $this->cE->getDaysInWeek(
- $this->thisYear(),
- $this->thisMonth(),
- $this->thisDay()
- );
- $sDOM = $this->tableHelper->getNumTableDaysInMonth();
- for ($i=1; $i <= $sDOM; $i+= $dIW) {
- $this->children[$i]->setFirst();
- $this->children[$i+($dIW-1)]->setLast();
- }
- }
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Harry Fuecks <hfuecks@phppatterns.com> |
-// | Lorenzo Alberton <l dot alberton at quipo dot it> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Weeks.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
-//
-/**
- * @package Calendar
- * @version $Id: Weeks.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- */
-
-/**
- * Allows Calendar include path to be redefined
- * @ignore
- */
-if (!defined('CALENDAR_ROOT')) {
- define('CALENDAR_ROOT', 'Calendar'.DIRECTORY_SEPARATOR);
-}
-
-/**
- * Load Calendar base class
- */
-require_once CALENDAR_ROOT.'Calendar.php';
-
-/**
- * Load base month
- */
-require_once CALENDAR_ROOT.'Month.php';
-
-/**
- * Represents a Month and builds Weeks
- * <code>
- * require_once 'Calendar'.DIRECTORY_SEPARATOR.'Month'.DIRECTORY_SEPARATOR.'Weeks.php';
- * $Month = & new Calendar_Month_Weeks(2003, 10); // Oct 2003
- * $Month->build(); // Build Calendar_Day objects
- * while ($Week = & $Month->fetch()) {
- * echo $Week->thisWeek().'<br />';
- * }
- * </code>
- * @package Calendar
- * @access public
- */
-class Calendar_Month_Weeks extends Calendar_Month
-{
- /**
- * Instance of Calendar_Table_Helper
- * @var Calendar_Table_Helper
- * @access private
- */
- var $tableHelper;
-
- /**
- * First day of the week
- * @access private
- * @var string
- */
- var $firstDay;
-
- /**
- * Constructs Calendar_Month_Weeks
- * @param int year e.g. 2003
- * @param int month e.g. 5
- * @param int (optional) first day of week (e.g. 0 for Sunday, 2 for Tuesday etc.)
- * @access public
- */
- function Calendar_Month_Weeks($y, $m, $firstDay=null)
- {
- Calendar_Month::Calendar_Month($y, $m, $firstDay);
- }
-
- /**
- * Builds Calendar_Week objects for the Month. Note that Calendar_Week
- * builds Calendar_Day object in tabular form (with Calendar_Day->empty)
- * @param array (optional) Calendar_Week objects representing selected dates
- * @return boolean
- * @access public
- */
- function build($sDates=array())
- {
- require_once CALENDAR_ROOT.'Table/Helper.php';
- $this->tableHelper = & new Calendar_Table_Helper($this, $this->firstDay);
- require_once CALENDAR_ROOT.'Week.php';
- $numWeeks = $this->tableHelper->getNumWeeks();
- for ($i=1, $d=1; $i<=$numWeeks; $i++,
- $d+=$this->cE->getDaysInWeek(
- $this->thisYear(),
- $this->thisMonth(),
- $this->thisDay()) ) {
- $this->children[$i] = new Calendar_Week(
- $this->year, $this->month, $d, $this->tableHelper->getFirstDay());
- }
- //used to set empty days
- $this->children[1]->setFirst(true);
- $this->children[$numWeeks]->setLast(true);
-
- // Handle selected weeks here
- if (count($sDates) > 0) {
- $this->setSelection($sDates);
- }
- return true;
- }
-
- /**
- * Called from build()
- * @param array
- * @return void
- * @access private
- */
- function setSelection($sDates)
- {
- foreach ($sDates as $sDate) {
- if ($this->year == $sDate->thisYear()
- && $this->month == $sDate->thisMonth())
- {
- $key = $sDate->thisWeek('n_in_month');
- if (isset($this->children[$key])) {
- $this->children[$key]->setSelected();
- }
- }
- }
- }
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Harry Fuecks <hfuecks@phppatterns.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Second.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
-//
-/**
- * @package Calendar
- * @version $Id: Second.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- */
-
-/**
- * Allows Calendar include path to be redefined
- * @ignore
- */
-if (!defined('CALENDAR_ROOT')) {
- define('CALENDAR_ROOT', 'Calendar'.DIRECTORY_SEPARATOR);
-}
-
-/**
- * Load Calendar base class
- */
-require_once CALENDAR_ROOT.'Calendar.php';
-
-/**
- * Represents a Second<br />
- * <b>Note:</b> Seconds do not build other objects
- * so related methods are overridden to return NULL
- * @package Calendar
- */
-class Calendar_Second extends Calendar
-{
- /**
- * Constructs Second
- * @param int year e.g. 2003
- * @param int month e.g. 5
- * @param int day e.g. 11
- * @param int hour e.g. 13
- * @param int minute e.g. 31
- * @param int second e.g. 45
- */
- function Calendar_Second($y, $m, $d, $h, $i, $s)
- {
- Calendar::Calendar($y, $m, $d, $h, $i, $s);
- }
-
- /**
- * Overwrite build
- * @return NULL
- */
- function build()
- {
- return null;
- }
-
- /**
- * Overwrite fetch
- * @return NULL
- */
- function fetch()
- {
- return null;
- }
-
- /**
- * Overwrite fetchAll
- * @return NULL
- */
- function fetchAll()
- {
- return null;
- }
-
- /**
- * Overwrite size
- * @return NULL
- */
- function size()
- {
- return null;
- }
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Harry Fuecks <hfuecks@phppatterns.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Helper.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
-//
-/**
- * @package Calendar
- * @version $Id: Helper.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- */
-
-/**
- * Used by Calendar_Month_Weekdays, Calendar_Month_Weeks and Calendar_Week to
- * help with building the calendar in tabular form
- * @package Calendar
- * @access protected
- */
-class Calendar_Table_Helper
-{
- /**
- * Instance of the Calendar object being helped.
- * @var object
- * @access private
- */
- var $calendar;
-
- /**
- * Instance of the Calendar_Engine
- * @var object
- * @access private
- */
- var $cE;
-
- /**
- * First day of the week
- * @access private
- * @var string
- */
- var $firstDay;
-
- /**
- * The seven days of the week named
- * @access private
- * @var array
- */
- var $weekDays;
-
- /**
- * Days of the week ordered with $firstDay at the beginning
- * @access private
- * @var array
- */
- var $daysOfWeek = array();
-
- /**
- * Days of the month built from days of the week
- * @access private
- * @var array
- */
- var $daysOfMonth = array();
-
- /**
- * Number of weeks in month
- * @var int
- * @access private
- */
- var $numWeeks = null;
-
- /**
- * Number of emtpy days before real days begin in month
- * @var int
- * @access private
- */
- var $emptyBefore = 0;
-
- /**
- * Constructs Calendar_Table_Helper
- * @param object Calendar_Month_Weekdays, Calendar_Month_Weeks, Calendar_Week
- * @param int (optional) first day of the week e.g. 1 for Monday
- * @access protected
- */
- function Calendar_Table_Helper(& $calendar, $firstDay=null)
- {
- $this->calendar = & $calendar;
- $this->cE = & $calendar->getEngine();
- if (is_null($firstDay)) {
- $firstDay = $this->cE->getFirstDayOfWeek(
- $this->calendar->thisYear(),
- $this->calendar->thisMonth(),
- $this->calendar->thisDay()
- );
- }
- $this->firstDay = $firstDay;
- $this->setFirstDay();
- $this->setDaysOfMonth();
- }
-
- /**
- * Constructs $this->daysOfWeek based on $this->firstDay
- * @return void
- * @access private
- */
- function setFirstDay()
- {
- $weekDays = $this->cE->getWeekDays(
- $this->calendar->thisYear(),
- $this->calendar->thisMonth(),
- $this->calendar->thisDay()
- );
- $endDays = array();
- $tmpDays = array();
- $begin = false;
- foreach ($weekDays as $day) {
- if ($begin) {
- $endDays[] = $day;
- } else if ($day === $this->firstDay) {
- $begin = true;
- $endDays[] = $day;
- } else {
- $tmpDays[] = $day;
- }
- }
- $this->daysOfWeek = array_merge($endDays, $tmpDays);
- }
-
- /**
- * Constructs $this->daysOfMonth
- * @return void
- * @access private
- */
- function setDaysOfMonth()
- {
- $this->daysOfMonth = $this->daysOfWeek;
- $daysInMonth = $this->cE->getDaysInMonth(
- $this->calendar->thisYear(), $this->calendar->thisMonth());
- $firstDayInMonth = $this->cE->getFirstDayInMonth(
- $this->calendar->thisYear(), $this->calendar->thisMonth());
- $this->emptyBefore=0;
- foreach ($this->daysOfMonth as $dayOfWeek) {
- if ($firstDayInMonth == $dayOfWeek) {
- break;
- }
- $this->emptyBefore++;
- }
- $this->numWeeks = ceil(
- ($daysInMonth + $this->emptyBefore)
- /
- $this->cE->getDaysInWeek(
- $this->calendar->thisYear(),
- $this->calendar->thisMonth(),
- $this->calendar->thisDay()
- )
- );
- for ($i=1; $i < $this->numWeeks; $i++) {
- $this->daysOfMonth =
- array_merge($this->daysOfMonth, $this->daysOfWeek);
- }
- }
-
- /**
- * Returns the first day of the month
- * @see Calendar_Engine_Interface::getFirstDayOfWeek()
- * @return int
- * @access protected
- */
- function getFirstDay()
- {
- return $this->firstDay;
- }
-
- /**
- * Returns the order array of days in a week
- * @return int
- * @access protected
- */
- function getDaysOfWeek()
- {
- return $this->daysOfWeek;
- }
-
- /**
- * Returns the number of tabular weeks in a month
- * @return int
- * @access protected
- */
- function getNumWeeks()
- {
- return $this->numWeeks;
- }
-
- /**
- * Returns the number of real days + empty days
- * @return int
- * @access protected
- */
- function getNumTableDaysInMonth()
- {
- return count($this->daysOfMonth);
- }
-
- /**
- * Returns the number of empty days before the real days begin
- * @return int
- * @access protected
- */
- function getEmptyDaysBefore()
- {
- return $this->emptyBefore;
- }
-
- /**
- * Returns the index of the last real day in the month
- * @todo Potential performance optimization with static
- * @return int
- * @access protected
- */
- function getEmptyDaysAfter()
- {
- // Causes bug when displaying more than one month
-// static $index;
-// if (!isset($index)) {
- $index = $this->getEmptyDaysBefore() + $this->cE->getDaysInMonth(
- $this->calendar->thisYear(), $this->calendar->thisMonth());
-// }
- return $index;
- }
-
- /**
- * Returns the index of the last real day in the month, relative to the
- * beginning of the tabular week it is part of
- * @return int
- * @access protected
- */
- function getEmptyDaysAfterOffset()
- {
- $eAfter = $this->getEmptyDaysAfter();
- return $eAfter - (
- $this->cE->getDaysInWeek(
- $this->calendar->thisYear(),
- $this->calendar->thisMonth(),
- $this->calendar->thisDay()
- ) * ($this->numWeeks-1) );
- }
-
- /**
- * Returns the timestamp of the first day of the current week
- */
- function getWeekStart($y, $m, $d, $firstDay=1)
- {
- $dow = $this->cE->getDayOfWeek($y, $m, $d);
- if ($dow > $firstDay) {
- $d -= ($dow - $firstDay);
- }
- if ($dow < $firstDay) {
- $d -= (
- $this->cE->getDaysInWeek(
- $this->calendar->thisYear(),
- $this->calendar->thisMonth(),
- $this->calendar->thisDay()
- ) - $firstDay + $dow);
- }
- return $this->cE->dateToStamp($y, $m, $d);
- }
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Harry Fuecks <hfuecks@phppatterns.com> |
-// | Lorenzo Alberton <l dot alberton at quipo dot it> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Textual.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
-//
-/**
- * @package Calendar
- * @version $Id: Textual.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- */
-
-/**
- * Allows Calendar include path to be redefined
- * @ignore
- */
-if (!defined('CALENDAR_ROOT')) {
- define('CALENDAR_ROOT', 'Calendar'.DIRECTORY_SEPARATOR);
-}
-
-/**
- * Load Calendar decorator base class
- */
-require_once CALENDAR_ROOT.'Decorator.php';
-
-/**
- * Static utlities to help with fetching textual representations of months and
- * days of the week.
- * @package Calendar
- * @access public
- */
-class Calendar_Util_Textual
-{
-
- /**
- * Returns an array of 12 month names (first index = 1)
- * @param string (optional) format of returned months (one,two,short or long)
- * @return array
- * @access public
- * @static
- */
- function monthNames($format='long')
- {
- $formats = array('one'=>'%b', 'two'=>'%b', 'short'=>'%b', 'long'=>'%B');
- if (!array_key_exists($format,$formats)) {
- $format = 'long';
- }
- $months = array();
- for ($i=1; $i<=12; $i++) {
- $stamp = mktime(0, 0, 0, $i, 1, 2003);
- $month = strftime($formats[$format], $stamp);
- switch($format) {
- case 'one':
- $month = substr($month, 0, 1);
- break;
- case 'two':
- $month = substr($month, 0, 2);
- break;
- }
- $months[$i] = $month;
- }
- return $months;
- }
-
- /**
- * Returns an array of 7 week day names (first index = 0)
- * @param string (optional) format of returned days (one,two,short or long)
- * @return array
- * @access public
- * @static
- */
- function weekdayNames($format='long')
- {
- $formats = array('one'=>'%a', 'two'=>'%a', 'short'=>'%a', 'long'=>'%A');
- if (!array_key_exists($format,$formats)) {
- $format = 'long';
- }
- $days = array();
- for ($i=0; $i<=6; $i++) {
- $stamp = mktime(0, 0, 0, 11, $i+2, 2003);
- $day = strftime($formats[$format], $stamp);
- switch($format) {
- case 'one':
- $day = substr($day, 0, 1);
- break;
- case 'two':
- $day = substr($day, 0, 2);
- break;
- }
- $days[$i] = $day;
- }
- return $days;
- }
-
- /**
- * Returns textual representation of the previous month of the decorated calendar object
- * @param object subclass of Calendar e.g. Calendar_Month
- * @param string (optional) format of returned months (one,two,short or long)
- * @return string
- * @access public
- * @static
- */
- function prevMonthName($Calendar, $format='long')
- {
- $months = Calendar_Util_Textual::monthNames($format);
- return $months[$Calendar->prevMonth()];
- }
-
- /**
- * Returns textual representation of the month of the decorated calendar object
- * @param object subclass of Calendar e.g. Calendar_Month
- * @param string (optional) format of returned months (one,two,short or long)
- * @return string
- * @access public
- * @static
- */
- function thisMonthName($Calendar, $format='long')
- {
- $months = Calendar_Util_Textual::monthNames($format);
- return $months[$Calendar->thisMonth()];
- }
-
- /**
- * Returns textual representation of the next month of the decorated calendar object
- * @param object subclass of Calendar e.g. Calendar_Month
- * @param string (optional) format of returned months (one,two,short or long)
- * @return string
- * @access public
- * @static
- */
- function nextMonthName($Calendar, $format='long')
- {
- $months = Calendar_Util_Textual::monthNames($format);
- return $months[$Calendar->nextMonth()];
- }
-
- /**
- * Returns textual representation of the previous day of week of the decorated calendar object
- * <b>Note:</b> Requires PEAR::Date
- * @param object subclass of Calendar e.g. Calendar_Month
- * @param string (optional) format of returned months (one,two,short or long)
- * @return string
- * @access public
- * @static
- */
- function prevDayName($Calendar, $format='long')
- {
- $days = Calendar_Util_Textual::weekdayNames($format);
- $stamp = $Calendar->prevDay('timestamp');
- $cE = $Calendar->getEngine();
- require_once 'Date/Calc.php';
- $day = Date_Calc::dayOfWeek($cE->stampToDay($stamp),
- $cE->stampToMonth($stamp), $cE->stampToYear($stamp));
- return $days[$day];
- }
-
- /**
- * Returns textual representation of the day of week of the decorated calendar object
- * <b>Note:</b> Requires PEAR::Date
- * @param object subclass of Calendar e.g. Calendar_Month
- * @param string (optional) format of returned months (one,two,short or long)
- * @return string
- * @access public
- * @static
- */
- function thisDayName($Calendar, $format='long')
- {
- $days = Calendar_Util_Textual::weekdayNames($format);
- require_once 'Date/Calc.php';
- $day = Date_Calc::dayOfWeek($Calendar->thisDay(), $Calendar->thisMonth(), $Calendar->thisYear());
- return $days[$day];
- }
-
- /**
- * Returns textual representation of the next day of week of the decorated calendar object
- * @param object subclass of Calendar e.g. Calendar_Month
- * @param string (optional) format of returned months (one,two,short or long)
- * @return string
- * @access public
- * @static
- */
- function nextDayName($Calendar, $format='long')
- {
- $days = Calendar_Util_Textual::weekdayNames($format);
- $stamp = $Calendar->nextDay('timestamp');
- $cE = $Calendar->getEngine();
- require_once 'Date/Calc.php';
- $day = Date_Calc::dayOfWeek($cE->stampToDay($stamp),
- $cE->stampToMonth($stamp), $cE->stampToYear($stamp));
- return $days[$day];
- }
-
- /**
- * Returns the days of the week using the order defined in the decorated
- * calendar object. Only useful for Calendar_Month_Weekdays, Calendar_Month_Weeks
- * and Calendar_Week. Otherwise the returned array will begin on Sunday
- * @param object subclass of Calendar e.g. Calendar_Month
- * @param string (optional) format of returned months (one,two,short or long)
- * @return array ordered array of week day names
- * @access public
- * @static
- */
- function orderedWeekdays($Calendar, $format='long')
- {
- $days = Calendar_Util_Textual::weekdayNames($format);
-
- // Not so good - need methods to access this information perhaps...
- if (isset($Calendar->tableHelper)) {
- $ordereddays = $Calendar->tableHelper->daysOfWeek;
- } else {
- $ordereddays = array(0, 1, 2, 3, 4, 5, 6);
- }
-
- $ordereddays = array_flip($ordereddays);
- $i = 0;
- $returndays = array();
- foreach ($ordereddays as $key => $value) {
- $returndays[$i] = $days[$key];
- $i++;
- }
- return $returndays;
- }
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-//
-// +----------------------------------------------------------------------+
-// | PHP |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Harry Fuecks <hfuecks@phppatterns.com> |
-// | Lorenzo Alberton <l dot alberton at quipo dot it> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Uri.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
-//
-/**
- * @package Calendar
- * @version $Id: Uri.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- */
-
-/**
- * Utility to help building HTML links for navigating the calendar<br />
- * <code>
- * $Day = new Calendar_Day(2003, 10, 23);
- * $Uri = & new Calendar_Util_Uri('year', 'month', 'day');
- * echo $Uri->prev($Day,'month'); // Displays year=2003&month=10
- * echo $Uri->prev($Day,'day'); // Displays year=2003&month=10&day=22
- * $Uri->seperator = '/';
- * $Uri->scalar = true;
- * echo $Uri->prev($Day,'month'); // Displays 2003/10
- * echo $Uri->prev($Day,'day'); // Displays 2003/10/22
- * </code>
- * @package Calendar
- * @access public
- */
-class Calendar_Util_Uri
-{
- /**
- * Uri fragments for year, month, day etc.
- * @var array
- * @access private
- */
- var $uris = array();
-
- /**
- * String to separate fragments with.
- * Set to just & for HTML.
- * For a scalar URL you might use / as the seperator
- * @var string (default XHTML &)
- * @access public
- */
- var $separator = '&';
-
- /**
- * To output a "scalar" string - variable names omitted.
- * Used for urls like index.php/2004/8/12
- * @var boolean (default false)
- * @access public
- */
- var $scalar = false;
-
- /**
- * Constructs Calendar_Decorator_Uri
- * The term "fragment" means <i>name</i> of a calendar GET variables in the URL
- * @param string URI fragment for year
- * @param string (optional) URI fragment for month
- * @param string (optional) URI fragment for day
- * @param string (optional) URI fragment for hour
- * @param string (optional) URI fragment for minute
- * @param string (optional) URI fragment for second
- * @access public
- */
- function Calendar_Util_Uri($y, $m=null, $d=null, $h=null, $i=null, $s=null)
- {
- $this->setFragments($y, $m, $d, $h, $i, $s);
- }
-
- /**
- * Sets the URI fragment names
- * @param string URI fragment for year
- * @param string (optional) URI fragment for month
- * @param string (optional) URI fragment for day
- * @param string (optional) URI fragment for hour
- * @param string (optional) URI fragment for minute
- * @param string (optional) URI fragment for second
- * @return void
- * @access public
- */
- function setFragments($y, $m=null, $d=null, $h=null, $i=null, $s=null) {
- if (!is_null($y)) $this->uris['Year'] = $y;
- if (!is_null($m)) $this->uris['Month'] = $m;
- if (!is_null($d)) $this->uris['Day'] = $d;
- if (!is_null($h)) $this->uris['Hour'] = $h;
- if (!is_null($i)) $this->uris['Minute'] = $i;
- if (!is_null($s)) $this->uris['Second'] = $s;
- }
-
- /**
- * Gets the URI string for the previous calendar unit
- * @param object subclassed from Calendar e.g. Calendar_Month
- * @param string calendar unit ( must be year, month, week, day, hour, minute or second)
- * @return string
- * @access public
- */
- function prev($Calendar, $unit)
- {
- $method = 'prev'.$unit;
- $stamp = $Calendar->{$method}('timestamp');
- return $this->buildUriString($Calendar, $method, $stamp);
- }
-
- /**
- * Gets the URI string for the current calendar unit
- * @param object subclassed from Calendar e.g. Calendar_Month
- * @param string calendar unit ( must be year, month, week, day, hour, minute or second)
- * @return string
- * @access public
- */
- function this($Calendar, $unit)
- {
- $method = 'this'.$unit;
- $stamp = $Calendar->{$method}('timestamp');
- return $this->buildUriString($Calendar, $method, $stamp);
- }
-
- /**
- * Gets the URI string for the next calendar unit
- * @param object subclassed from Calendar e.g. Calendar_Month
- * @param string calendar unit ( must be year, month, week, day, hour, minute or second)
- * @return string
- * @access public
- */
- function next($Calendar, $unit)
- {
- $method = 'next'.$unit;
- $stamp = $Calendar->{$method}('timestamp');
- return $this->buildUriString($Calendar, $method, $stamp);
- }
-
- /**
- * Build the URI string
- * @param string method substring
- * @param int timestamp
- * @return string build uri string
- * @access private
- */
- function buildUriString($Calendar, $method, $stamp)
- {
- $uriString = '';
- $cE = & $Calendar->getEngine();
- $separator = '';
- foreach ($this->uris as $unit => $uri) {
- $call = 'stampTo'.$unit;
- $uriString .= $separator;
- if (!$this->scalar) $uriString .= $uri.'=';
- $uriString .= $cE->{$call}($stamp);
- $separator = $this->separator;
- }
- return $uriString;
- }
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Harry Fuecks <hfuecks@phppatterns.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Validator.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
-//
-/**
- * @package Calendar
- * @version $Id: Validator.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- */
-
-/**
- * Validation Error Messages
- */
-if (!defined('CALENDAR_VALUE_TOOSMALL')) {
- define('CALENDAR_VALUE_TOOSMALL', 'Too small: min = ');
-}
-if (!defined('CALENDAR_VALUE_TOOLARGE')) {
- define('CALENDAR_VALUE_TOOLARGE', 'Too large: max = ');
-}
-
-/**
- * Used to validate any given Calendar date object. Instances of this class
- * can be obtained from any data object using the getValidator method
- * @see Calendar::getValidator()
- * @package Calendar
- * @access public
- */
-class Calendar_Validator
-{
- /**
- * Instance of the Calendar date object to validate
- * @var object
- * @access private
- */
- var $calendar;
-
- /**
- * Instance of the Calendar_Engine
- * @var object
- * @access private
- */
- var $cE;
-
- /**
- * Array of errors for validation failures
- * @var array
- * @access private
- */
- var $errors = array();
-
- /**
- * Constructs Calendar_Validator
- * @param object subclass of Calendar
- * @access public
- */
- function Calendar_Validator(& $calendar)
- {
- $this->calendar = & $calendar;
- $this->cE = & $calendar->getEngine();
- }
-
- /**
- * Calls all the other isValidXXX() methods in the validator
- * @return boolean
- * @access public
- */
- function isValid()
- {
- $checks = array('isValidYear', 'isValidMonth', 'isValidDay',
- 'isValidHour', 'isValidMinute', 'isValidSecond');
- $valid = true;
- foreach ($checks as $check) {
- if (!$this->{$check}()) {
- $valid = false;
- }
- }
- return $valid;
- }
-
- /**
- * Check whether this is a valid year
- * @return boolean
- * @access public
- */
- function isValidYear()
- {
- $y = $this->calendar->thisYear();
- $min = $this->cE->getMinYears();
- if ($min > $y) {
- $this->errors[] = new Calendar_Validation_Error(
- 'Year', $y, CALENDAR_VALUE_TOOSMALL.$min);
- return false;
- }
- $max = $this->cE->getMaxYears();
- if ($y > $max) {
- $this->errors[] = new Calendar_Validation_Error(
- 'Year', $y, CALENDAR_VALUE_TOOLARGE.$max);
- return false;
- }
- return true;
- }
-
- /**
- * Check whether this is a valid month
- * @return boolean
- * @access public
- */
- function isValidMonth()
- {
- $m = $this->calendar->thisMonth();
- $min = 1;
- if ($min > $m) {
- $this->errors[] = new Calendar_Validation_Error(
- 'Month', $m, CALENDAR_VALUE_TOOSMALL.$min);
- return false;
- }
- $max = $this->cE->getMonthsInYear($this->calendar->thisYear());
- if ($m > $max) {
- $this->errors[] = new Calendar_Validation_Error(
- 'Month', $m, CALENDAR_VALUE_TOOLARGE.$max);
- return false;
- }
- return true;
- }
-
- /**
- * Check whether this is a valid day
- * @return boolean
- * @access public
- */
- function isValidDay()
- {
- $d = $this->calendar->thisDay();
- $min = 1;
- if ($min > $d) {
- $this->errors[] = new Calendar_Validation_Error(
- 'Day', $d, CALENDAR_VALUE_TOOSMALL.$min);
- return false;
- }
- $max = $this->cE->getDaysInMonth(
- $this->calendar->thisYear(), $this->calendar->thisMonth());
- if ($d > $max) {
- $this->errors[] = new Calendar_Validation_Error(
- 'Day', $d, CALENDAR_VALUE_TOOLARGE.$max);
- return false;
- }
- return true;
- }
-
- /**
- * Check whether this is a valid hour
- * @return boolean
- * @access public
- */
- function isValidHour()
- {
- $h = $this->calendar->thisHour();
- $min = 0;
- if ($min > $h) {
- $this->errors[] = new Calendar_Validation_Error(
- 'Hour', $h, CALENDAR_VALUE_TOOSMALL.$min);
- return false;
- }
- $max = ($this->cE->getHoursInDay($this->calendar->thisDay())-1);
- if ($h > $max) {
- $this->errors[] = new Calendar_Validation_Error(
- 'Hour', $h, CALENDAR_VALUE_TOOLARGE.$max);
- return false;
- }
- return true;
- }
-
- /**
- * Check whether this is a valid minute
- * @return boolean
- * @access public
- */
- function isValidMinute()
- {
- $i = $this->calendar->thisMinute();
- $min = 0;
- if ($min > $i) {
- $this->errors[] = new Calendar_Validation_Error(
- 'Minute', $i, CALENDAR_VALUE_TOOSMALL.$min);
- return false;
- }
- $max = ($this->cE->getMinutesInHour($this->calendar->thisHour())-1);
- if ($i > $max) {
- $this->errors[] = new Calendar_Validation_Error(
- 'Minute', $i, CALENDAR_VALUE_TOOLARGE.$max);
- return false;
- }
- return true;
- }
-
- /**
- * Check whether this is a valid second
- * @return boolean
- * @access public
- */
- function isValidSecond()
- {
- $s = $this->calendar->thisSecond();
- $min = 0;
- if ($min > $s) {
- $this->errors[] = new Calendar_Validation_Error(
- 'Second', $s, CALENDAR_VALUE_TOOSMALL.$min);
- return false;
- }
- $max = ($this->cE->getSecondsInMinute($this->calendar->thisMinute())-1);
- if ($s > $max) {
- $this->errors[] = new Calendar_Validation_Error(
- 'Second', $s, CALENDAR_VALUE_TOOLARGE.$max);
- return false;
- }
- return true;
- }
-
- /**
- * Iterates over any validation errors
- * @return mixed either Calendar_Validation_Error or false
- * @access public
- */
- function fetch()
- {
- $error = each ($this->errors);
- if ($error) {
- return $error['value'];
- } else {
- reset($this->errors);
- return false;
- }
- }
-}
-
-/**
- * For Validation Error messages
- * @see Calendar::fetch()
- * @package Calendar
- * @access public
- */
-class Calendar_Validation_Error
-{
- /**
- * Date unit (e.g. month,hour,second) which failed test
- * @var string
- * @access private
- */
- var $unit;
-
- /**
- * Value of unit which failed test
- * @var int
- * @access private
- */
- var $value;
-
- /**
- * Validation error message
- * @var string
- * @access private
- */
- var $message;
-
- /**
- * Constructs Calendar_Validation_Error
- * @param string Date unit (e.g. month,hour,second)
- * @param int Value of unit which failed test
- * @param string Validation error message
- * @access protected
- */
- function Calendar_Validation_Error($unit,$value,$message)
- {
- $this->unit = $unit;
- $this->value = $value;
- $this->message = $message;
- }
-
- /**
- * Returns the Date unit
- * @return string
- * @access public
- */
- function getUnit()
- {
- return $this->unit;
- }
-
- /**
- * Returns the value of the unit
- * @return int
- * @access public
- */
- function getValue()
- {
- return $this->value;
- }
-
- /**
- * Returns the validation error message
- * @return string
- * @access public
- */
- function getMessage()
- {
- return $this->message;
- }
-
- /**
- * Returns a string containing the unit, value and error message
- * @return string
- * @access public
- */
- function toString ()
- {
- return $this->unit.' = '.$this->value.' ['.$this->message.']';
- }
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Harry Fuecks <hfuecks@phppatterns.com> |
-// | Lorenzo Alberton <l dot alberton at quipo dot it> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Week.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
-//
-/**
- * @package Calendar
- * @version $Id: Week.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- */
-
-/**
- * Allows Calendar include path to be redefined
- * @ignore
- */
-if (!defined('CALENDAR_ROOT')) {
- define('CALENDAR_ROOT', 'Calendar'.DIRECTORY_SEPARATOR);
-}
-
-/**
- * Load Calendar base class
- */
-require_once CALENDAR_ROOT.'Calendar.php';
-
-/**
- * Represents a Week and builds Days in tabular format<br>
- * <code>
- * require_once 'Calendar'.DIRECTORY_SEPARATOR.'Week.php';
- * $Week = & new Calendar_Week(2003, 10, 1); Oct 2003, 1st tabular week
- * echo '<tr>';
- * while ($Day = & $Week->fetch()) {
- * if ($Day->isEmpty()) {
- * echo '<td> </td>';
- * } else {
- * echo '<td>'.$Day->thisDay().'</td>';
- * }
- * }
- * echo '</tr>';
- * </code>
- * @package Calendar
- * @access public
- */
-class Calendar_Week extends Calendar
-{
- /**
- * Instance of Calendar_Table_Helper
- * @var Calendar_Table_Helper
- * @access private
- */
- var $tableHelper;
-
- /**
- * Stores the timestamp of the first day of this week
- * @access private
- * @var object
- */
- var $thisWeek;
-
- /**
- * Stores the timestamp of first day of previous week
- * @access private
- * @var object
- */
- var $prevWeek;
-
- /**
- * Stores the timestamp of first day of next week
- * @access private
- * @var object
- */
- var $nextWeek;
-
- /**
- * Used by build() to set empty days
- * @access private
- * @var boolean
- */
- var $firstWeek = false;
-
- /**
- * Used by build() to set empty days
- * @access private
- * @var boolean
- */
- var $lastWeek = false;
-
- /**
- * First day of the week (0=sunday, 1=monday...)
- * @access private
- * @var boolean
- */
- var $firstDay = 1;
-
- /**
- * Constructs Week
- * @param int year e.g. 2003
- * @param int month e.g. 5
- * @param int a day of the desired week
- * @param int (optional) first day of week (e.g. 0 for Sunday, 2 for Tuesday etc.)
- * @access public
- */
- function Calendar_Week($y, $m, $d, $firstDay=null)
- {
- require_once CALENDAR_ROOT.'Table/Helper.php';
- Calendar::Calendar($y, $m, $d);
- $this->firstDay = $this->defineFirstDayOfWeek($firstDay);
- $this->tableHelper = & new Calendar_Table_Helper($this, $this->firstDay);
- $this->thisWeek = $this->tableHelper->getWeekStart($y, $m, $d, $this->firstDay);
- $this->prevWeek = $this->tableHelper->getWeekStart($y, $m, $d - $this->cE->getDaysInWeek(
- $this->thisYear(),
- $this->thisMonth(),
- $this->thisDay()), $this->firstDay);
- $this->nextWeek = $this->tableHelper->getWeekStart($y, $m, $d + $this->cE->getDaysInWeek(
- $this->thisYear(),
- $this->thisMonth(),
- $this->thisDay()), $this->firstDay);
- }
-
- /**
- * Defines the calendar by a timestamp (Unix or ISO-8601), replacing values
- * passed to the constructor
- * @param int|string Unix or ISO-8601 timestamp
- * @return void
- * @access public
- */
- function setTimestamp($ts)
- {
- parent::setTimestamp($ts);
- $this->thisWeek = $this->tableHelper->getWeekStart(
- $this->year, $this->month, $this->day, $this->firstDay
- );
- $this->prevWeek = $this->tableHelper->getWeekStart(
- $this->year, $this->month, $this->day - $this->cE->getDaysInWeek(
- $this->thisYear(),
- $this->thisMonth(),
- $this->thisDay()), $this->firstDay
- );
- $this->nextWeek = $this->tableHelper->getWeekStart(
- $this->year, $this->month, $this->day + $this->cE->getDaysInWeek(
- $this->thisYear(),
- $this->thisMonth(),
- $this->thisDay()), $this->firstDay
- );
- }
-
- /**
- * Builds Calendar_Day objects for this Week
- * @param array (optional) Calendar_Day objects representing selected dates
- * @return boolean
- * @access public
- */
- function build($sDates = array())
- {
- require_once CALENDAR_ROOT.'Day.php';
- $year = $this->cE->stampToYear($this->thisWeek);
- $month = $this->cE->stampToMonth($this->thisWeek);
- $day = $this->cE->stampToDay($this->thisWeek);
- $end = $this->cE->getDaysInWeek(
- $this->thisYear(),
- $this->thisMonth(),
- $this->thisDay()
- );
-
- for ($i=1; $i <= $end; $i++) {
- $stamp = $this->cE->dateToStamp($year, $month, $day++);
- $this->children[$i] = new Calendar_Day(
- $this->cE->stampToYear($stamp),
- $this->cE->stampToMonth($stamp),
- $this->cE->stampToDay($stamp));
- }
-
- //set empty days (@see Calendar_Month_Weeks::build())
- if ($this->firstWeek) {
- $eBefore = $this->tableHelper->getEmptyDaysBefore();
- for ($i=1; $i <= $eBefore; $i++) {
- $this->children[$i]->setEmpty();
- }
- }
- if ($this->lastWeek) {
- $eAfter = $this->tableHelper->getEmptyDaysAfterOffset();
- for ($i = $eAfter+1; $i <= $end; $i++) {
- $this->children[$i]->setEmpty();
- }
- }
-
- if (count($sDates) > 0) {
- $this->setSelection($sDates);
- }
- return true;
- }
-
- /**
- * @param boolean
- * @return void
- * @access private
- */
- function setFirst($state=true)
- {
- $this->firstWeek = $state;
- }
-
- /**
- * @param boolean
- * @return void
- * @access private
- */
- function setLast($state=true)
- {
- $this->lastWeek = $state;
- }
-
- /**
- * Called from build()
- * @param array
- * @return void
- * @access private
- */
- function setSelection($sDates)
- {
- foreach ($sDates as $sDate) {
- foreach ($this->children as $key => $child) {
- if ($child->thisDay() == $sDate->thisDay() &&
- $child->thisMonth() == $sDate->thisMonth() &&
- $child->thisYear() == $sDate->thisYear()
- ) {
- $this->children[$key] = $sDate;
- $this->children[$key]->setSelected();
- }
- }
- }
- reset($this->children);
- }
-
- /**
- * Gets the value of the previous week, according to the requested format
- *
- * @param string $format ['timestamp' | 'n_in_month' | 'n_in_year' | 'array']
- * @return mixed
- * @access public
- */
- function prevWeek($format = 'n_in_month')
- {
- switch (strtolower($format)) {
- case 'int':
- case 'n_in_month':
- return ($this->firstWeek) ? null : $this->thisWeek('n_in_month') -1;
- break;
- case 'n_in_year':
- return $this->cE->getWeekNInYear(
- $this->cE->stampToYear($this->prevWeek),
- $this->cE->stampToMonth($this->prevWeek),
- $this->cE->stampToDay($this->prevWeek));
- break;
- case 'array':
- return $this->toArray($this->prevWeek);
- break;
- case 'object':
- require_once CALENDAR_ROOT.'Factory.php';
- return Calendar_Factory::createByTimestamp('Week', $this->prevWeek);
- break;
- case 'timestamp':
- default:
- return $this->prevWeek;
- break;
- }
- }
-
- /**
- * Gets the value of the current week, according to the requested format
- *
- * @param string $format ['timestamp' | 'n_in_month' | 'n_in_year' | 'array']
- * @return mixed
- * @access public
- */
- function thisWeek($format = 'n_in_month')
- {
- switch (strtolower($format)) {
- case 'int':
- case 'n_in_month':
- if ($this->firstWeek) {
- return 1;
- }
- if ($this->lastWeek) {
- return $this->cE->getWeeksInMonth(
- $this->thisYear(),
- $this->thisMonth(),
- $this->firstDay);
- }
- return $this->cE->getWeekNInMonth(
- $this->thisYear(),
- $this->thisMonth(),
- $this->thisDay(),
- $this->firstDay);
- break;
- case 'n_in_year':
- return $this->cE->getWeekNInYear(
- $this->cE->stampToYear($this->thisWeek),
- $this->cE->stampToMonth($this->thisWeek),
- $this->cE->stampToDay($this->thisWeek));
- break;
- case 'array':
- return $this->toArray($this->thisWeek);
- break;
- case 'object':
- require_once CALENDAR_ROOT.'Factory.php';
- return Calendar_Factory::createByTimestamp('Week', $this->thisWeek);
- break;
- case 'timestamp':
- default:
- return $this->thisWeek;
- break;
- }
- }
-
- /**
- * Gets the value of the following week, according to the requested format
- *
- * @param string $format ['timestamp' | 'n_in_month' | 'n_in_year' | 'array']
- * @return mixed
- * @access public
- */
- function nextWeek($format = 'n_in_month')
- {
- switch (strtolower($format)) {
- case 'int':
- case 'n_in_month':
- return ($this->lastWeek) ? null : $this->thisWeek('n_in_month') +1;
- break;
- case 'n_in_year':
- return $this->cE->getWeekNInYear(
- $this->cE->stampToYear($this->nextWeek),
- $this->cE->stampToMonth($this->nextWeek),
- $this->cE->stampToDay($this->nextWeek));
- break;
- case 'array':
- return $this->toArray($this->nextWeek);
- break;
- case 'object':
- require_once CALENDAR_ROOT.'Factory.php';
- return Calendar_Factory::createByTimestamp('Week', $this->nextWeek);
- break;
- case 'timestamp':
- default:
- return $this->nextWeek;
- break;
- }
- }
-
- /**
- * Returns the instance of Calendar_Table_Helper.
- * Called from Calendar_Validator::isValidWeek
- * @return Calendar_Table_Helper
- * @access protected
- */
- function & getHelper()
- {
- return $this->tableHelper;
- }
-
- /**
- * Makes sure theres a value for $this->day
- * @return void
- * @access private
- */
- function findFirstDay()
- {
- if (!count($this->children) > 0) {
- $this->build();
- foreach ($this->children as $Day) {
- if (!$Day->isEmpty()) {
- $this->day = $Day->thisDay();
- break;
- }
- }
- }
- }
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Harry Fuecks <hfuecks@phppatterns.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Year.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
-//
-/**
- * @package Calendar
- * @version $Id: Year.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- */
-
-/**
- * Allows Calendar include path to be redefined
- * @ignore
- */
-if (!defined('CALENDAR_ROOT')) {
- define('CALENDAR_ROOT', 'Calendar'.DIRECTORY_SEPARATOR);
-}
-
-/**
- * Load Calendar base class
- */
-require_once CALENDAR_ROOT.'Calendar.php';
-
-/**
- * Represents a Year and builds Months<br>
- * <code>
- * require_once 'Calendar'.DIRECTORY_SEPARATOR.'Year.php';
- * $Year = & new Calendar_Year(2003, 10, 21); // 21st Oct 2003
- * $Year->build(); // Build Calendar_Month objects
- * while ($Month = & $Year->fetch()) {
- * echo $Month->thisMonth().'<br />';
- * }
- * </code>
- * @package Calendar
- * @access public
- */
-class Calendar_Year extends Calendar
-{
- /**
- * Constructs Calendar_Year
- * @param int year e.g. 2003
- * @access public
- */
- function Calendar_Year($y)
- {
- Calendar::Calendar($y);
- }
-
- /**
- * Builds the Months of the Year.<br>
- * <b>Note:</b> by defining the constant CALENDAR_MONTH_STATE you can
- * control what class of Calendar_Month is built e.g.;
- * <code>
- * require_once 'Calendar/Calendar_Year.php';
- * define ('CALENDAR_MONTH_STATE',CALENDAR_USE_MONTH_WEEKDAYS); // Use Calendar_Month_Weekdays
- * // define ('CALENDAR_MONTH_STATE',CALENDAR_USE_MONTH_WEEKS); // Use Calendar_Month_Weeks
- * // define ('CALENDAR_MONTH_STATE',CALENDAR_USE_MONTH); // Use Calendar_Month
- * </code>
- * It defaults to building Calendar_Month objects.
- * @param array (optional) array of Calendar_Month objects representing selected dates
- * @param int (optional) first day of week (e.g. 0 for Sunday, 2 for Tuesday etc.)
- * @return boolean
- * @access public
- */
- function build($sDates = array(), $firstDay = null)
- {
- require_once CALENDAR_ROOT.'Factory.php';
- $this->firstDay = $this->defineFirstDayOfWeek($firstDay);
- $monthsInYear = $this->cE->getMonthsInYear($this->thisYear());
- for ($i=1; $i <= $monthsInYear; $i++) {
- $this->children[$i] = Calendar_Factory::create('Month', $this->year, $i);
- }
- if (count($sDates) > 0) {
- $this->setSelection($sDates);
- }
- return true;
- }
-
- /**
- * Called from build()
- * @param array
- * @return void
- * @access private
- */
- function setSelection($sDates) {
- foreach ($sDates as $sDate) {
- if ($this->year == $sDate->thisYear()) {
- $key = $sDate->thisMonth();
- if (isset($this->children[$key])) {
- $sDate->setSelected();
- $this->children[$key] = $sDate;
- }
- }
- }
- }
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * A simple HTTP client class.
- *
- * PHP versions 4 and 5
- *
- * LICENSE:
- *
- * Copyright (c) 2003-2007, Alexey Borzov <avb@php.net>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * @category HTTP
- * @package HTTP_Client
- * @author Alexey Borzov <avb@php.net>
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: Client.php,v 1.1.1.1 2008/04/28 15:20:46 jamie Exp $
- * @link http://pear.php.net/package/HTTP_Client
- */
-
-/*
- * Do this define in your script if you wish HTTP_Client to follow browser
- * quirks rather than HTTP specification (RFC2616). This means:
- * - do a GET request after redirect with code 301, rather than use the
- * same method as before redirect.
- */
-// define('HTTP_CLIENT_QUIRK_MODE', true);
-
-/**
- * Class for performing HTTP requests
- */
-require_once 'HTTP/Request.php';
-/**
- * Class used to store cookies and pass them between HTTP requests.
- */
-require_once 'HTTP/Client/CookieManager.php';
-
-/**
- * A simple HTTP client class.
- *
- * The class wraps around HTTP_Request providing a higher-level
- * API for performing multiple HTTP requests
- *
- * @category HTTP
- * @package HTTP_Client
- * @author Alexey Borzov <avb@php.net>
- * @version Release: 1.1.1
- */
-class HTTP_Client
-{
- /**#@+
- * @access private
- */
- /**
- * Cookie manager object
- * @var HTTP_Client_CookieManager
- */
- var $_cookieManager;
-
- /**
- * Received HTTP responses
- * @var array
- */
- var $_responses;
-
- /**
- * Default headers to send on every request
- * @var array
- */
- var $_defaultHeaders = array();
-
- /**
- * Default parameters for HTTP_Request's constructor
- * @var array
- */
- var $_defaultRequestParams = array();
-
- /**
- * How many redirects were done
- * @var integer
- */
- var $_redirectCount = 0;
-
- /**
- * Maximum allowed redirects
- * @var integer
- */
- var $_maxRedirects = 5;
-
- /**
- * Listeners attached to the client
- * @var array
- */
- var $_listeners = array();
-
- /**
- * Whether the listener should be propagated to Request objects
- * @var array
- */
- var $_propagate = array();
-
- /**
- * Whether to keep all the responses or just the most recent one
- * @var boolean
- */
- var $_isHistoryEnabled = true;
- /**#@-*/
-
- /**
- * Constructor
- *
- * @access public
- * @param array Parameters to pass to HTTP_Request's constructor
- * @param array Default headers to send on every request
- * @param HTTP_Client_CookieManager Cookie manager object to use
- */
- function HTTP_Client($defaultRequestParams = null, $defaultHeaders = null, $cookieManager = null)
- {
- if (!empty($cookieManager) && is_a($cookieManager, 'HTTP_Client_CookieManager')) {
- $this->_cookieManager = $cookieManager;
- } else {
- $this->_cookieManager =& new HTTP_Client_CookieManager();
- }
- if (isset($defaultHeaders)) {
- $this->setDefaultHeader($defaultHeaders);
- }
- if (isset($defaultRequestParams)) {
- $this->setRequestParameter($defaultRequestParams);
- }
- }
-
-
- /**
- * Sets the maximum redirects that will be processed.
- *
- * Setting this to 0 disables redirect processing. If not 0 and the
- * number of redirects in a request is bigger than this number, then an
- * error will be raised.
- *
- * @access public
- * @param int Max number of redirects to process
- */
- function setMaxRedirects($value)
- {
- $this->_maxRedirects = $value;
- }
-
-
- /**
- * Sets whether to keep all the responses or just the most recent one
- *
- * @access public
- * @param bool Whether to enable history
- */
- function enableHistory($enable)
- {
- $this->_isHistoryEnabled = (bool)$enable;
- }
-
- /**
- * Creates a HTTP_Request objects, applying all the necessary defaults
- *
- * @param string URL
- * @param string Method, constants are defined in HTTP_Request
- * @param array Extra headers to send
- * @access private
- * @return HTTP_Request Request object with all defaults applied
- */
- function &_createRequest($url, $method = HTTP_REQUEST_METHOD_GET, $headers = array())
- {
- $req =& new HTTP_Request($url, $this->_defaultRequestParams);
- $req->setMethod($method);
- foreach ($this->_defaultHeaders as $name => $value) {
- $req->addHeader($name, $value);
- }
- foreach ($headers as $name => $value) {
- $req->addHeader($name, $value);
- }
- $this->_cookieManager->passCookies($req);
- foreach ($this->_propagate as $id => $propagate) {
- if ($propagate) {
- $req->attach($this->_listeners[$id]);
- }
- }
- return $req;
- }
-
-
- /**
- * Sends a 'HEAD' HTTP request
- *
- * @param string URL
- * @param array Extra headers to send
- * @access public
- * @return integer HTTP response code
- * @throws PEAR_Error
- */
- function head($url, $headers = array())
- {
- $request =& $this->_createRequest($url, HTTP_REQUEST_METHOD_HEAD, $headers);
- return $this->_performRequest($request);
- }
-
-
- /**
- * Sends a 'GET' HTTP request
- *
- * @param string URL
- * @param mixed additional data to send
- * @param boolean Whether the data is already urlencoded
- * @param array Extra headers to send
- * @access public
- * @return integer HTTP response code
- * @throws PEAR_Error
- */
- function get($url, $data = null, $preEncoded = false, $headers = array())
- {
- $request =& $this->_createRequest($url, HTTP_REQUEST_METHOD_GET, $headers);
- if (is_array($data)) {
- foreach ($data as $name => $value) {
- $request->addQueryString($name, $value, $preEncoded);
- }
- } elseif (isset($data)) {
- $request->addRawQueryString($data, $preEncoded);
- }
- return $this->_performRequest($request);
- }
-
-
- /**
- * Sends a 'POST' HTTP request
- *
- * @param string URL
- * @param mixed Data to send
- * @param boolean Whether the data is already urlencoded
- * @param array Files to upload. Elements of the array should have the form:
- * array(name, filename(s)[, content type]), see HTTP_Request::addFile()
- * @param array Extra headers to send
- * @access public
- * @return integer HTTP response code
- * @throws PEAR_Error
- */
- function post($url, $data, $preEncoded = false, $files = array(), $headers = array())
- {
- $request =& $this->_createRequest($url, HTTP_REQUEST_METHOD_POST, $headers);
- if (is_array($data)) {
- foreach ($data as $name => $value) {
- $request->addPostData($name, $value, $preEncoded);
- }
- } else {
- $request->addRawPostData($data, $preEncoded);
- }
- foreach ($files as $fileData) {
- $res = call_user_func_array(array(&$request, 'addFile'), $fileData);
- if (PEAR::isError($res)) {
- return $res;
- }
- }
- return $this->_performRequest($request);
- }
-
-
- /**
- * Sets default header(s) for HTTP requests
- *
- * @param mixed header name or array ('header name' => 'header value')
- * @param string header value if $name is not an array
- * @access public
- */
- function setDefaultHeader($name, $value = null)
- {
- if (is_array($name)) {
- $this->_defaultHeaders = array_merge($this->_defaultHeaders, $name);
- } else {
- $this->_defaultHeaders[$name] = $value;
- }
- }
-
-
- /**
- * Sets parameter(s) for HTTP requests
- *
- * @param mixed parameter name or array ('parameter name' => 'parameter value')
- * @param string parameter value if $name is not an array
- * @access public
- */
- function setRequestParameter($name, $value = null)
- {
- if (is_array($name)) {
- $this->_defaultRequestParams = array_merge($this->_defaultRequestParams, $name);
- } else {
- $this->_defaultRequestParams[$name] = $value;
- }
- }
-
-
- /**
- * Performs a request, processes redirects
- *
- * @param HTTP_Request Request object
- * @access private
- * @return integer HTTP response code
- * @throws PEAR_Error
- */
- function _performRequest(&$request)
- {
- // If this is not a redirect, notify the listeners of new request
- if (0 == $this->_redirectCount && !empty($request->_url)) {
- $this->_notify('request', $request->_url->getUrl());
- }
- if (PEAR::isError($err = $request->sendRequest())) {
- $this->_redirectCount = 0;
- return $err;
- }
- $this->_pushResponse($request);
-
- $code = $request->getResponseCode();
- if ($this->_maxRedirects > 0) {
- if (in_array($code, array(300, 301, 302, 303, 307))) {
- if ('' == ($location = $request->getResponseHeader('Location'))) {
- $this->_redirectCount = 0;
- return PEAR::raiseError("No 'Location' field on redirect");
- }
- // Bug #5759: do not try to follow non-HTTP redirects
- if (null === ($redirectUrl = $this->_redirectUrl($request->_url, $location))) {
- $this->_redirectCount = 0;
- return $code;
- }
- // Redirect via <meta http-equiv="Refresh"> tag, see request #5734
- } elseif (200 <= $code && $code < 300) {
- $redirectUrl = $this->_getMetaRedirect($request);
- }
- }
- if (!empty($redirectUrl)) {
- if (++$this->_redirectCount > $this->_maxRedirects) {
- $this->_redirectCount = 0;
- return PEAR::raiseError('Too many redirects');
- }
- // Notify of redirection
- $this->_notify('httpRedirect', $redirectUrl);
- // we access the private properties directly, as there are no accessors for them
- switch ($request->_method) {
- case HTTP_REQUEST_METHOD_POST:
- if (302 == $code || 303 == $code || (301 == $code && defined('HTTP_CLIENT_QUIRK_MODE'))) {
- return $this->get($redirectUrl);
- } else {
- $postFiles = array();
- foreach ($request->_postFiles as $name => $data) {
- $postFiles[] = array($name, $data['name'], $data['type']);
- }
- return $this->post($redirectUrl, $request->_postData, true, $postFiles);
- }
- case HTTP_REQUEST_METHOD_HEAD:
- return (303 == $code? $this->get($redirectUrl): $this->head($redirectUrl));
- case HTTP_REQUEST_METHOD_GET:
- default:
- return $this->get($redirectUrl);
- } // switch
-
- } else {
- $this->_redirectCount = 0;
- if (400 >= $code) {
- $this->_notify('httpSuccess');
- $this->setDefaultHeader('Referer', $request->_url->getUrl());
- // some result processing should go here
- } else {
- $this->_notify('httpError');
- }
- }
- return $code;
- }
-
-
- /**
- * Returns the most recent HTTP response
- *
- * @access public
- * @return array
- */
- function ¤tResponse()
- {
- return $this->_responses[count($this->_responses) - 1];
- }
-
-
- /**
- * Saves the server's response to responses list
- *
- * @param HTTP_Request Request object already containing the response
- * @access private
- */
- function _pushResponse(&$request)
- {
- $this->_cookieManager->updateCookies($request);
- $idx = $this->_isHistoryEnabled? count($this->_responses): 0;
- $this->_responses[$idx] = array(
- 'code' => $request->getResponseCode(),
- 'headers' => $request->getResponseHeader(),
- 'body' => $request->getResponseBody()
- );
- }
-
-
- /**
- * Clears object's internal properties
- *
- * @access public
- */
- function reset()
- {
- $this->_cookieManager->reset();
- $this->_responses = array();
- $this->_defaultHeaders = array();
- $this->_defaultRequestParams = array();
- }
-
-
- /**
- * Adds a Listener to the list of listeners that are notified of
- * the object's events
- *
- * Events sent by HTTP_Client objects:
- * - 'request': sent on HTTP request that is not a redirect
- * - 'httpSuccess': sent when we receive a successfull 2xx response
- * - 'httpRedirect': sent when we receive a redirection response
- * - 'httpError': sent on 4xx, 5xx response
- *
- * @param HTTP_Request_Listener Listener to attach
- * @param boolean Whether the listener should be attached
- * to the created HTTP_Request objects
- * @return boolean whether the listener was successfully attached
- * @access public
- */
- function attach(&$listener, $propagate = false)
- {
- if (!is_a($listener, 'HTTP_Request_Listener')) {
- return false;
- }
- $this->_listeners[$listener->getId()] =& $listener;
- $this->_propagate[$listener->getId()] = $propagate;
- return true;
- }
-
-
- /**
- * Removes a Listener from the list of listeners
- *
- * @param HTTP_Request_Listener Listener to detach
- * @return boolean Whether the listener was successfully detached
- * @access public
- */
- function detach(&$listener)
- {
- if (!is_a($listener, 'HTTP_Request_Listener') ||
- !isset($this->_listeners[$listener->getId()])) {
- return false;
- }
- unset($this->_listeners[$listener->getId()], $this->_propagate[$listener->getId()]);
- return true;
- }
-
-
- /**
- * Notifies all registered listeners of an event.
- *
- * @param string Event name
- * @param mixed Additional data
- * @access private
- */
- function _notify($event, $data = null)
- {
- foreach (array_keys($this->_listeners) as $id) {
- $this->_listeners[$id]->update($this, $event, $data);
- }
- }
-
-
- /**
- * Calculates the absolute URL of a redirect
- *
- * @param Net_Url Object containing the request URL
- * @param string Value of the 'Location' response header
- * @return string|null Absolute URL we are being redirected to, null in case of non-HTTP URL
- * @access private
- */
- function _redirectUrl($url, $location)
- {
- // If it begins with a scheme (as defined in RFC 2396) then it is absolute URI
- if (preg_match('/^([a-zA-Z][a-zA-Z0-9+.-]*):/', $location, $matches)) {
- // Bug #5759: we shouldn't try to follow non-HTTP redirects
- if ('http' == strtolower($matches[1]) || 'https' == strtolower($matches[1])) {
- return $location;
- } else {
- return null;
- }
- } else {
- if ('/' == $location{0}) {
- $url->path = Net_URL::resolvePath($location);
- } elseif('/' == substr($url->path, -1)) {
- $url->path = Net_URL::resolvePath($url->path . $location);
- } else {
- $dirname = (DIRECTORY_SEPARATOR == dirname($url->path)? '/': dirname($url->path));
- $url->path = Net_URL::resolvePath($dirname . '/' . $location);
- }
- $url->querystring = array();
- $url->anchor = '';
- return $url->getUrl();
- }
- }
-
-
- /**
- * Returns the cookie manager object (e.g. for storing it somewhere)
- *
- * @return HTTP_Client_CookieManager
- * @access public
- */
- function getCookieManager()
- {
- return $this->_cookieManager;
- }
-
-
- /**
- * Tries to extract a redirect URL from <<meta http-equiv=Refresh>> tag (request #5734)
- *
- * @param HTTP_Request A request object already containing the response
- * @return string|null Absolute URI we are being redirected to, null if no redirect / invalid redirect
- * @access private
- */
- function _getMetaRedirect(&$request)
- {
- // Non-HTML response or empty response body
- if ('text/html' != substr($request->getResponseHeader('content-type'), 0, 9) ||
- '' == ($body = $request->getResponseBody())) {
- return null;
- }
- // No <meta http-equiv=Refresh> tag
- if (!preg_match('!<meta\\s+([^>]*http-equiv\\s*=\\s*("Refresh"|\'Refresh\'|Refresh)[^>]*)>!is', $body, $matches)) {
- return null;
- }
- // Just a refresh, no redirect
- if (!preg_match('!content\\s*=\\s*("[^"]+"|\'[^\']+\'|\\S+)!is', $matches[1], $urlMatches)) {
- return null;
- }
- $parts = explode(';', ('\'' == substr($urlMatches[1], 0, 1) || '"' == substr($urlMatches[1], 0, 1))?
- substr($urlMatches[1], 1, -1): $urlMatches[1]);
- if (empty($parts[1]) || !preg_match('/url\\s*=\\s*(\\S+)/is', $parts[1], $urlMatches)) {
- return null;
- }
- // We do finally have an url... Now check that it's:
- // a) HTTP, b) not to the same page
- $previousUrl = $request->_url->getUrl();
- $redirectUrl = $this->_redirectUrl($request->_url, html_entity_decode($urlMatches[1]));
- return (null === $redirectUrl || $redirectUrl == $previousUrl)? null: $redirectUrl;
- }
-}
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * Class used to store cookies and pass them between HTTP requests.
- *
- * PHP versions 4 and 5
- *
- * LICENSE:
- *
- * Copyright (c) 2003-2007, Alexey Borzov <avb@php.net>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * @category HTTP
- * @package HTTP_Client
- * @author Alexey Borzov <avb@php.net>
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: CookieManager.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
- * @link http://pear.php.net/package/HTTP_Client
- */
-
-/**
- * Class used to store cookies and pass them between HTTP requests.
- *
- * @category HTTP
- * @package HTTP_Client
- * @author Alexey Borzov <avb@php.net>
- * @version Release: 1.1.1
- */
-class HTTP_Client_CookieManager
-{
- /**
- * An array containing cookie values
- * @var array
- * @access private
- */
- var $_cookies = array();
-
- /**
- * Whether session cookies should be serialized on object serialization
- * @var boolean
- * @access private
- */
- var $_serializeSessionCookies = false;
-
-
- /**
- * Constructor
- *
- * @param boolean Whether session cookies should be serialized
- * @access public
- * @see serializeSessionCookies()
- */
- function HTTP_Client_CookieManager($serializeSession = false)
- {
- $this->serializeSessionCookies($serializeSession);
- }
-
- /**
- * Sets whether session cookies should be serialized when serializing object
- *
- * @param boolean
- * @access public
- */
- function serializeSessionCookies($serialize)
- {
- $this->_serializeSessionCookies = (bool)$serialize;
- }
-
-
- /**
- * Adds cookies to the request
- *
- * @access public
- * @param HTTP_Request Request object
- */
- function passCookies(&$request)
- {
- if (!empty($this->_cookies)) {
- $url =& $request->_url;
- // We do not check cookie's "expires" field, as we do not store deleted
- // cookies in the array and our client does not work long enough for other
- // cookies to expire.
- $cookies = array();
- foreach ($this->_cookies as $cookie) {
- if ($this->_domainMatch($url->host, $cookie['domain']) && (0 === strpos($url->path, $cookie['path']))
- && (empty($cookie['secure']) || $url->protocol == 'https')) {
- $cookies[$cookie['name']][strlen($cookie['path'])] = $cookie['value'];
- }
- }
- // cookies with longer paths go first
- foreach ($cookies as $name => $values) {
- krsort($values);
- foreach ($values as $value) {
- $request->addCookie($name, $value);
- }
- }
- }
- return true;
- }
-
-
- /**
- * Explicitly adds cookie to the list
- *
- * @param array An array representing cookie, this function expects all of the array's
- * fields to be set
- * @access public
- */
- function addCookie($cookie)
- {
- $hash = $this->_makeHash($cookie['name'], $cookie['domain'], $cookie['path']);
- $this->_cookies[$hash] = $cookie;
- }
-
-
- /**
- * Updates cookie list from HTTP server response
- *
- * @access public
- * @param HTTP_Request Request object already containing the response
- */
- function updateCookies(&$request)
- {
- if (false !== ($cookies = $request->getResponseCookies())) {
- $url =& $request->_url;
- foreach ($cookies as $cookie) {
- // use the current domain by default
- if (!isset($cookie['domain'])) {
- $cookie['domain'] = $url->host;
- }
- // use the path to the current page by default
- if (empty($cookie['path'])) {
- $cookie['path'] = DIRECTORY_SEPARATOR == dirname($url->path)? '/': dirname($url->path);
- }
- // check if the domains match
- if ($this->_domainMatch($url->host, $cookie['domain'])) {
- $hash = $this->_makeHash($cookie['name'], $cookie['domain'], $cookie['path']);
- // if value is empty or the time is in the past the cookie is deleted, else added
- if (strlen($cookie['value'])
- && (!isset($cookie['expires']) || (strtotime($cookie['expires']) > time()))) {
- $this->_cookies[$hash] = $cookie;
- } elseif (isset($this->_cookies[$hash])) {
- unset($this->_cookies[$hash]);
- }
- }
- }
- }
- }
-
-
- /**
- * Generates a key for the $_cookies array.
- *
- * The cookies is uniquely identified by its name, domain and path.
- * Thus we cannot make f.e. an associative array with name as a key, we should
- * generate a key from these 3 values.
- *
- * @access private
- * @param string Cookie name
- * @param string Cookie domain
- * @param string Cookie path
- * @return string a key
- */
- function _makeHash($name, $domain, $path)
- {
- return md5($name . "\r\n" . $domain . "\r\n" . $path);
- }
-
-
- /**
- * Checks whether a cookie domain matches a request host.
- *
- * Cookie domain can begin with a dot, it also must contain at least
- * two dots.
- *
- * @access private
- * @param string request host
- * @param string cookie domain
- * @return bool match success
- */
- function _domainMatch($requestHost, $cookieDomain)
- {
- if ('.' != $cookieDomain{0}) {
- return $requestHost == $cookieDomain;
- } elseif (substr_count($cookieDomain, '.') < 2) {
- return false;
- } else {
- return substr('.'. $requestHost, - strlen($cookieDomain)) == $cookieDomain;
- }
- }
-
-
- /**
- * Clears the $_cookies array
- *
- * @access public
- */
- function reset()
- {
- $this->_cookies = array();
- }
-
-
- /**
- * Magic serialization function
- *
- * Removes session cookies if $_serializeSessionCookies is false (default)
- */
- function __sleep()
- {
- if (!$this->_serializeSessionCookies) {
- foreach ($this->_cookies as $hash => $cookie) {
- if (empty($cookie['expires'])) {
- unset($this->_cookies[$hash]);
- }
- }
- }
- return array('_cookies', '_serializeSessionCookies');
- }
-
-
- /**
- * Magic unserialization function, purges expired cookies
- */
- function __wakeup()
- {
- foreach ($this->_cookies as $hash => $cookie) {
- if (!empty($cookie['expires']) && strtotime($cookie['expires']) < time()) {
- unset($this->_cookies[$hash]);
- }
- }
- }
-}
-?>
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Bertrand Mansion <bmansion@mamasam.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Config.php,v 1.1.1.1 2008/04/28 15:20:46 jamie Exp $
-
-require_once('PEAR.php');
-require_once('Config/Container.php');
-
-$GLOBALS['CONFIG_TYPES'] =
- array(
- 'apache' => array('Config/Container/Apache.php', 'Config_Container_Apache'),
- 'genericconf' => array('Config/Container/GenericConf.php', 'Config_Container_GenericConf'),
- 'inifile' => array('Config/Container/IniFile.php', 'Config_Container_IniFile'),
- 'inicommented' => array('Config/Container/IniCommented.php', 'Config_Container_IniCommented'),
- 'phparray' => array('Config/Container/PHPArray.php', 'Config_Container_PHPArray'),
- 'phpconstants' => array('Config/Container/PHPConstants.php', 'Config_Container_PHPConstants'),
- 'xml' => array('Config/Container/XML.php', 'Config_Container_XML')
- );
-
-/**
-* Config
-*
-* This class allows for parsing and editing of configuration datasources.
-* Do not use this class only to read datasources because of the overhead
-* it creates to keep track of the configuration structure.
-*
-* @author Bertrand Mansion <bmansion@mamasam.com>
-* @package Config
-*/
-class Config {
-
- /**
- * Datasource
- * Can be a file url, a dsn, an object...
- * @var mixed
- */
- var $datasrc;
-
- /**
- * Type of datasource for config
- * Ex: IniCommented, Apache...
- * @var string
- */
- var $configType = '';
-
- /**
- * Options for parser
- * @var string
- */
- var $parserOptions = array();
-
- /**
- * Container object
- * @var object
- */
- var $container;
-
- /**
- * Constructor
- * Creates a root container
- *
- * @access public
- */
- function Config()
- {
- $this->container =& new Config_Container('section', 'root');
- } // end constructor
-
- /**
- * Returns true if container is registered
- *
- * @param string $configType Type of config
- * @access public
- * @return bool
- */
- function isConfigTypeRegistered($configType)
- {
- return isset($GLOBALS['CONFIG_TYPES'][strtolower($configType)]);
- } // end func isConfigTypeRegistered
-
- /**
- * Register a new container
- *
- * @param string $configType Type of config
- * @param array|false $configInfo Array of format:
- * array('path/to/Name.php',
- * 'Config_Container_Class_Name').
- *
- * If left false, defaults to:
- * array('Config/Container/$configType.php',
- * 'Config_Container_$configType')
- * @access public
- * @static
- * @author Greg Beaver <cellog@users.sourceforge.net>
- * @return true|PEAR_Error true on success
- */
- function registerConfigType($configType, $configInfo = false)
- {
- if (Config::isConfigTypeRegistered($configType)) {
- $info = $GLOBALS['CONFIG_TYPES'][strtolower($configType)];
- if ($info[0] == $configInfo[0] &&
- $info[1] == $configInfo[1]) {
- return true;
- } else {
- return PEAR::raiseError("Config::registerConfigType registration of existing $configType failed.", null, PEAR_ERROR_RETURN);
- }
- }
- if (!is_array($configInfo)) {
- // make the normal assumption, that this is a standard config container added in at runtime
- $configInfo = array('Config/Container/' . $configType . '.php',
- 'Config_Container_'. $configType);
- }
- $file_exists = @include_once($configInfo[0]);
- if ($file_exists) {
- if (!class_exists($configInfo[1])) {
- return PEAR::raiseError("Config::registerConfigType class '$configInfo[1]' not found in $configInfo[0]", null, PEAR_ERROR_RETURN);
- }
- } else {
- return PEAR::raiseError("Config::registerConfigType file $configInfo[0] not found", null, PEAR_ERROR_RETURN);
- }
- $GLOBALS['CONFIG_TYPES'][strtolower($configType)] = $configInfo;
- return true;
- } // end func registerConfigType
-
- /**
- * Returns the root container for this config object
- *
- * @access public
- * @return object reference to config's root container object
- */
- function &getRoot()
- {
- return $this->container;
- } // end func getRoot
-
- /**
- * Sets the content of the root Config_container object.
- *
- * This method will replace the current child of the root
- * Config_Container object by the given object.
- *
- * @param object $rootContainer container to be used as the first child to root
- * @access public
- * @return mixed true on success or PEAR_Error
- */
- function setRoot(&$rootContainer)
- {
- if (is_object($rootContainer) && strtolower(get_class($rootContainer)) === 'config_container') {
- if ($rootContainer->getName() === 'root' && $rootContainer->getType() === 'section') {
- $this->container =& $rootContainer;
- } else {
- $this->container =& new Config_Container('section', 'root');
- $this->container->addItem($rootContainer);
- }
- return true;
- } else {
- return PEAR::raiseError("Config::setRoot only accepts object of Config_Container type.", null, PEAR_ERROR_RETURN);
- }
- } // end func setRoot
-
- /**
- * Parses the datasource contents
- *
- * This method will parse the datasource given and fill the root
- * Config_Container object with other Config_Container objects.
- *
- * @param mixed $datasrc Datasource to parse
- * @param string $configType Type of configuration
- * @param array $options Options for the parser
- * @access public
- * @return mixed PEAR_Error on error or Config_Container object
- */
- function &parseConfig($datasrc, $configType, $options = array())
- {
- $configType = strtolower($configType);
- if (!$this->isConfigTypeRegistered($configType)) {
- return PEAR::raiseError("Configuration type '$configType' is not registered in Config::parseConfig.", null, PEAR_ERROR_RETURN);
- }
- $includeFile = $GLOBALS['CONFIG_TYPES'][$configType][0];
- $className = $GLOBALS['CONFIG_TYPES'][$configType][1];
- include_once($includeFile);
-
- $parser = new $className($options);
- $error = $parser->parseDatasrc($datasrc, $this);
- if ($error !== true) {
- return $error;
- }
- $this->parserOptions = $parser->options;
- $this->datasrc = $datasrc;
- $this->configType = $configType;
- return $this->container;
- } // end func &parseConfig
-
- /**
- * Writes the container contents to the datasource.
- *
- * @param mixed $datasrc Datasource to write to
- * @param string $configType Type of configuration
- * @param array $options Options for config container
- * @access public
- * @return mixed PEAR_Error on error or true if ok
- */
- function writeConfig($datasrc = null, $configType = null, $options = array())
- {
- if (empty($datasrc)) {
- $datasrc = $this->datasrc;
- }
- if (empty($configType)) {
- $configType = $this->configType;
- }
- if (empty($options)) {
- $options = $this->parserOptions;
- }
- return $this->container->writeDatasrc($datasrc, $configType, $options);
- } // end func writeConfig
-} // end class Config
-?>
+++ /dev/null
-<?php
-// +---------------------------------------------------------------------+
-// | PHP Version 4 |
-// +---------------------------------------------------------------------+
-// | Copyright (c) 1997, 1998, 1999, 2000, 2001 The PHP Group |
-// +---------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +---------------------------------------------------------------------+
-// | Author: Bertrand Mansion <bmansion@mamasam.com> |
-// +---------------------------------------------------------------------+
-//
-// $Id: Container.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
-
-require_once 'Config.php';
-
-/**
-* Interface for Config containers
-*
-* @author Bertrand Mansion <bmansion@mamasam.com>
-* @package Config
-*/
-class Config_Container {
-
- /**
- * Container object type
- * Ex: section, directive, comment, blank
- * @var string
- */
- var $type;
-
- /**
- * Container object name
- * @var string
- */
- var $name = '';
-
- /**
- * Container object content
- * @var string
- */
- var $content = '';
-
- /**
- * Container object children
- * @var array
- */
- var $children = array();
-
- /**
- * Reference to container object's parent
- * @var object
- */
- var $parent;
-
- /**
- * Array of attributes for this item
- * @var array
- */
- var $attributes;
-
- /**
- * Unique id to differenciate nodes
- *
- * This is used to compare nodes
- * Will not be needed anymore when this class will use ZendEngine 2
- *
- * @var int
- */
- var $_id;
-
- /**
- * Constructor
- *
- * @param string $type Type of container object
- * @param string $name Name of container object
- * @param string $content Content of container object
- * @param array $attributes Array of attributes for container object
- */
- function Config_Container($type = 'section', $name = '', $content = '', $attributes = null)
- {
- $this->type = $type;
- $this->name = $name;
- $this->content = $content;
- $this->attributes = $attributes;
- $this->parent = null;
- if (version_compare(PHP_VERSION, '5.0.0', 'gt')) {
- $this->_id = uniqid($name.$type, true);
- } else {
- $this->_id = uniqid(substr($name.$type, 0, 114), true);
- }
- } // end constructor
-
- /**
- * Create a child for this item.
- * @param string $type type of item: directive, section, comment, blank...
- * @param mixed $item item name
- * @param string $content item content
- * @param array $attributes item attributes
- * @param string $where choose a position 'bottom', 'top', 'after', 'before'
- * @param object $target needed if you choose 'before' or 'after' for where
- * @return object reference to new item or Pear_Error
- */
- function &createItem($type, $name, $content, $attributes = null, $where = 'bottom', $target = null)
- {
- $item =& new Config_Container($type, $name, $content, $attributes);
- $result =& $this->addItem($item, $where, $target);
- return $result;
- } // end func &createItem
-
- /**
- * Adds an item to this item.
- * @param object $item a container object
- * @param string $where choose a position 'bottom', 'top', 'after', 'before'
- * @param object $target needed if you choose 'before' or 'after' in $where
- * @return mixed reference to added container on success, Pear_Error on error
- */
- function &addItem(&$item, $where = 'bottom', $target = null)
- {
- if ($this->type != 'section') {
- return PEAR::raiseError('Config_Container::addItem must be called on a section type object.', null, PEAR_ERROR_RETURN);
- }
- if (is_null($target)) {
- $target =& $this;
- }
- if (strtolower(get_class($target)) != 'config_container') {
- return PEAR::raiseError('Target must be a Config_Container object in Config_Container::addItem.', null, PEAR_ERROR_RETURN);
- }
-
- switch ($where) {
- case 'before':
- $index = $target->getItemIndex();
- break;
- case 'after':
- $index = $target->getItemIndex()+1;
- break;
- case 'top':
- $index = 0;
- break;
- case 'bottom':
- $index = -1;
- break;
- default:
- return PEAR::raiseError('Use only top, bottom, before or after in Config_Container::addItem.', null, PEAR_ERROR_RETURN);
- }
- if (isset($index) && $index >= 0) {
- array_splice($this->children, $index, 0, 'tmp');
- } else {
- $index = count($this->children);
- }
- $this->children[$index] =& $item;
- $this->children[$index]->parent =& $this;
-
- return $item;
- } // end func addItem
-
- /**
- * Adds a comment to this item.
- * This is a helper method that calls createItem
- *
- * @param string $content Object content
- * @param string $where Position : 'top', 'bottom', 'before', 'after'
- * @param object $target Needed when $where is 'before' or 'after'
- * @return object reference to new item or Pear_Error
- */
- function &createComment($content = '', $where = 'bottom', $target = null)
- {
- return $this->createItem('comment', null, $content, null, $where, $target);
- } // end func &createComment
-
- /**
- * Adds a blank line to this item.
- * This is a helper method that calls createItem
- *
- * @return object reference to new item or Pear_Error
- */
- function &createBlank($where = 'bottom', $target = null)
- {
- return $this->createItem('blank', null, null, null, $where, $target);
- } // end func &createBlank
-
- /**
- * Adds a directive to this item.
- * This is a helper method that calls createItem
- *
- * @param string $name Name of new directive
- * @param string $content Content of new directive
- * @param mixed $attributes Directive attributes
- * @param string $where Position : 'top', 'bottom', 'before', 'after'
- * @param object $target Needed when $where is 'before' or 'after'
- * @return object reference to new item or Pear_Error
- */
- function &createDirective($name, $content, $attributes = null, $where = 'bottom', $target = null)
- {
- return $this->createItem('directive', $name, $content, $attributes, $where, $target);
- } // end func &createDirective
-
- /**
- * Adds a section to this item.
- *
- * This is a helper method that calls createItem
- * If the section already exists, it won't create a new one.
- * It will return reference to existing item.
- *
- * @param string $name Name of new section
- * @param array $attributes Section attributes
- * @param string $where Position : 'top', 'bottom', 'before', 'after'
- * @param object $target Needed when $where is 'before' or 'after'
- * @return object reference to new item or Pear_Error
- */
- function &createSection($name, $attributes = null, $where = 'bottom', $target = null)
- {
- return $this->createItem('section', $name, null, $attributes, $where, $target);
- } // end func &createSection
-
- /**
- * Tries to find the specified item(s) and returns the objects.
- *
- * Examples:
- * $directives =& $obj->getItem('directive');
- * $directive_bar_4 =& $obj->getItem('directive', 'bar', null, 4);
- * $section_foo =& $obj->getItem('section', 'foo');
- *
- * This method can only be called on an object of type 'section'.
- * Note that root is a section.
- * This method is not recursive and tries to keep the current structure.
- * For a deeper search, use searchPath()
- *
- * @param string $type Type of item: directive, section, comment, blank...
- * @param mixed $name Item name
- * @param mixed $content Find item with this content
- * @param array $attributes Find item with attribute set to the given value
- * @param int $index Index of the item in the returned object list. If it is not set, will try to return the last item with this name.
- * @return mixed reference to item found or false when not found
- * @see &searchPath()
- */
- function &getItem($type = null, $name = null, $content = null, $attributes = null, $index = -1)
- {
- if ($this->type != 'section') {
- return PEAR::raiseError('Config_Container::getItem must be called on a section type object.', null, PEAR_ERROR_RETURN);
- }
- if (!is_null($type)) {
- $testFields[] = 'type';
- }
- if (!is_null($name)) {
- $testFields[] = 'name';
- }
- if (!is_null($content)) {
- $testFields[] = 'content';
- }
- if (!is_null($attributes) && is_array($attributes)) {
- $testFields[] = 'attributes';
- }
-
- $itemsArr = array();
- $fieldsToMatch = count($testFields);
- for ($i = 0, $count = count($this->children); $i < $count; $i++) {
- $match = 0;
- reset($testFields);
- foreach ($testFields as $field) {
- if ($field != 'attributes') {
- if ($this->children[$i]->$field == ${$field}) {
- $match++;
- }
- } else {
- // Look for attributes in array
- $attrToMatch = count($attributes);
- $attrMatch = 0;
- foreach ($attributes as $key => $value) {
- if (isset($this->children[$i]->attributes[$key]) &&
- $this->children[$i]->attributes[$key] == $value) {
- $attrMatch++;
- }
- }
- if ($attrMatch == $attrToMatch) {
- $match++;
- }
- }
- }
- if ($match == $fieldsToMatch) {
- $itemsArr[] =& $this->children[$i];
- }
- }
- if ($index >= 0) {
- if (isset($itemsArr[$index])) {
- return $itemsArr[$index];
- } else {
- $return = false;
- return $return;
- }
- } else {
- if ($count = count($itemsArr)) {
- return $itemsArr[$count-1];
- } else {
- $return = false;
- return $return;
- }
- }
- } // end func &getItem
-
- /**
- * Finds a node using XPATH like format.
- *
- * The search format is an array:
- * array(item1, item2, item3, ...)
- *
- * Each item can be defined as the following:
- * item = 'string' : will match the container named 'string'
- * item = array('string', array('name' => 'xyz'))
- * will match the container name 'string' whose attribute name is equal to "xyz"
- * For example : <string name="xyz">
- *
- * @param mixed Search path and attributes
- *
- * @return mixed Config_Container object, array of Config_Container objects or false on failure.
- * @access public
- */
- function &searchPath($args)
- {
- if ($this->type != 'section') {
- return PEAR::raiseError('Config_Container::searchPath must be called on a section type object.', null, PEAR_ERROR_RETURN);
- }
-
- $arg = array_shift($args);
-
- if (is_array($arg)) {
- $name = $arg[0];
- $attributes = $arg[1];
- } else {
- $name = $arg;
- $attributes = null;
- }
- // find all the matches for first..
- $match =& $this->getItem(null, $name, null, $attributes);
-
- if (!$match) {
- $return = false;
- return $return;
- }
- if (!empty($args)) {
- return $match->searchPath($args);
- }
- return $match;
- } // end func &searchPath
-
- /**
- * Return a child directive's content.
- *
- * This method can use two different search approach, depending on
- * the parameter it is given. If the parameter is an array, it will use
- * the {@link Config_Container::searchPath()} method. If it is a string,
- * it will use the {@link Config_Container::getItem()} method.
- *
- * Example:
- * <code>
- * require_once 'Config.php';
- * $ini = new Config();
- * $conf =& $ini->parseConfig('/path/to/config.ini', 'inicommented');
- *
- * // Will return the value found at :
- * // [Database]
- * // host=localhost
- * echo $conf->directiveContent(array('Database', 'host')));
- *
- * // Will return the value found at :
- * // date="dec-2004"
- * echo $conf->directiveContent('date');
- *
- * </code>
- *
- * @param mixed Search path and attributes or a directive name
- * @param int Index of the item in the returned directive list.
- * Eventually used if args is a string.
- *
- * @return mixed Content of directive or false if not found.
- * @access public
- */
- function directiveContent($args, $index = -1)
- {
- if (is_array($args)) {
- $item =& $this->searchPath($args);
- } else {
- $item =& $this->getItem('directive', $args, null, null, $index);
- }
- if ($item) {
- return $item->getContent();
- }
- return false;
- } // end func getDirectiveContent
-
- /**
- * Returns how many children this container has
- *
- * @param string $type type of children counted
- * @param string $name name of children counted
- * @return int number of children found
- */
- function countChildren($type = null, $name = null)
- {
- if (is_null($type) && is_null($name)) {
- return count($this->children);
- }
- $count = 0;
- if (isset($name) && isset($type)) {
- for ($i = 0, $children = count($this->children); $i < $children; $i++) {
- if ($this->children[$i]->name === $name &&
- $this->children[$i]->type == $type) {
- $count++;
- }
- }
- return $count;
- }
- if (isset($type)) {
- for ($i = 0, $children = count($this->children); $i < $children; $i++) {
- if ($this->children[$i]->type == $type) {
- $count++;
- }
- }
- return $count;
- }
- if (isset($name)) {
- // Some directives can have the same name
- for ($i = 0, $children = count($this->children); $i < $children; $i++) {
- if ($this->children[$i]->name === $name) {
- $count++;
- }
- }
- return $count;
- }
- } // end func &countChildren
-
- /**
- * Deletes an item (section, directive, comment...) from the current object
- * TODO: recursive remove in sub-sections
- * @return mixed true if object was removed, false if not, or PEAR_Error if root
- */
- function removeItem()
- {
- if ($this->isRoot()) {
- return PEAR::raiseError('Cannot remove root item in Config_Container::removeItem.', null, PEAR_ERROR_RETURN);
- }
- $index = $this->getItemIndex();
- if (!is_null($index)) {
- array_splice($this->parent->children, $index, 1);
- return true;
- }
- return false;
- } // end func removeItem
-
- /**
- * Returns the item index in its parent children array.
- * @return int returns int or null if root object
- */
- function getItemIndex()
- {
- if (is_object($this->parent)) {
- // This will be optimized with Zend Engine 2
- $pchildren =& $this->parent->children;
- for ($i = 0, $count = count($pchildren); $i < $count; $i++) {
- if ($pchildren[$i]->_id == $this->_id) {
- return $i;
- }
- }
- }
- return;
- } // end func getItemIndex
-
- /**
- * Returns the item rank in its parent children array
- * according to other items with same type and name.
- * @param bool count items differently by type
- * @return int returns int or null if root object
- */
- function getItemPosition($byType = true)
- {
- if (is_object($this->parent)) {
- $pchildren =& $this->parent->children;
- for ($i = 0, $count = count($pchildren); $i < $count; $i++) {
- if ($pchildren[$i]->name == $this->name) {
- if ($byType == true) {
- if ($pchildren[$i]->type == $this->type) {
- $obj[] =& $pchildren[$i];
- }
- } else {
- $obj[] =& $pchildren[$i];
- }
- }
- }
- for ($i = 0, $count = count($obj); $i < $count; $i++) {
- if ($obj[$i]->_id == $this->_id) {
- return $i;
- }
- }
- }
- return;
- } // end func getItemPosition
-
- /**
- * Returns the item parent object.
- * @return object returns reference to parent object or null if root object
- */
- function &getParent()
- {
- return $this->parent;
- } // end func &getParent
-
- /**
- * Returns the item parent object.
- * @return mixed returns reference to child object or false if child does not exist
- */
- function &getChild($index = 0)
- {
- if (!empty($this->children[$index])) {
- return $this->children[$index];
- } else {
- return false;
- }
- } // end func &getChild
-
- /**
- * Set this item's name.
- * @return void
- */
- function setName($name)
- {
- $this->name = $name;
- } // end func setName
-
- /**
- * Get this item's name.
- * @return string item's name
- */
- function getName()
- {
- return $this->name;
- } // end func getName
-
- /**
- * Set this item's content.
- * @return void
- */
- function setContent($content)
- {
- $this->content = $content;
- } // end func setContent
-
- /**
- * Get this item's content.
- * @return string item's content
- */
- function getContent()
- {
- return $this->content;
- } // end func getContent
-
- /**
- * Set this item's type.
- * @return void
- */
- function setType($type)
- {
- $this->type = $type;
- } // end func setType
-
- /**
- * Get this item's type.
- * @return string item's type
- */
- function getType()
- {
- return $this->type;
- } // end func getType
-
- /**
- * Set this item's attributes.
- * @param array $attributes Array of attributes
- * @return void
- */
- function setAttributes($attributes)
- {
- $this->attributes = $attributes;
- } // end func setAttributes
-
- /**
- * Set this item's attributes.
- * @param array $attributes Array of attributes
- * @return void
- */
- function updateAttributes($attributes)
- {
- if (is_array($attributes)) {
- foreach ($attributes as $key => $value) {
- $this->attributes[$key] = $value;
- }
- }
- } // end func updateAttributes
-
- /**
- * Get this item's attributes.
- * @return array item's attributes
- */
- function getAttributes()
- {
- return $this->attributes;
- } // end func getAttributes
-
- /**
- * Get one attribute value of this item
- * @param string $attribute Attribute key
- * @return mixed item's attribute value
- */
- function getAttribute($attribute)
- {
- if (isset($this->attributes[$attribute])) {
- return $this->attributes[$attribute];
- }
- return null;
- } // end func getAttribute
-
- /**
- * Set a children directive content.
- * This is an helper method calling getItem and addItem or setContent for you.
- * If the directive does not exist, it will be created at the bottom.
- *
- * @param string $name Name of the directive to look for
- * @param mixed $content New content
- * @param int $index Index of the directive to set,
- * in case there are more than one directive
- * with the same name
- * @return object newly set directive
- */
- function &setDirective($name, $content, $index = -1)
- {
- $item =& $this->getItem('directive', $name, null, null, $index);
- if ($item === false || PEAR::isError($item)) {
- // Directive does not exist, will create one
- unset($item);
- return $this->createDirective($name, $content, null);
- } else {
- // Change existing directive value
- $item->setContent($content);
- return $item;
- }
- } // end func setDirective
-
- /**
- * Is this item root, in a config container object
- * @return bool true if item is root
- */
- function isRoot()
- {
- if (is_null($this->parent)) {
- return true;
- }
- return false;
- } // end func isRoot
-
- /**
- * Call the toString methods in the container plugin
- * @param string $configType Type of configuration used to generate the string
- * @param array $options Specify special options used by the parser
- * @return mixed true on success or PEAR_ERROR
- */
- function toString($configType, $options = array())
- {
- $configType = strtolower($configType);
- if (!isset($GLOBALS['CONFIG_TYPES'][$configType])) {
- return PEAR::raiseError("Configuration type '$configType' is not registered in Config_Container::toString.", null, PEAR_ERROR_RETURN);
- }
- $includeFile = $GLOBALS['CONFIG_TYPES'][$configType][0];
- $className = $GLOBALS['CONFIG_TYPES'][$configType][1];
- include_once($includeFile);
- $renderer = new $className($options);
- return $renderer->toString($this);
- } // end func toString
-
- /**
- * Returns a key/value pair array of the container and its children.
- *
- * Format : section[directive][index] = value
- * If the container has attributes, it will use '@' and '#'
- * index is here because multiple directives can have the same name.
- *
- * @param bool $useAttr Whether to return the attributes too
- * @return array
- */
- function toArray($useAttr = true)
- {
- $array[$this->name] = array();
- switch ($this->type) {
- case 'directive':
- if ($useAttr && count($this->attributes) > 0) {
- $array[$this->name]['#'] = $this->content;
- $array[$this->name]['@'] = $this->attributes;
- } else {
- $array[$this->name] = $this->content;
- }
- break;
- case 'section':
- if ($useAttr && count($this->attributes) > 0) {
- $array[$this->name]['@'] = $this->attributes;
- }
- if ($count = count($this->children)) {
- for ($i = 0; $i < $count; $i++) {
- $newArr = $this->children[$i]->toArray($useAttr);
- if (!is_null($newArr)) {
- foreach ($newArr as $key => $value) {
- if (isset($array[$this->name][$key])) {
- // duplicate name/type
- if (!is_array($array[$this->name][$key]) ||
- !isset($array[$this->name][$key][0])) {
- $old = $array[$this->name][$key];
- unset($array[$this->name][$key]);
- $array[$this->name][$key][0] = $old;
- }
- $array[$this->name][$key][] = $value;
- } else {
- $array[$this->name][$key] = $value;
- }
- }
- }
- }
- }
- break;
- default:
- return null;
- }
- return $array;
- } // end func toArray
-
- /**
- * Writes the configuration to a file
- *
- * @param mixed $datasrc Info on datasource such as path to the configuraton file or dsn...
- * @param string $configType Type of configuration
- * @param array $options Options for writer
- * @access public
- * @return mixed true on success or PEAR_ERROR
- */
- function writeDatasrc($datasrc, $configType, $options = array())
- {
- $configType = strtolower($configType);
- if (!isset($GLOBALS['CONFIG_TYPES'][$configType])) {
- return PEAR::raiseError("Configuration type '$configType' is not registered in Config_Container::writeDatasrc.", null, PEAR_ERROR_RETURN);
- }
- $includeFile = $GLOBALS['CONFIG_TYPES'][$configType][0];
- $className = $GLOBALS['CONFIG_TYPES'][$configType][1];
- include_once($includeFile);
-
- $writeMethodName = (version_compare(phpversion(), '5', '<')) ? 'writedatasrc' : 'writeDatasrc';
- if (in_array($writeMethodName, get_class_methods($className))) {
- $writer = new $className($options);
- return $writer->writeDatasrc($datasrc, $this);
- }
-
- // Default behaviour
- $fp = @fopen($datasrc, 'w');
- if ($fp) {
- $string = $this->toString($configType, $options);
- $len = strlen($string);
- @flock($fp, LOCK_EX);
- @fwrite($fp, $string, $len);
- @flock($fp, LOCK_UN);
- @fclose($fp);
- return true;
- } else {
- return PEAR::raiseError('Cannot open datasource for writing.', 1, PEAR_ERROR_RETURN);
- }
- } // end func writeDatasrc
-} // end class Config_Container
-?>
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Bertrand Mansion <bmansion@mamasam.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Apache.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
-
-/**
-* Simple config parser for apache httpd.conf files
-* A more complex version could handle directives as
-* associative arrays.
-*
-* @author Bertrand Mansion <bmansion@mamasam.com>
-* @package Config
-*/
-class Config_Container_Apache {
-
- /**
- * This class options
- * Not used at the moment
- *
- * @var array
- */
- var $options = array();
-
- /**
- * Constructor
- *
- * @access public
- * @param string $options (optional)Options to be used by renderer
- */
- function Config_Container_Apache($options = array())
- {
- $this->options = $options;
- } // end constructor
-
- /**
- * Parses the data of the given configuration file
- *
- * @access public
- * @param string $datasrc path to the configuration file
- * @param object $obj reference to a config object
- * @return mixed returns a PEAR_ERROR, if error occurs or true if ok
- */
- function &parseDatasrc($datasrc, &$obj)
- {
- $return = true;
- if (!is_readable($datasrc)) {
- return PEAR::raiseError("Datasource file cannot be read.", null, PEAR_ERROR_RETURN);
- }
- $lines = file($datasrc);
- $n = 0;
- $lastline = '';
- $sections[0] =& $obj->container;
- foreach ($lines as $line) {
- $n++;
- if (!preg_match('/^\s*#/', $line) &&
- preg_match('/^\s*(.*)\s+\\\$/', $line, $match)) {
- // directive on more than one line
- $lastline .= $match[1].' ';
- continue;
- }
- if ($lastline != '') {
- $line = $lastline.trim($line);
- $lastline = '';
- }
- if (preg_match('/^\s*#+\s*(.*?)\s*$/', $line, $match)) {
- // a comment
- $currentSection =& $sections[count($sections)-1];
- $currentSection->createComment($match[1]);
- } elseif (trim($line) == '') {
- // a blank line
- $currentSection =& $sections[count($sections)-1];
- $currentSection->createBlank();
- } elseif (preg_match('/^\s*(\w+)(?:\s+(.*?)|)\s*$/', $line, $match)) {
- // a directive
- $currentSection =& $sections[count($sections)-1];
- $currentSection->createDirective($match[1], $match[2]);
- } elseif (preg_match('/^\s*<(\w+)(?:\s+([^>]*)|\s*)>\s*$/', $line, $match)) {
- // a section opening
- if (!isset($match[2]))
- $match[2] = '';
- $currentSection =& $sections[count($sections)-1];
- $attributes = explode(' ', $match[2]);
- $sections[] =& $currentSection->createSection($match[1], $attributes);
- } elseif (preg_match('/^\s*<\/(\w+)\s*>\s*$/', $line, $match)) {
- // a section closing
- $currentSection =& $sections[count($sections)-1];
- if ($currentSection->name != $match[1]) {
- return PEAR::raiseError("Section not closed in '$datasrc' at line $n.", null, PEAR_ERROR_RETURN);
- }
- array_pop($sections);
- } else {
- return PEAR::raiseError("Syntax error in '$datasrc' at line $n.", null, PEAR_ERROR_RETURN);
- }
- }
- return $return;
- } // end func parseDatasrc
-
- /**
- * Returns a formatted string of the object
- * @param object $obj Container object to be output as string
- * @access public
- * @return string
- */
- function toString(&$obj)
- {
- static $deep = -1;
- $ident = '';
- if (!$obj->isRoot()) {
- // no indent for root
- $deep++;
- $ident = str_repeat(' ', $deep);
- }
- if (!isset($string)) {
- $string = '';
- }
- switch ($obj->type) {
- case 'blank':
- $string = "\n";
- break;
- case 'comment':
- $string = $ident.'# '.$obj->content."\n";
- break;
- case 'directive':
- $string = $ident.$obj->name.' '.$obj->content."\n";
- break;
- case 'section':
- if (!$obj->isRoot()) {
- $string = $ident.'<'.$obj->name;
- if (is_array($obj->attributes) && count($obj->attributes) > 0) {
- foreach ($obj->attributes as $attr => $val) {
- $string .= ' '.$val;
- }
- }
- $string .= ">\n";
- }
- if (count($obj->children) > 0) {
- for ($i = 0; $i < count($obj->children); $i++) {
- $string .= $this->toString($obj->getChild($i));
- }
- }
- if (!$obj->isRoot()) {
- // object is not root
- $string .= $ident.'</'.$obj->name.">\n";
- }
- break;
- default:
- $string = '';
- }
- if (!$obj->isRoot()) {
- $deep--;
- }
- return $string;
- } // end func toString
-} // end class Config_Container_Apache
-?>
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Bertrand Mansion <bmansion@mamasam.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: GenericConf.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
-
-/**
-* Config parser for generic .conf files like
-* htdig.conf...
-*
-* @author Bertrand Mansion <bmansion@mamasam.com>
-* @package Config
-*/
-class Config_Container_GenericConf {
-
- /**
- * This class options:
- * Ex: $options['comment'] = '#';
- * Ex: $options['equals'] = ':';
- * Ex: $options['newline'] = '\\';
- *
- * @var array
- */
- var $options = array();
-
- /**
- * Constructor
- *
- * @access public
- * @param string $options (optional)Options to be used by renderer
- */
- function Config_Container_GenericConf($options = array())
- {
- if (empty($options['comment'])) {
- $options['comment'] = '#';
- }
- if (empty($options['equals'])) {
- $options['equals'] = ':';
- }
- if (empty($options['newline'])) {
- $options['newline'] = '\\';
- }
- $this->options = $options;
- } // end constructor
-
- /**
- * Parses the data of the given configuration file
- *
- * @access public
- * @param string $datasrc path to the configuration file
- * @param object $obj reference to a config object
- * @return mixed returns a PEAR_ERROR, if error occurs or true if ok
- */
- function &parseDatasrc($datasrc, &$obj)
- {
- $return = true;
- if (!is_readable($datasrc)) {
- return PEAR::raiseError("Datasource file cannot be read.", null, PEAR_ERROR_RETURN);
- }
-
- $lines = file($datasrc);
- $n = 0;
- $lastline = '';
- $currentSection =& $obj->container;
- foreach ($lines as $line) {
- $n++;
- if (!preg_match('/^\s*'.$this->options['comment'].'/', $line) &&
- preg_match('/^\s*(.*)\s+'.$this->options['newline'].'\s*$/', $line, $match)) {
- // directive on more than one line
- $lastline .= $match[1].' ';
- continue;
- }
- if ($lastline != '') {
- $line = $lastline.trim($line);
- $lastline = '';
- }
- if (preg_match('/^\s*'.$this->options['comment'].'+\s*(.*?)\s*$/', $line, $match)) {
- // a comment
- $currentSection->createComment($match[1]);
- } elseif (preg_match('/^\s*$/', $line)) {
- // a blank line
- $currentSection->createBlank();
- } elseif (preg_match('/^\s*(\w+)'.$this->options['equals'].'\s*((.*?)|)\s*$/', $line, $match)) {
- // a directive
- $currentSection->createDirective($match[1], $match[2]);
- } else {
- return PEAR::raiseError("Syntax error in '$datasrc' at line $n.", null, PEAR_ERROR_RETURN);
- }
- }
- return $return;
- } // end func parseDatasrc
-
- /**
- * Returns a formatted string of the object
- * @param object $obj Container object to be output as string
- * @access public
- * @return string
- */
- function toString(&$obj)
- {
- $string = '';
- switch ($obj->type) {
- case 'blank':
- $string = "\n";
- break;
- case 'comment':
- $string = $this->options['comment'].$obj->content."\n";
- break;
- case 'directive':
- $string = $obj->name.$this->options['equals'].$obj->content."\n";
- break;
- case 'section':
- // How to deal with sections ???
- if (count($obj->children) > 0) {
- for ($i = 0; $i < count($obj->children); $i++) {
- $string .= $this->toString($obj->getChild($i));
- }
- }
- break;
- default:
- $string = '';
- }
- return $string;
- } // end func toString
-} // end class Config_Container_GenericConf
-?>
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Bertrand Mansion <bmansion@mamasam.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: IniCommented.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
-
-/**
-* Config parser for PHP .ini files with comments
-*
-* @author Bertrand Mansion <bmansion@mamasam.com>
-* @package Config
-*/
-class Config_Container_IniCommented {
-
- /**
- * This class options
- * Not used at the moment
- *
- * @var array
- */
- var $options = array();
-
- /**
- * Constructor
- *
- * @access public
- * @param string $options (optional)Options to be used by renderer
- */
- function Config_Container_IniCommented($options = array())
- {
- $this->options = $options;
- } // end constructor
-
- /**
- * Parses the data of the given configuration file
- *
- * @access public
- * @param string $datasrc path to the configuration file
- * @param object $obj reference to a config object
- * @return mixed returns a PEAR_ERROR, if error occurs or true if ok
- */
- function &parseDatasrc($datasrc, &$obj)
- {
- $return = true;
- if (!file_exists($datasrc)) {
- return PEAR::raiseError("Datasource file does not exist.", null, PEAR_ERROR_RETURN);
- }
- $lines = file($datasrc);
- $n = 0;
- $lastline = '';
- $currentSection =& $obj->container;
- foreach ($lines as $line) {
- $n++;
- if (preg_match('/^\s*;(.*?)\s*$/', $line, $match)) {
- // a comment
- $currentSection->createComment($match[1]);
- } elseif (preg_match('/^\s*$/', $line)) {
- // a blank line
- $currentSection->createBlank();
- } elseif (preg_match('/^\s*([a-zA-Z0-9_\-\.\s:]*)\s*=\s*(.*)\s*$/', $line, $match)) {
- // a directive
-
- $values = $this->_quoteAndCommaParser($match[2]);
- if (PEAR::isError($values)) {
- return PEAR::raiseError($values);
- }
-
- if (count($values)) {
- foreach($values as $value) {
- if ($value[0] == 'normal') {
- $currentSection->createDirective(trim($match[1]), $value[1]);
- }
- if ($value[0] == 'comment') {
- $currentSection->createComment(substr($value[1], 1));
- }
- }
- }
- } elseif (preg_match('/^\s*\[\s*(.*)\s*\]\s*$/', $line, $match)) {
- // a section
- $currentSection =& $obj->container->createSection($match[1]);
- } else {
- return PEAR::raiseError("Syntax error in '$datasrc' at line $n.", null, PEAR_ERROR_RETURN);
- }
- }
- return $return;
- } // end func parseDatasrc
-
- /**
- * Quote and Comma Parser for INI files
- *
- * This function allows complex values such as:
- *
- * <samp>
- * mydirective = "Item, number \"1\"", Item 2 ; "This" is really, really tricky
- * </samp>
- * @param string $text value of a directive to parse for quotes/multiple values
- * @return array The array returned contains multiple values, if any (unquoted literals
- * to be used as is), and a comment, if any. The format of the array is:
- *
- * <pre>
- * array(array('normal', 'first value'),
- * array('normal', 'next value'),...
- * array('comment', '; comment with leading ;'))
- * </pre>
- * @author Greg Beaver <cellog@users.sourceforge.net>
- * @access private
- */
- function _quoteAndCommaParser($text)
- {
- $text = trim($text);
- if ($text == '') {
- $emptyNode = array();
- $emptyNode[0][0] = 'normal';
- $emptyNode[0][1] = '';
- return $emptyNode;
- }
-
- // tokens
- $tokens['normal'] = array('"', ';', ',');
- $tokens['quote'] = array('"', '\\');
- $tokens['escape'] = false; // cycle
- $tokens['after_quote'] = array(',', ';');
-
- // events
- $events['normal'] = array('"' => 'quote', ';' => 'comment', ',' => 'normal');
- $events['quote'] = array('"' => 'after_quote', '\\' => 'escape');
- $events['after_quote'] = array(',' => 'normal', ';' => 'comment');
-
- // state stack
- $stack = array();
-
- // return information
- $return = array();
- $returnpos = 0;
- $returntype = 'normal';
-
- // initialize
- array_push($stack, 'normal');
- $pos = 0; // position in $text
-
- do {
- $char = $text{$pos};
- $state = $this->_getQACEvent($stack);
-
- if ($tokens[$state]) {
- if (in_array($char, $tokens[$state])) {
- switch($events[$state][$char]) {
- case 'quote' :
- if ($state == 'normal' &&
- isset($return[$returnpos]) &&
- !empty($return[$returnpos][1])) {
- return PEAR::raiseError("invalid ini syntax, quotes cannot follow text '$text'",
- null, PEAR_ERROR_RETURN);
- }
- if ($returnpos >= 0 && isset($return[$returnpos])) {
- // trim any unnecessary whitespace in earlier entries
- $return[$returnpos][1] = trim($return[$returnpos][1]);
- } else {
- $returnpos++;
- }
- $return[$returnpos] = array('normal', '');
- array_push($stack, 'quote');
- continue 2;
- break;
- case 'comment' :
- // comments go to the end of the line, so we are done
- $return[++$returnpos] = array('comment', substr($text, $pos));
- return $return;
- break;
- case 'after_quote' :
- array_push($stack, 'after_quote');
- break;
- case 'escape' :
- // don't save the first slash
- array_push($stack, 'escape');
- continue 2;
- break;
- case 'normal' :
- // start a new segment
- if ($state == 'normal') {
- $returnpos++;
- continue 2;
- } else {
- while ($state != 'normal') {
- array_pop($stack);
- $state = $this->_getQACEvent($stack);
- }
- $returnpos++;
- }
- break;
- default :
- PEAR::raiseError("::_quoteAndCommaParser oops, state missing", null, PEAR_ERROR_DIE);
- break;
- }
- } else {
- if ($state != 'after_quote') {
- if (!isset($return[$returnpos])) {
- $return[$returnpos] = array('normal', '');
- }
- // add this character to the current ini segment if non-empty, or if in a quote
- if ($state == 'quote') {
- $return[$returnpos][1] .= $char;
- } elseif (!empty($return[$returnpos][1]) ||
- (empty($return[$returnpos][1]) && trim($char) != '')) {
- if (!isset($return[$returnpos])) {
- $return[$returnpos] = array('normal', '');
- }
- $return[$returnpos][1] .= $char;
- if (strcasecmp('true', $return[$returnpos][1]) == 0) {
- $return[$returnpos][1] = '1';
- } elseif (strcasecmp('false', $return[$returnpos][1]) == 0) {
- $return[$returnpos][1] = '';
- }
- }
- } else {
- if (trim($char) != '') {
- return PEAR::raiseError("invalid ini syntax, text after a quote not allowed '$text'",
- null, PEAR_ERROR_RETURN);
- }
- }
- }
- } else {
- // no tokens, so add this one and cycle to previous state
- $return[$returnpos][1] .= $char;
- array_pop($stack);
- }
- } while (++$pos < strlen($text));
- return $return;
- } // end func _quoteAndCommaParser
-
- /**
- * Retrieve the state off of a state stack for the Quote and Comma Parser
- * @param array $stack The parser state stack
- * @author Greg Beaver <cellog@users.sourceforge.net>
- * @access private
- */
- function _getQACEvent($stack)
- {
- return array_pop($stack);
- } // end func _getQACEvent
-
- /**
- * Returns a formatted string of the object
- * @param object $obj Container object to be output as string
- * @access public
- * @return string
- */
- function toString(&$obj)
- {
- static $childrenCount, $commaString;
-
- if (!isset($string)) {
- $string = '';
- }
- switch ($obj->type) {
- case 'blank':
- $string = "\n";
- break;
- case 'comment':
- $string = ';'.$obj->content."\n";
- break;
- case 'directive':
- $count = $obj->parent->countChildren('directive', $obj->name);
- $content = $obj->content;
- if ($content === false) {
- $content = '0';
- } elseif ($content === true) {
- $content = '1';
- } elseif (strlen(trim($content)) < strlen($content) ||
- strpos($content, ',') !== false ||
- strpos($content, ';') !== false ||
- strpos($content, '=') !== false ||
- strpos($content, '"') !== false ||
- strpos($content, '%') !== false ||
- strpos($content, '~') !== false) {
- $content = '"'.addslashes($content).'"';
- }
- if ($count > 1) {
- // multiple values for a directive are separated by a comma
- if (isset($childrenCount[$obj->name])) {
- $childrenCount[$obj->name]++;
- } else {
- $childrenCount[$obj->name] = 0;
- $commaString[$obj->name] = $obj->name.' = ';
- }
- if ($childrenCount[$obj->name] == $count-1) {
- // Clean the static for future calls to toString
- $string .= $commaString[$obj->name].$content."\n";
- unset($childrenCount[$obj->name]);
- unset($commaString[$obj->name]);
- } else {
- $commaString[$obj->name] .= $content.', ';
- }
- } else {
- $string = $obj->name.' = '.$content."\n";
- }
- break;
- case 'section':
- if (!$obj->isRoot()) {
- $string = '['.$obj->name."]\n";
- }
- if (count($obj->children) > 0) {
- for ($i = 0; $i < count($obj->children); $i++) {
- $string .= $this->toString($obj->getChild($i));
- }
- }
- break;
- default:
- $string = '';
- }
- return $string;
- } // end func toString
-} // end class Config_Container_IniCommented
-?>
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Bertrand Mansion <bmansion@mamasam.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: IniFile.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
-
-/**
-* Config parser for PHP .ini files
-* Faster because it uses parse_ini_file() but get rid of comments,
-* quotes, types and converts On, Off, True, False, Yes, No to 0 and 1.
-*
-* @author Bertrand Mansion <bmansion@mamasam.com>
-* @package Config
-*/
-class Config_Container_IniFile {
-
- /**
- * This class options
- * Not used at the moment
- *
- * @var array
- */
- var $options = array();
-
- /**
- * Constructor
- *
- * @access public
- * @param string $options (optional)Options to be used by renderer
- */
- function Config_Container_IniFile($options = array())
- {
- $this->options = $options;
- } // end constructor
-
- /**
- * Parses the data of the given configuration file
- *
- * @access public
- * @param string $datasrc path to the configuration file
- * @param object $obj reference to a config object
- * @return mixed returns a PEAR_ERROR, if error occurs or true if ok
- */
- function &parseDatasrc($datasrc, &$obj)
- {
- $return = true;
- if (!file_exists($datasrc)) {
- return PEAR::raiseError("Datasource file does not exist.", null, PEAR_ERROR_RETURN);
- }
- $currentSection =& $obj->container;
- $confArray = parse_ini_file($datasrc, true);
- if (!$confArray) {
- return PEAR::raiseError("File '$datasrc' does not contain configuration data.", null, PEAR_ERROR_RETURN);
- }
- foreach ($confArray as $key => $value) {
- if (is_array($value)) {
- $currentSection =& $obj->container->createSection($key);
- foreach ($value as $directive => $content) {
- // try to split the value if comma found
- if (strpos($content, '"') === false) {
- $values = preg_split('/\s*,\s+/', $content);
- if (count($values) > 1) {
- foreach ($values as $k => $v) {
- $currentSection->createDirective($directive, $v);
- }
- } else {
- $currentSection->createDirective($directive, $content);
- }
- } else {
- $currentSection->createDirective($directive, $content);
- }
- }
- } else {
- $currentSection->createDirective($key, $value);
- }
- }
- return $return;
- } // end func parseDatasrc
-
- /**
- * Returns a formatted string of the object
- * @param object $obj Container object to be output as string
- * @access public
- * @return string
- */
- function toString(&$obj)
- {
- static $childrenCount, $commaString;
-
- if (!isset($string)) {
- $string = '';
- }
- switch ($obj->type) {
- case 'blank':
- $string = "\n";
- break;
- case 'comment':
- $string = ';'.$obj->content."\n";
- break;
- case 'directive':
- $count = $obj->parent->countChildren('directive', $obj->name);
- $content = $obj->content;
- if ($content === false) {
- $content = '0';
- } elseif ($content === true) {
- $content = '1';
- } elseif (strlen(trim($content)) < strlen($content) ||
- strpos($content, ',') !== false ||
- strpos($content, ';') !== false ||
- strpos($content, '=') !== false ||
- strpos($content, '"') !== false ||
- strpos($content, '%') !== false ||
- strpos($content, '~') !== false) {
- $content = '"'.addslashes($content).'"';
- }
- if ($count > 1) {
- // multiple values for a directive are separated by a comma
- if (isset($childrenCount[$obj->name])) {
- $childrenCount[$obj->name]++;
- } else {
- $childrenCount[$obj->name] = 0;
- $commaString[$obj->name] = $obj->name.'=';
- }
- if ($childrenCount[$obj->name] == $count-1) {
- // Clean the static for future calls to toString
- $string .= $commaString[$obj->name].$content."\n";
- unset($childrenCount[$obj->name]);
- unset($commaString[$obj->name]);
- } else {
- $commaString[$obj->name] .= $content.', ';
- }
- } else {
- $string = $obj->name.'='.$content."\n";
- }
- break;
- case 'section':
- if (!$obj->isRoot()) {
- $string = '['.$obj->name."]\n";
- }
- if (count($obj->children) > 0) {
- for ($i = 0; $i < count($obj->children); $i++) {
- $string .= $this->toString($obj->getChild($i));
- }
- }
- break;
- default:
- $string = '';
- }
- return $string;
- } // end func toString
-} // end class Config_Container_IniFile
-?>
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Bertrand Mansion <bmansion@mamasam.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: PHPArray.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
-
-/**
-* Config parser for common PHP configuration array
-* such as found in the horde project.
-*
-* Options expected is:
-* 'name' => 'conf'
-* Name of the configuration array.
-* Default is $conf[].
-* 'useAttr' => true
-* Whether we render attributes
-*
-* @author Bertrand Mansion <bmansion@mamasam.com>
-* @package Config
-*/
-class Config_Container_PHPArray {
-
- /**
- * This class options:
- * - name of the config array to parse/output
- * Ex: $options['name'] = 'myconf';
- * - Whether to add attributes to the array
- * Ex: $options['useAttr'] = false;
- * - Whether to treat numbered arrays as duplicates of their parent directive
- * or as individual directives
- * Ex: $options['duplicateDirectives'] = false;
- *
- * @var array
- */
- var $options = array('name' => 'conf',
- 'useAttr' => true,
- 'duplicateDirectives' => true);
-
- /**
- * Constructor
- *
- * @access public
- * @param string $options Options to be used by renderer
- */
- function Config_Container_PHPArray($options = array())
- {
- foreach ($options as $key => $value) {
- $this->options[$key] = $value;
- }
- } // end constructor
-
- /**
- * Parses the data of the given configuration file
- *
- * @access public
- * @param string $datasrc path to the configuration file
- * @param object $obj reference to a config object
- * @return mixed returns a PEAR_ERROR, if error occurs or true if ok
- */
- function &parseDatasrc($datasrc, &$obj)
- {
- $return = true;
- if (empty($datasrc)) {
- return PEAR::raiseError("Datasource file path is empty.", null, PEAR_ERROR_RETURN);
- }
- if (is_array($datasrc)) {
- $this->_parseArray($datasrc, $obj->container);
- } else {
- if (!file_exists($datasrc)) {
- return PEAR::raiseError("Datasource file does not exist.", null, PEAR_ERROR_RETURN);
- } else {
- include($datasrc);
- if (!isset(${$this->options['name']}) || !is_array(${$this->options['name']})) {
- return PEAR::raiseError("File '$datasrc' does not contain a required '".$this->options['name']."' array.", null, PEAR_ERROR_RETURN);
- }
- }
- $this->_parseArray(${$this->options['name']}, $obj->container);
- }
- return $return;
- } // end func parseDatasrc
-
- /**
- * Parses the PHP array recursively
- * @param array $array array values from the config file
- * @param object $container reference to the container object
- * @access private
- * @return void
- */
- function _parseArray($array, &$container)
- {
- foreach ($array as $key => $value) {
- switch ((string)$key) {
- case '@':
- $container->setAttributes($value);
- break;
- case '#':
- $container->setType('directive');
- $container->setContent($value);
- break;
- default:
- if (is_array($value)) {
- if ($this->options['duplicateDirectives'] == true && is_integer(key($value))) {
- foreach ($value as $nestedValue) {
- if (is_array($nestedValue)) {
- $section =& $container->createSection($key);
- $this->_parseArray($nestedValue, $section);
- } else {
- $container->createDirective($key, $nestedValue);
- }
- }
- } else {
- $section =& $container->createSection($key);
- $this->_parseArray($value, $section);
- }
- } else {
- $container->createDirective($key, $value);
- }
- }
- }
- } // end func _parseArray
-
- /**
- * Returns a formatted string of the object
- * @param object $obj Container object to be output as string
- * @access public
- * @return string
- */
- function toString(&$obj)
- {
- if (!isset($string)) {
- $string = '';
- }
- switch ($obj->type) {
- case 'blank':
- $string .= "\n";
- break;
- case 'comment':
- $string .= '// '.$obj->content."\n";
- break;
- case 'directive':
- $attrString = '';
- $parentString = $this->_getParentString($obj);
- $attributes = $obj->getAttributes();
- if ($this->options['useAttr'] && is_array($attributes) && count($attributes) > 0) {
- // Directive with attributes '@' and value '#'
- $string .= $parentString."['#']";
- foreach ($attributes as $attr => $val) {
- $attrString .= $parentString."['@']"
- ."['".$attr."'] = '".addcslashes($val, "\\'")."';\n";
- }
- } else {
- $string .= $parentString;
- }
- $string .= ' = ';
- if (is_string($obj->content)) {
- $string .= "'".addcslashes($obj->content, "\\'")."'";
- } elseif (is_int($obj->content) || is_float($obj->content)) {
- $string .= $obj->content;
- } elseif (is_bool($obj->content)) {
- $string .= ($obj->content) ? 'true' : 'false';
- }
- $string .= ";\n";
- $string .= $attrString;
- break;
- case 'section':
- $attrString = '';
- $attributes = $obj->getAttributes();
- if ($this->options['useAttr'] && is_array($attributes) && count($attributes) > 0) {
- $parentString = $this->_getParentString($obj);
- foreach ($attributes as $attr => $val) {
- $attrString .= $parentString."['@']"
- ."['".$attr."'] = '".addcslashes($val, "\\'")."';\n";
- }
- }
- $string .= $attrString;
- if ($count = count($obj->children)) {
- for ($i = 0; $i < $count; $i++) {
- $string .= $this->toString($obj->getChild($i));
- }
- }
- break;
- default:
- $string = '';
- }
- return $string;
- } // end func toString
-
- /**
- * Returns a formatted string of the object parents
- * @access private
- * @return string
- */
- function _getParentString(&$obj)
- {
- $string = '';
- if (!$obj->isRoot()) {
- $string = is_int($obj->name) ? "[".$obj->name."]" : "['".$obj->name."']";
- $string = $this->_getParentString($obj->parent).$string;
- $count = $obj->parent->countChildren(null, $obj->name);
- if ($count > 1) {
- $string .= '['.$obj->getItemPosition(false).']';
- }
- }
- else {
- if (empty($this->options['name'])) {
- $string .= '$'.$obj->name;
- } else {
- $string .= '$'.$this->options['name'];
- }
- }
- return $string;
- } // end func _getParentString
-
- /**
- * Writes the configuration to a file
- *
- * @param mixed datasrc info on datasource such as path to the configuraton file
- * @param string configType (optional)type of configuration
- * @access public
- * @return string
- */
- function writeDatasrc($datasrc, &$obj)
- {
- $fp = @fopen($datasrc, 'w');
- if ($fp) {
- $string = "<?php\n". $this->toString($obj) ."?>"; // <? : Fix my syntax coloring
- $len = strlen($string);
- @flock($fp, LOCK_EX);
- @fwrite($fp, $string, $len);
- @flock($fp, LOCK_UN);
- @fclose($fp);
- return true;
- } else {
- return PEAR::raiseError('Cannot open datasource for writing.', 1, PEAR_ERROR_RETURN);
- }
- } // end func writeDatasrc
-} // end class Config_Container_PHPArray
-?>
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Phillip Oertel <me@phillipoertel.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: PHPConstants.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
-
-/**
-* Config parser for PHP constant files
-*
-* @author Phillip Oertel <me@phillipoertel.com>
-* @package Config
-* @version 0.1 (not submitted)
-*/
-
-require_once 'Config/Container.php';
-
-class Config_Container_PHPConstants extends Config_Container {
-
- /**
- * This class options
- * Not used at the moment
- *
- * @var array
- */
- var $options = array();
-
- /**
- * Constructor
- *
- * @access public
- * @param string $options (optional)Options to be used by renderer
- */
- function Config_Container_PHPConstants($options = array())
- {
- $this->options = $options;
- } // end constructor
-
- /**
- * Parses the data of the given configuration file
- *
- * @access public
- * @param string $datasrc path to the configuration file
- * @param object $obj reference to a config object
- * @return mixed returns a PEAR_ERROR, if error occurs or true if ok
- */
- function &parseDatasrc($datasrc, &$obj)
- {
- $return = true;
-
- if (!file_exists($datasrc)) {
- return PEAR::raiseError("Datasource file does not exist.", null,
- PEAR_ERROR_RETURN);
- }
-
- $fileContent = file_get_contents($datasrc, true);
-
- if (!$fileContent) {
- return PEAR::raiseError("File '$datasrc' could not be read.", null,
- PEAR_ERROR_RETURN);
- }
-
- $rows = explode("\n", $fileContent);
- for ($i=0, $max=count($rows); $i<$max; $i++) {
- $line = $rows[$i];
-
- //blanks?
-
- // sections
- if (preg_match("/^\/\/\s*$/", $line)) {
- preg_match("/^\/\/\s*(.+)$/", $rows[$i+1], $matches);
- $obj->container->createSection(trim($matches[1]));
- $i += 2;
- continue;
- }
-
- // comments
- if (preg_match("/^\/\/\s*(.+)$/", $line, $matches) ||
- preg_match("/^#\s*(.+)$/", $line, $matches)) {
- $obj->container->createComment(trim($matches[1]));
- continue;
- }
-
- // directives
- $regex = "/^\s*define\s*\('([A-Z1-9_]+)',\s*'*(.[^\']*)'*\)/";
- preg_match($regex, $line, $matches);
- if (!empty($matches)) {
- $obj->container->createDirective(trim($matches[1]),
- trim($matches[2]));
- }
- }
-
- return $return;
-
- } // end func parseDatasrc
-
- /**
- * Returns a formatted string of the object
- * @param object $obj Container object to be output as string
- * @access public
- * @return string
- */
- function toString(&$obj)
- {
- $string = '';
-
- switch ($obj->type)
- {
- case 'blank':
- $string = "\n";
- break;
-
- case 'comment':
- $string = '// '.$obj->content."\n";
- break;
-
- case 'directive':
- $content = $obj->content;
- // don't quote numeric values, true/false and constants
- if (!is_numeric($content) && !in_array($content, array('false',
- 'true')) && !preg_match('/^[A-Z_]+$/', $content)) {
- $content = "'".$content."'";
- }
- $string = 'define(\''.$obj->name.'\', '.$content.');'.chr(10);
- break;
-
- case 'section':
- if (!$obj->isRoot()) {
- $string = chr(10);
- $string .= '//'.chr(10);
- $string .= '// '.$obj->name.chr(10);
- $string .= '//'.chr(10);
- }
- if (count($obj->children) > 0) {
- for ($i = 0, $max = count($obj->children); $i < $max; $i++) {
- $string .= $this->toString($obj->getChild($i));
- }
- }
- break;
- default:
- $string = '';
- }
- return $string;
- } // end func toString
-
- /**
- * Writes the configuration to a file
- *
- * @param mixed datasrc info on datasource such as path to the file
- * @param string configType (optional)type of configuration
- * @access public
- * @return string
- */
- function writeDatasrc($datasrc, &$obj)
- {
- $fp = @fopen($datasrc, 'w');
- if ($fp) {
- $string = "<?php";
- $string .= "\n\n";
- $string .= '/**' . chr(10);
- $string .= ' *' . chr(10);
- $string .= ' * AUTOMATICALLY GENERATED CODE -
- DO NOT EDIT BY HAND' . chr(10);
- $string .= ' *' . chr(10);
- $string .= '**/' . chr(10);
- $string .= $this->toString($obj);
- $string .= "\n?>"; // <? : Fix my syntax coloring
-
- $len = strlen($string);
- @flock($fp, LOCK_EX);
- @fwrite($fp, $string, $len);
- @flock($fp, LOCK_UN);
- @fclose($fp);
-
- // need an error check here
-
- return true;
- } else {
- return PEAR::raiseError('Cannot open datasource for writing.', 1,
- PEAR_ERROR_RETURN);
- }
- } // end func writeDatasrc
-
-
-} // end class Config_Container_PHPConstants
-
-?>
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Bertrand Mansion <bmansion@mamasam.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: XML.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
-
-require_once('XML/Parser.php');
-require_once('XML/Util.php');
-
-/**
-* Config parser for XML Files
-*
-* @author Bertrand Mansion <bmansion@mamasam.com>
-* @package Config
-*/
-class Config_Container_XML extends XML_Parser
-{
- /**
- * Deep level used for indentation
- *
- * @var int
- * @access private
- */
- var $_deep = -1;
-
- /**
- * This class options:
- * version (1.0) : XML version
- * encoding (ISO-8859-1) : XML content encoding
- * name : like in phparray, name of your config global entity
- * indent : char used for indentation
- * linebreak : char used for linebreak
- * addDecl : whether to add the xml declaration at beginning or not
- * useAttr : whether to use the attributes
- * isFile : whether the given content is a file or an XML string
- * useCData : whether to surround data with <![CDATA[...]]>
- *
- * @var array
- */
- var $options = array('version' => '1.0',
- 'encoding' => 'ISO-8859-1',
- 'name' => '',
- 'indent' => ' ',
- 'linebreak' => "\n",
- 'addDecl' => true,
- 'useAttr' => true,
- 'isFile' => true,
- 'useCData' => false);
-
- /**
- * Container objects
- *
- * @var array
- */
- var $containers = array();
-
- /**
- * Constructor
- *
- * @access public
- * @param string $options Options to be used by renderer
- * version : (1.0) XML version
- * encoding : (ISO-8859-1) XML content encoding
- * name : like in phparray, name of your config global entity
- * indent : char used for indentation
- * linebreak : char used for linebreak
- * addDecl : whether to add the xml declaration at beginning or not
- * useAttr : whether to use the attributes
- * isFile : whether the given content is a file or an XML string
- */
- function Config_Container_XML($options = array())
- {
- foreach ($options as $key => $value) {
- $this->options[$key] = $value;
- }
- } // end constructor
-
- /**
- * Parses the data of the given configuration file
- *
- * @access public
- * @param string $datasrc path to the configuration file
- * @param object $obj reference to a config object
- * @return mixed returns a PEAR_ERROR, if error occurs or true if ok
- */
- function &parseDatasrc($datasrc, &$obj)
- {
- $err = true;
- $this->folding = false;
- $this->cdata = null;
- $this->XML_Parser($this->options['encoding'], 'event');
- $this->containers[0] =& $obj->container;
- if (is_string($datasrc)) {
- if ($this->options['isFile']) {
- $err = $this->setInputFile($datasrc);
- if (PEAR::isError($err)) {
- return $err;
- }
- $err = $this->parse();
- } else {
- $err = $this->parseString($datasrc, true);
- }
- } else {
- $this->setInput($datasrc);
- $err = $this->parse();
- }
- return $err;
- } // end func parseDatasrc
-
- /**
- * Handler for the xml-data
- *
- * @param mixed $xp ignored
- * @param string $elem name of the element
- * @param array $attribs attributes for the generated node
- *
- * @access private
- */
- function startHandler($xp, $elem, &$attribs)
- {
- $container =& new Config_Container('section', $elem, null, $attribs);
- $this->containers[] =& $container;
- return null;
- } // end func startHandler
-
- /**
- * Handler for the xml-data
- *
- * @param mixed $xp ignored
- * @param string $elem name of the element
- *
- * @access private
- */
- function endHandler($xp, $elem)
- {
- $count = count($this->containers);
- $container =& $this->containers[$count-1];
- $currentSection =& $this->containers[$count-2];
- if (count($container->children) == 0) {
- $container->setType('directive');
- $container->setContent(trim($this->cdata));
- }
- $currentSection->addItem($container);
- array_pop($this->containers);
- $this->cdata = null;
- return null;
- } // end func endHandler
-
- /*
- * The xml character data handler
- *
- * @param mixed $xp ignored
- * @param string $data PCDATA between tags
- *
- * @access private
- */
- function cdataHandler($xp, $cdata)
- {
- $this->cdata .= $cdata;
- } // end func cdataHandler
-
- /**
- * Returns a formatted string of the object
- * @param object $obj Container object to be output as string
- * @access public
- * @return string
- */
- function toString(&$obj)
- {
- $indent = '';
- if (!$obj->isRoot()) {
- // no indent for root
- $this->_deep++;
- $indent = str_repeat($this->options['indent'], $this->_deep);
- } else {
- // Initialize string with xml declaration
- $string = '';
- if ($this->options['addDecl']) {
- $string .= XML_Util::getXMLDeclaration($this->options['version'], $this->options['encoding']);
- $string .= $this->options['linebreak'];
- }
- if (!empty($this->options['name'])) {
- $string .= '<'.$this->options['name'].'>'.$this->options['linebreak'];
- $this->_deep++;
- $indent = str_repeat($this->options['indent'], $this->_deep);
- }
- }
- if (!isset($string)) {
- $string = '';
- }
- switch ($obj->type) {
- case 'directive':
- $attributes = ($this->options['useAttr']) ? $obj->attributes : array();
- $string .= $indent.XML_Util::createTag($obj->name, $attributes, $obj->content, null,
- ($this->options['useCData'] ? XML_UTIL_CDATA_SECTION : XML_UTIL_REPLACE_ENTITIES));
- $string .= $this->options['linebreak'];
- break;
- case 'comment':
- $string .= $indent.'<!-- '.$obj->content.' -->';
- $string .= $this->options['linebreak'];
- break;
- case 'section':
- if (!$obj->isRoot()) {
- $string = $indent.'<'.$obj->name;
- $string .= ($this->options['useAttr']) ? XML_Util::attributesToString($obj->attributes) : '';
- }
- if ($children = count($obj->children)) {
- if (!$obj->isRoot()) {
- $string .= '>'.$this->options['linebreak'];
- }
- for ($i = 0; $i < $children; $i++) {
- $string .= $this->toString($obj->getChild($i));
- }
- }
- if (!$obj->isRoot()) {
- if ($children) {
- $string .= $indent.'</'.$obj->name.'>'.$this->options['linebreak'];
- } else {
- $string .= '/>'.$this->options['linebreak'];
- }
- } else {
- if (!empty($this->options['name'])) {
- $string .= '</'.$this->options['name'].'>'.$this->options['linebreak'];
- }
- }
- break;
- default:
- $string = '';
- }
- if (!$obj->isRoot()) {
- $this->_deep--;
- }
- return $string;
- } // end func toString
-} // end class Config_Container_XML
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP Version 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available through the world-wide-web at the following url: |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Andrei Zmievski <andrei@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Getopt.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
-
-require_once 'PEAR.php';
-
-/**
- * Command-line options parsing class.
- *
- * @author Andrei Zmievski <andrei@php.net>
- *
- */
-class Console_Getopt {
- /**
- * Parses the command-line options.
- *
- * The first parameter to this function should be the list of command-line
- * arguments without the leading reference to the running program.
- *
- * The second parameter is a string of allowed short options. Each of the
- * option letters can be followed by a colon ':' to specify that the option
- * requires an argument, or a double colon '::' to specify that the option
- * takes an optional argument.
- *
- * The third argument is an optional array of allowed long options. The
- * leading '--' should not be included in the option name. Options that
- * require an argument should be followed by '=', and options that take an
- * option argument should be followed by '=='.
- *
- * The return value is an array of two elements: the list of parsed
- * options and the list of non-option command-line arguments. Each entry in
- * the list of parsed options is a pair of elements - the first one
- * specifies the option, and the second one specifies the option argument,
- * if there was one.
- *
- * Long and short options can be mixed.
- *
- * Most of the semantics of this function are based on GNU getopt_long().
- *
- * @param array $args an array of command-line arguments
- * @param string $short_options specifies the list of allowed short options
- * @param array $long_options specifies the list of allowed long options
- *
- * @return array two-element array containing the list of parsed options and
- * the non-option arguments
- *
- * @access public
- *
- */
- function getopt2($args, $short_options, $long_options = null)
- {
- return Console_Getopt::doGetopt(2, $args, $short_options, $long_options);
- }
-
- /**
- * This function expects $args to start with the script name (POSIX-style).
- * Preserved for backwards compatibility.
- * @see getopt2()
- */
- function getopt($args, $short_options, $long_options = null)
- {
- return Console_Getopt::doGetopt(1, $args, $short_options, $long_options);
- }
-
- /**
- * The actual implementation of the argument parsing code.
- */
- function doGetopt($version, $args, $short_options, $long_options = null)
- {
- // in case you pass directly readPHPArgv() as the first arg
- if (PEAR::isError($args)) {
- return $args;
- }
- if (empty($args)) {
- return array(array(), array());
- }
- $opts = array();
- $non_opts = array();
-
- settype($args, 'array');
-
- if ($long_options) {
- sort($long_options);
- }
-
- /*
- * Preserve backwards compatibility with callers that relied on
- * erroneous POSIX fix.
- */
- if ($version < 2) {
- if (isset($args[0]{0}) && $args[0]{0} != '-') {
- array_shift($args);
- }
- }
-
- reset($args);
- while (list($i, $arg) = each($args)) {
-
- /* The special element '--' means explicit end of
- options. Treat the rest of the arguments as non-options
- and end the loop. */
- if ($arg == '--') {
- $non_opts = array_merge($non_opts, array_slice($args, $i + 1));
- break;
- }
-
- if ($arg{0} != '-' || (strlen($arg) > 1 && $arg{1} == '-' && !$long_options)) {
- $non_opts = array_merge($non_opts, array_slice($args, $i));
- break;
- } elseif (strlen($arg) > 1 && $arg{1} == '-') {
- $error = Console_Getopt::_parseLongOption(substr($arg, 2), $long_options, $opts, $args);
- if (PEAR::isError($error))
- return $error;
- } elseif ($arg == '-') {
- // - is stdin
- $non_opts = array_merge($non_opts, array_slice($args, $i));
- break;
- } else {
- $error = Console_Getopt::_parseShortOption(substr($arg, 1), $short_options, $opts, $args);
- if (PEAR::isError($error))
- return $error;
- }
- }
-
- return array($opts, $non_opts);
- }
-
- /**
- * @access private
- *
- */
- function _parseShortOption($arg, $short_options, &$opts, &$args)
- {
- for ($i = 0; $i < strlen($arg); $i++) {
- $opt = $arg{$i};
- $opt_arg = null;
-
- /* Try to find the short option in the specifier string. */
- if (($spec = strstr($short_options, $opt)) === false || $arg{$i} == ':')
- {
- return PEAR::raiseError("Console_Getopt: unrecognized option -- $opt");
- }
-
- if (strlen($spec) > 1 && $spec{1} == ':') {
- if (strlen($spec) > 2 && $spec{2} == ':') {
- if ($i + 1 < strlen($arg)) {
- /* Option takes an optional argument. Use the remainder of
- the arg string if there is anything left. */
- $opts[] = array($opt, substr($arg, $i + 1));
- break;
- }
- } else {
- /* Option requires an argument. Use the remainder of the arg
- string if there is anything left. */
- if ($i + 1 < strlen($arg)) {
- $opts[] = array($opt, substr($arg, $i + 1));
- break;
- } else if (list(, $opt_arg) = each($args)) {
- /* Else use the next argument. */;
- if (Console_Getopt::_isShortOpt($opt_arg) || Console_Getopt::_isLongOpt($opt_arg)) {
- return PEAR::raiseError("Console_Getopt: option requires an argument -- $opt");
- }
- } else {
- return PEAR::raiseError("Console_Getopt: option requires an argument -- $opt");
- }
- }
- }
-
- $opts[] = array($opt, $opt_arg);
- }
- }
-
- /**
- * @access private
- *
- */
- function _isShortOpt($arg)
- {
- return strlen($arg) == 2 && $arg[0] == '-' && preg_match('/[a-zA-Z]/', $arg[1]);
- }
-
- /**
- * @access private
- *
- */
- function _isLongOpt($arg)
- {
- return strlen($arg) > 2 && $arg[0] == '-' && $arg[1] == '-' &&
- preg_match('/[a-zA-Z]+$/', substr($arg, 2));
- }
-
- /**
- * @access private
- *
- */
- function _parseLongOption($arg, $long_options, &$opts, &$args)
- {
- @list($opt, $opt_arg) = explode('=', $arg, 2);
- $opt_len = strlen($opt);
-
- for ($i = 0; $i < count($long_options); $i++) {
- $long_opt = $long_options[$i];
- $opt_start = substr($long_opt, 0, $opt_len);
- $long_opt_name = str_replace('=', '', $long_opt);
-
- /* Option doesn't match. Go on to the next one. */
- if ($long_opt_name != $opt) {
- continue;
- }
-
- $opt_rest = substr($long_opt, $opt_len);
-
- /* Check that the options uniquely matches one of the allowed
- options. */
- if ($i + 1 < count($long_options)) {
- $next_option_rest = substr($long_options[$i + 1], $opt_len);
- } else {
- $next_option_rest = '';
- }
- if ($opt_rest != '' && $opt{0} != '=' &&
- $i + 1 < count($long_options) &&
- $opt == substr($long_options[$i+1], 0, $opt_len) &&
- $next_option_rest != '' &&
- $next_option_rest{0} != '=') {
- return PEAR::raiseError("Console_Getopt: option --$opt is ambiguous");
- }
-
- if (substr($long_opt, -1) == '=') {
- if (substr($long_opt, -2) != '==') {
- /* Long option requires an argument.
- Take the next argument if one wasn't specified. */;
- if (!strlen($opt_arg) && !(list(, $opt_arg) = each($args))) {
- return PEAR::raiseError("Console_Getopt: option --$opt requires an argument");
- }
- if (Console_Getopt::_isShortOpt($opt_arg) || Console_Getopt::_isLongOpt($opt_arg)) {
- return PEAR::raiseError("Console_Getopt: option requires an argument --$opt");
- }
- }
- } else if ($opt_arg) {
- return PEAR::raiseError("Console_Getopt: option --$opt doesn't allow an argument");
- }
-
- $opts[] = array('--' . $opt, $opt_arg);
- return;
- }
-
- return PEAR::raiseError("Console_Getopt: unrecognized option --$opt");
- }
-
- /**
- * Safely read the $argv PHP array across different PHP configurations.
- * Will take care on register_globals and register_argc_argv ini directives
- *
- * @access public
- * @return mixed the $argv PHP array or PEAR error if not registered
- */
- function readPHPArgv()
- {
- global $argv;
- if (!is_array($argv)) {
- if (!@is_array($_SERVER['argv'])) {
- if (!@is_array($GLOBALS['HTTP_SERVER_VARS']['argv'])) {
- return PEAR::raiseError("Console_Getopt: Could not read cmd args (register_argc_argv=Off?)");
- }
- return $GLOBALS['HTTP_SERVER_VARS']['argv'];
- }
- return $_SERVER['argv'];
- }
- return $argv;
- }
-
-}
-
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */
-
-/**
- * Auth_Container Base Class
- *
- * PHP versions 4 and 5
- *
- * LICENSE: This source file is subject to version 3.01 of the PHP license
- * that is available through the world-wide-web at the following URI:
- * http://www.php.net/license/3_01.txt. If you did not receive a copy of
- * the PHP License and are unable to obtain it through the web, please
- * send a note to license@php.net so we can mail you a copy immediately.
- *
- * @category Authentication
- * @package Auth
- * @author Martin Jansen <mj@php.net>
- * @author Adam Ashley <aashley@php.net>
- * @copyright 2001-2006 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version CVS: $Id: Container.php,v 1.1.1.1 2008/04/28 15:20:46 jamie Exp $
- * @link http://pear.php.net/package/Auth
- */
-
-/**
- * Storage class for fetching login data
- *
- * @category Authentication
- * @package Auth
- * @author Martin Jansen <mj@php.net>
- * @author Adam Ashley <aashley@php.net>
- * @copyright 2001-2006 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version Release: 1.5.4 File: $Revision: 1.1.1.1 $
- * @link http://pear.php.net/package/Auth
- */
-class Auth_Container
-{
-
- // {{{ properties
-
- /**
- * User that is currently selected from the storage container.
- *
- * @access public
- */
- var $activeUser = "";
-
- /**
- * The Auth object this container is attached to.
- *
- * @access public
- */
- var $_auth_obj = null;
-
- // }}}
- // {{{ Auth_Container() [constructor]
-
- /**
- * Constructor
- *
- * Has to be overwritten by each storage class
- *
- * @access public
- */
- function Auth_Container()
- {
- }
-
- // }}}
- // {{{ fetchData()
-
- /**
- * Fetch data from storage container
- *
- * Has to be overwritten by each storage class
- *
- * @access public
- */
- function fetchData($username, $password, $isChallengeResponse=false)
- {
- $this->log('Auth_Container::fetchData() called.', AUTH_LOG_DEBUG);
- }
-
- // }}}
- // {{{ verifyPassword()
-
- /**
- * Crypt and verfiy the entered password
- *
- * @param string Entered password
- * @param string Password from the data container (usually this password
- * is already encrypted.
- * @param string Type of algorithm with which the password from
- * the container has been crypted. (md5, crypt etc.)
- * Defaults to "md5".
- * @return bool True, if the passwords match
- */
- function verifyPassword($password1, $password2, $cryptType = "md5")
- {
- $this->log('Auth_Container::verifyPassword() called.', AUTH_LOG_DEBUG);
- switch ($cryptType) {
- case "crypt" :
- return ((string)crypt($password1, $password2) === (string)$password2);
- break;
- case "none" :
- case "" :
- return ((string)$password1 === (string)$password2);
- break;
- case "md5" :
- return ((string)md5($password1) === (string)$password2);
- break;
- default :
- if (function_exists($cryptType)) {
- return ((string)$cryptType($password1) === (string)$password2);
- } elseif (method_exists($this,$cryptType)) {
- return ((string)$this->$cryptType($password1) === (string)$password2);
- } else {
- return false;
- }
- break;
- }
- }
-
- // }}}
- // {{{ supportsChallengeResponse()
-
- /**
- * Returns true if the container supports Challenge Response
- * password authentication
- */
- function supportsChallengeResponse()
- {
- return(false);
- }
-
- // }}}
- // {{{ getCryptType()
-
- /**
- * Returns the crypt current crypt type of the container
- *
- * @return string
- */
- function getCryptType()
- {
- return('');
- }
-
- // }}}
- // {{{ listUsers()
-
- /**
- * List all users that are available from the storage container
- */
- function listUsers()
- {
- $this->log('Auth_Container::listUsers() called.', AUTH_LOG_DEBUG);
- return AUTH_METHOD_NOT_SUPPORTED;
- }
-
- // }}}
- // {{{ getUser()
-
- /**
- * Returns a user assoc array
- *
- * Containers which want should overide this
- *
- * @param string The username
- */
- function getUser($username)
- {
- $this->log('Auth_Container::getUser() called.', AUTH_LOG_DEBUG);
- $users = $this->listUsers();
- if ($users === AUTH_METHOD_NOT_SUPPORTED) {
- return AUTH_METHOD_NOT_SUPPORTED;
- }
- for ($i=0; $c = count($users), $i<$c; $i++) {
- if ($users[$i]['username'] == $username) {
- return $users[$i];
- }
- }
- return false;
- }
-
- // }}}
- // {{{ addUser()
-
- /**
- * Add a new user to the storage container
- *
- * @param string Username
- * @param string Password
- * @param array Additional information
- *
- * @return boolean
- */
- function addUser($username, $password, $additional=null)
- {
- $this->log('Auth_Container::addUser() called.', AUTH_LOG_DEBUG);
- return AUTH_METHOD_NOT_SUPPORTED;
- }
-
- // }}}
- // {{{ removeUser()
-
- /**
- * Remove user from the storage container
- *
- * @param string Username
- */
- function removeUser($username)
- {
- $this->log('Auth_Container::removeUser() called.', AUTH_LOG_DEBUG);
- return AUTH_METHOD_NOT_SUPPORTED;
- }
-
- // }}}
- // {{{ changePassword()
-
- /**
- * Change password for user in the storage container
- *
- * @param string Username
- * @param string The new password
- */
- function changePassword($username, $password)
- {
- $this->log('Auth_Container::changePassword() called.', AUTH_LOG_DEBUG);
- return AUTH_METHOD_NOT_SUPPORTED;
- }
-
- // }}}
- // {{{ log()
-
- /**
- * Log a message to the Auth log
- *
- * @param string The message
- * @param int
- * @return boolean
- */
- function log($message, $level = AUTH_LOG_DEBUG) {
-
- if (is_null($this->_auth_obj)) {
-
- return false;
-
- } else {
-
- return $this->_auth_obj->log($message, $level);
-
- }
-
- }
-
- // }}}
-
-}
-
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */
-
-/**
- * Storage driver for use against a PHP Array
- *
- * PHP versions 4 and 5
- *
- * LICENSE: This source file is subject to version 3.01 of the PHP license
- * that is available through the world-wide-web at the following URI:
- * http://www.php.net/license/3_01.txt. If you did not receive a copy of
- * the PHP License and are unable to obtain it through the web, please
- * send a note to license@php.net so we can mail you a copy immediately.
- *
- * @category Authentication
- * @package Auth
- * @author georg_1 at have2 dot com
- * @author Adam Ashley <aashley@php.net>
- * @copyright 2001-2006 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version CVS: $Id: Array.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- * @since File available since Release 1.4.0
- */
-
-/**
- * Include Auth_Container base class
- */
-require_once "Auth/Container.php";
-/**
- * Include PEAR package for error handling
- */
-require_once "PEAR.php";
-
-/**
- * Storage driver for fetching authentication data from a PHP Array
- *
- * This container takes two options when configuring:
- *
- * cryptType: The crypt used to store the password. Currently recognised
- * are: none, md5 and crypt. default: none
- * users: A named array of usernames and passwords.
- * Ex:
- * array(
- * 'guest' => '084e0343a0486ff05530df6c705c8bb4', // password guest
- * 'georg' => 'fc77dba827fcc88e0243404572c51325' // password georg
- * )
- *
- * Usage Example:
- * <?php
- * $AuthOptions = array(
- * 'users' => array(
- * 'guest' => '084e0343a0486ff05530df6c705c8bb4', // password guest
- * 'georg' => 'fc77dba827fcc88e0243404572c51325' // password georg
- * ),
- * 'cryptType'=>'md5',
- * );
- *
- * $auth = new Auth("Array", $AuthOptions);
- * ?>
- *
- * @category Authentication
- * @package Auth
- * @author georg_1 at have2 dot com
- * @author Adam Ashley <aashley@php.net>
- * @copyright 2001-2006 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version Release: 1.5.4 File: $Revision: 1.1.1.1 $
- * @since File available since Release 1.4.0
- */
-
-class Auth_Container_Array extends Auth_Container {
-
- // {{{ properties
-
- /**
- * The users and their password to authenticate against
- *
- * @var array $users
- */
- var $users;
-
- /**
- * The cryptType used on the passwords
- *
- * @var string $cryptType
- */
- var $cryptType = 'none';
-
- // }}}
- // {{{ Auth_Container_Array()
-
- /**
- * Constructor for Array Container
- *
- * @param array $data Options for the container
- * @return void
- */
- function Auth_Container_Array($data)
- {
- if (!is_array($data)) {
- PEAR::raiseError('The options for Auth_Container_Array must be an array');
- }
- if (isset($data['users']) && is_array($data['users'])) {
- $this->users = $data['users'];
- } else {
- $this->users = array();
- PEAR::raiseError('Auth_Container_Array: no user data found in options array');
- }
- if (isset($data['cryptType'])) {
- $this->cryptType = $data['cryptType'];
- }
- }
-
- // }}}
- // {{{ fetchData()
-
- /**
- * Get user information from array
- *
- * This function uses the given username to fetch the corresponding
- * login data from the array. If an account that matches the passed
- * username and password is found, the function returns true.
- * Otherwise it returns false.
- *
- * @param string Username
- * @param string Password
- * @return boolean|PEAR_Error Error object or boolean
- */
- function fetchData($user, $pass)
- {
- $this->log('Auth_Container_Array::fetchData() called.', AUTH_LOG_DEBUG);
- if ( isset($this->users[$user])
- && $this->verifyPassword($pass, $this->users[$user], $this->cryptType)) {
- return true;
- }
- return false;
- }
-
- // }}}
- // {{{ listUsers()
-
- /**
- * Returns a list of users available within the container
- *
- * @return array
- */
- function listUsers()
- {
- $this->log('Auth_Container_Array::listUsers() called.', AUTH_LOG_DEBUG);
- $ret = array();
- foreach ($this->users as $username => $password) {
- $ret[]['username'] = $username;
- }
- return $ret;
- }
-
- // }}}
-
-}
-
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */
-
-/**
- * Storage driver for use against PEAR DB
- *
- * PHP versions 4 and 5
- *
- * LICENSE: This source file is subject to version 3.01 of the PHP license
- * that is available through the world-wide-web at the following URI:
- * http://www.php.net/license/3_01.txt. If you did not receive a copy of
- * the PHP License and are unable to obtain it through the web, please
- * send a note to license@php.net so we can mail you a copy immediately.
- *
- * @category Authentication
- * @package Auth
- * @author Martin Jansen <mj@php.net>
- * @author Adam Ashley <aashley@php.net>
- * @copyright 2001-2006 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version CVS: $Id: DB.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- * @link http://pear.php.net/package/Auth
- */
-
-/**
- * Include Auth_Container base class
- */
-require_once 'Auth/Container.php';
-/**
- * Include PEAR DB
- */
-require_once 'DB.php';
-
-/**
- * Storage driver for fetching login data from a database
- *
- * This storage driver can use all databases which are supported
- * by the PEAR DB abstraction layer to fetch login data.
- *
- * @category Authentication
- * @package Auth
- * @author Martin Jansen <mj@php.net>
- * @author Adam Ashley <aashley@php.net>
- * @copyright 2001-2006 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version Release: 1.5.4 File: $Revision: 1.1.1.1 $
- * @link http://pear.php.net/package/Auth
- */
-class Auth_Container_DB extends Auth_Container
-{
-
- // {{{ properties
-
- /**
- * Additional options for the storage container
- * @var array
- */
- var $options = array();
-
- /**
- * DB object
- * @var object
- */
- var $db = null;
- var $dsn = '';
-
- /**
- * User that is currently selected from the DB.
- * @var string
- */
- var $activeUser = '';
-
- // }}}
- // {{{ Auth_Container_DB [constructor]
-
- /**
- * Constructor of the container class
- *
- * Save the initial options passed to the container. Initiation of the DB
- * connection is no longer performed here and is only done when needed.
- *
- * @param string Connection data or DB object
- * @return object Returns an error object if something went wrong
- */
- function Auth_Container_DB($dsn)
- {
- $this->_setDefaults();
-
- if (is_array($dsn)) {
- $this->_parseOptions($dsn);
-
- if (empty($this->options['dsn'])) {
- PEAR::raiseError('No connection parameters specified!');
- }
- } else {
- $this->options['dsn'] = $dsn;
- }
- }
-
- // }}}
- // {{{ _connect()
-
- /**
- * Connect to database by using the given DSN string
- *
- * @access private
- * @param string DSN string
- * @return mixed Object on error, otherwise bool
- */
- function _connect($dsn)
- {
- $this->log('Auth_Container_DB::_connect() called.', AUTH_LOG_DEBUG);
-
- if (is_string($dsn) || is_array($dsn)) {
- $this->db = DB::Connect($dsn, $this->options['db_options']);
- } elseif (is_subclass_of($dsn, 'db_common')) {
- $this->db = $dsn;
- } elseif (DB::isError($dsn)) {
- return PEAR::raiseError($dsn->getMessage(), $dsn->getCode());
- } else {
- return PEAR::raiseError('The given dsn was not valid in file ' . __FILE__ . ' at line ' . __LINE__,
- 41,
- PEAR_ERROR_RETURN,
- null,
- null
- );
- }
-
- if (DB::isError($this->db) || PEAR::isError($this->db)) {
- return PEAR::raiseError($this->db->getMessage(), $this->db->getCode());
- } else {
- return true;
- }
- }
-
- // }}}
- // {{{ _prepare()
-
- /**
- * Prepare database connection
- *
- * This function checks if we have already opened a connection to
- * the database. If that's not the case, a new connection is opened.
- *
- * @access private
- * @return mixed True or a DB error object.
- */
- function _prepare()
- {
- if (!DB::isConnection($this->db)) {
- $res = $this->_connect($this->options['dsn']);
- if (DB::isError($res) || PEAR::isError($res)) {
- return $res;
- }
- }
- if ($this->options['auto_quote'] && $this->db->dsn['phptype'] != 'sqlite') {
- $this->options['final_table'] = $this->db->quoteIdentifier($this->options['table']);
- $this->options['final_usernamecol'] = $this->db->quoteIdentifier($this->options['usernamecol']);
- $this->options['final_passwordcol'] = $this->db->quoteIdentifier($this->options['passwordcol']);
- } else {
- $this->options['final_table'] = $this->options['table'];
- $this->options['final_usernamecol'] = $this->options['usernamecol'];
- $this->options['final_passwordcol'] = $this->options['passwordcol'];
- }
- return true;
- }
-
- // }}}
- // {{{ query()
-
- /**
- * Prepare query to the database
- *
- * This function checks if we have already opened a connection to
- * the database. If that's not the case, a new connection is opened.
- * After that the query is passed to the database.
- *
- * @access public
- * @param string Query string
- * @return mixed a DB_result object or DB_OK on success, a DB
- * or PEAR error on failure
- */
- function query($query)
- {
- $err = $this->_prepare();
- if ($err !== true) {
- return $err;
- }
- return $this->db->query($query);
- }
-
- // }}}
- // {{{ _setDefaults()
-
- /**
- * Set some default options
- *
- * @access private
- * @return void
- */
- function _setDefaults()
- {
- $this->options['table'] = 'auth';
- $this->options['usernamecol'] = 'username';
- $this->options['passwordcol'] = 'password';
- $this->options['dsn'] = '';
- $this->options['db_fields'] = '';
- $this->options['cryptType'] = 'md5';
- $this->options['db_options'] = array();
- $this->options['db_where'] = '';
- $this->options['auto_quote'] = true;
- }
-
- // }}}
- // {{{ _parseOptions()
-
- /**
- * Parse options passed to the container class
- *
- * @access private
- * @param array
- */
- function _parseOptions($array)
- {
- foreach ($array as $key => $value) {
- if (isset($this->options[$key])) {
- $this->options[$key] = $value;
- }
- }
- }
-
- // }}}
- // {{{ _quoteDBFields()
-
- /**
- * Quote the db_fields option to avoid the possibility of SQL injection.
- *
- * @access private
- * @return string A properly quoted string that can be concatenated into a
- * SELECT clause.
- */
- function _quoteDBFields()
- {
- if (isset($this->options['db_fields'])) {
- if (is_array($this->options['db_fields'])) {
- if ($this->options['auto_quote']) {
- $fields = array();
- foreach ($this->options['db_fields'] as $field) {
- $fields[] = $this->db->quoteIdentifier($field);
- }
- return implode(', ', $fields);
- } else {
- return implode(', ', $this->options['db_fields']);
- }
- } else {
- if (strlen($this->options['db_fields']) > 0) {
- if ($this->options['auto_quote']) {
- return $this->db->quoteIdentifier($this->options['db_fields']);
- } else {
- return $this->options['db_fields'];
- }
- }
- }
- }
-
- return '';
- }
-
- // }}}
- // {{{ fetchData()
-
- /**
- * Get user information from database
- *
- * This function uses the given username to fetch
- * the corresponding login data from the database
- * table. If an account that matches the passed username
- * and password is found, the function returns true.
- * Otherwise it returns false.
- *
- * @param string Username
- * @param string Password
- * @param boolean If true password is secured using a md5 hash
- * the frontend and auth are responsible for making sure the container supports
- * challenge response password authentication
- * @return mixed Error object or boolean
- */
- function fetchData($username, $password, $isChallengeResponse=false)
- {
- $this->log('Auth_Container_DB::fetchData() called.', AUTH_LOG_DEBUG);
- // Prepare for a database query
- $err = $this->_prepare();
- if ($err !== true) {
- return PEAR::raiseError($err->getMessage(), $err->getCode());
- }
-
- // Find if db_fields contains a *, if so assume all columns are selected
- if (is_string($this->options['db_fields'])
- && strstr($this->options['db_fields'], '*')) {
- $sql_from = "*";
- } else {
- $sql_from = $this->options['final_usernamecol'].
- ", ".$this->options['final_passwordcol'];
-
- if (strlen($fields = $this->_quoteDBFields()) > 0) {
- $sql_from .= ', '.$fields;
- }
- }
-
- $query = "SELECT ".$sql_from.
- " FROM ".$this->options['final_table'].
- " WHERE ".$this->options['final_usernamecol']." = ".$this->db->quoteSmart($username);
-
- // check if there is an optional parameter db_where
- if ($this->options['db_where'] != '') {
- // there is one, so add it to the query
- $query .= " AND ".$this->options['db_where'];
- }
-
- $this->log('Running SQL against DB: '.$query, AUTH_LOG_DEBUG);
-
- $res = $this->db->getRow($query, null, DB_FETCHMODE_ASSOC);
-
- if (DB::isError($res)) {
- return PEAR::raiseError($res->getMessage(), $res->getCode());
- }
-
- if (!is_array($res)) {
- $this->activeUser = '';
- return false;
- }
-
- // Perform trimming here before the hashihg
- $password = trim($password, "\r\n");
- $res[$this->options['passwordcol']] = trim($res[$this->options['passwordcol']], "\r\n");
-
- // If using Challenge Response md5 the pass with the secret
- if ($isChallengeResponse) {
- $res[$this->options['passwordcol']] = md5($res[$this->options['passwordcol']]
- .$this->_auth_obj->session['loginchallenege']);
-
- // UGLY cannot avoid without modifying verifyPassword
- if ($this->options['cryptType'] == 'md5') {
- $res[$this->options['passwordcol']] = md5($res[$this->options['passwordcol']]);
- }
-
- //print " Hashed Password [{$res[$this->options['passwordcol']]}]<br/>\n";
- }
-
- if ($this->verifyPassword($password,
- $res[$this->options['passwordcol']],
- $this->options['cryptType'])) {
- // Store additional field values in the session
- foreach ($res as $key => $value) {
- if ($key == $this->options['passwordcol'] ||
- $key == $this->options['usernamecol']) {
- continue;
- }
-
- $this->log('Storing additional field: '.$key, AUTH_LOG_DEBUG);
-
- // Use reference to the auth object if exists
- // This is because the auth session variable can change so a
- // static call to setAuthData does not make sence
- $this->_auth_obj->setAuthData($key, $value);
- }
- return true;
- }
- $this->activeUser = $res[$this->options['usernamecol']];
- return false;
- }
-
- // }}}
- // {{{ listUsers()
-
- /**
- * Returns a list of users from the container
- *
- * @return mixed
- * @access public
- */
- function listUsers()
- {
- $this->log('Auth_Container_DB::listUsers() called.', AUTH_LOG_DEBUG);
- $err = $this->_prepare();
- if ($err !== true) {
- return PEAR::raiseError($err->getMessage(), $err->getCode());
- }
-
- $retVal = array();
-
- // Find if db_fields contains a *, if so assume all col are selected
- if ( is_string($this->options['db_fields'])
- && strstr($this->options['db_fields'], '*')) {
- $sql_from = "*";
- } else {
- $sql_from = $this->options['final_usernamecol'].
- ", ".$this->options['final_passwordcol'];
-
- if (strlen($fields = $this->_quoteDBFields()) > 0) {
- $sql_from .= ', '.$fields;
- }
- }
-
- $query = sprintf("SELECT %s FROM %s",
- $sql_from,
- $this->options['final_table']
- );
-
- // check if there is an optional parameter db_where
- if ($this->options['db_where'] != '') {
- // there is one, so add it to the query
- $query .= " WHERE ".$this->options['db_where'];
- }
-
- $this->log('Running SQL against DB: '.$query, AUTH_LOG_DEBUG);
-
- $res = $this->db->getAll($query, null, DB_FETCHMODE_ASSOC);
-
- if (DB::isError($res)) {
- return PEAR::raiseError($res->getMessage(), $res->getCode());
- } else {
- foreach ($res as $user) {
- $user['username'] = $user[$this->options['usernamecol']];
- $retVal[] = $user;
- }
- }
- $this->log('Found '.count($retVal).' users.', AUTH_LOG_DEBUG);
- return $retVal;
- }
-
- // }}}
- // {{{ addUser()
-
- /**
- * Add user to the storage container
- *
- * @access public
- * @param string Username
- * @param string Password
- * @param mixed Additional information that are stored in the DB
- *
- * @return mixed True on success, otherwise error object
- */
- function addUser($username, $password, $additional = "")
- {
- $this->log('Auth_Container_DB::addUser() called.', AUTH_LOG_DEBUG);
- $err = $this->_prepare();
- if ($err !== true) {
- return PEAR::raiseError($err->getMessage(), $err->getCode());
- }
-
- if ( isset($this->options['cryptType'])
- && $this->options['cryptType'] == 'none') {
- $cryptFunction = 'strval';
- } elseif ( isset($this->options['cryptType'])
- && function_exists($this->options['cryptType'])) {
- $cryptFunction = $this->options['cryptType'];
- } else {
- $cryptFunction = 'md5';
- }
-
- $password = $cryptFunction($password);
-
- $additional_key = '';
- $additional_value = '';
-
- if (is_array($additional)) {
- foreach ($additional as $key => $value) {
- if ($this->options['auto_quote']) {
- $additional_key .= ', ' . $this->db->quoteIdentifier($key);
- } else {
- $additional_key .= ', ' . $key;
- }
- $additional_value .= ", " . $this->db->quoteSmart($value);
- }
- }
-
- $query = sprintf("INSERT INTO %s (%s, %s%s) VALUES (%s, %s%s)",
- $this->options['final_table'],
- $this->options['final_usernamecol'],
- $this->options['final_passwordcol'],
- $additional_key,
- $this->db->quoteSmart($username),
- $this->db->quoteSmart($password),
- $additional_value
- );
-
- $this->log('Running SQL against DB: '.$query, AUTH_LOG_DEBUG);
-
- $res = $this->query($query);
-
- if (DB::isError($res)) {
- return PEAR::raiseError($res->getMessage(), $res->getCode());
- } else {
- return true;
- }
- }
-
- // }}}
- // {{{ removeUser()
-
- /**
- * Remove user from the storage container
- *
- * @access public
- * @param string Username
- *
- * @return mixed True on success, otherwise error object
- */
- function removeUser($username)
- {
- $this->log('Auth_Container_DB::removeUser() called.', AUTH_LOG_DEBUG);
-
- $err = $this->_prepare();
- if ($err !== true) {
- return PEAR::raiseError($err->getMessage(), $err->getCode());
- }
-
- // check if there is an optional parameter db_where
- if ($this->options['db_where'] != '') {
- // there is one, so add it to the query
- $where = " AND ".$this->options['db_where'];
- } else {
- $where = '';
- }
-
- $query = sprintf("DELETE FROM %s WHERE %s = %s %s",
- $this->options['final_table'],
- $this->options['final_usernamecol'],
- $this->db->quoteSmart($username),
- $where
- );
-
- $this->log('Running SQL against DB: '.$query, AUTH_LOG_DEBUG);
-
- $res = $this->query($query);
-
- if (DB::isError($res)) {
- return PEAR::raiseError($res->getMessage(), $res->getCode());
- } else {
- return true;
- }
- }
-
- // }}}
- // {{{ changePassword()
-
- /**
- * Change password for user in the storage container
- *
- * @param string Username
- * @param string The new password (plain text)
- */
- function changePassword($username, $password)
- {
- $this->log('Auth_Container_DB::changePassword() called.', AUTH_LOG_DEBUG);
- $err = $this->_prepare();
- if ($err !== true) {
- return PEAR::raiseError($err->getMessage(), $err->getCode());
- }
-
- if ( isset($this->options['cryptType'])
- && $this->options['cryptType'] == 'none') {
- $cryptFunction = 'strval';
- } elseif ( isset($this->options['cryptType'])
- && function_exists($this->options['cryptType'])) {
- $cryptFunction = $this->options['cryptType'];
- } else {
- $cryptFunction = 'md5';
- }
-
- $password = $cryptFunction($password);
-
- // check if there is an optional parameter db_where
- if ($this->options['db_where'] != '') {
- // there is one, so add it to the query
- $where = " AND ".$this->options['db_where'];
- } else {
- $where = '';
- }
-
- $query = sprintf("UPDATE %s SET %s = %s WHERE %s = %s %s",
- $this->options['final_table'],
- $this->options['final_passwordcol'],
- $this->db->quoteSmart($password),
- $this->options['final_usernamecol'],
- $this->db->quoteSmart($username),
- $where
- );
-
- $this->log('Running SQL against DB: '.$query, AUTH_LOG_DEBUG);
-
- $res = $this->query($query);
-
- if (DB::isError($res)) {
- return PEAR::raiseError($res->getMessage(), $res->getCode());
- } else {
- return true;
- }
- }
-
- // }}}
- // {{{ supportsChallengeResponse()
-
- /**
- * Determine if this container supports
- * password authentication with challenge response
- *
- * @return bool
- * @access public
- */
- function supportsChallengeResponse()
- {
- return in_array($this->options['cryptType'], array('md5', 'none', ''));
- }
-
- // }}}
- // {{{ getCryptType()
-
- /**
- * Returns the selected crypt type for this container
- */
- function getCryptType()
- {
- return($this->options['cryptType']);
- }
-
- // }}}
-
-}
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */
-
-/**
- * Reduced storage driver for use against PEAR DB
- *
- * PHP versions 4 and 5
- *
- * LICENSE: This source file is subject to version 3.01 of the PHP license
- * that is available through the world-wide-web at the following URI:
- * http://www.php.net/license/3_01.txt. If you did not receive a copy of
- * the PHP License and are unable to obtain it through the web, please
- * send a note to license@php.net so we can mail you a copy immediately.
- *
- * @category Authentication
- * @package Auth
- * @author Martin Jansen <mj@php.net>
- * @author Adam Ashley <aashley@php.net>
- * @copyright 2001-2006 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version CVS: $Id: DBLite.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- * @link http://pear.php.net/package/Auth
- * @since File available since Release 1.3.0
- */
-
-/**
- * Include Auth_Container base class
- */
-require_once 'Auth/Container.php';
-/**
- * Include PEAR DB package
- */
-require_once 'DB.php';
-
-/**
- * A lighter storage driver for fetching login data from a database
- *
- * This driver is derived from the DB storage container but
- * with the user manipulation function removed for smaller file size
- * by the PEAR DB abstraction layer to fetch login data.
- *
- * @category Authentication
- * @package Auth
- * @author Martin Jansen <mj@php.net>
- * @author Adam Ashley <aashley@php.net>
- * @copyright 2001-2006 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version Release: 1.5.4 File: $Revision: 1.1.1.1 $
- * @link http://pear.php.net/package/Auth
- * @since Class available since Release 1.3.0
- */
-class Auth_Container_DBLite extends Auth_Container
-{
-
- // {{{ properties
-
- /**
- * Additional options for the storage container
- * @var array
- */
- var $options = array();
-
- /**
- * DB object
- * @var object
- */
- var $db = null;
- var $dsn = '';
-
- /**
- * User that is currently selected from the DB.
- * @var string
- */
- var $activeUser = '';
-
- // }}}
- // {{{ Auth_Container_DBLite() [constructor]
-
- /**
- * Constructor of the container class
- *
- * Initate connection to the database via PEAR::DB
- *
- * @param string Connection data or DB object
- * @return object Returns an error object if something went wrong
- */
- function Auth_Container_DBLite($dsn)
- {
- $this->options['table'] = 'auth';
- $this->options['usernamecol'] = 'username';
- $this->options['passwordcol'] = 'password';
- $this->options['dsn'] = '';
- $this->options['db_fields'] = '';
- $this->options['cryptType'] = 'md5';
- $this->options['db_options'] = array();
- $this->options['db_where'] = '';
- $this->options['auto_quote'] = true;
-
- if (is_array($dsn)) {
- $this->_parseOptions($dsn);
- if (empty($this->options['dsn'])) {
- PEAR::raiseError('No connection parameters specified!');
- }
- } else {
- $this->options['dsn'] = $dsn;
- }
- }
-
- // }}}
- // {{{ _connect()
-
- /**
- * Connect to database by using the given DSN string
- *
- * @access private
- * @param string DSN string
- * @return mixed Object on error, otherwise bool
- */
- function _connect(&$dsn)
- {
- $this->log('Auth_Container_DBLite::_connect() called.', AUTH_LOG_DEBUG);
- if (is_string($dsn) || is_array($dsn)) {
- $this->db =& DB::connect($dsn, $this->options['db_options']);
- } elseif (is_subclass_of($dsn, "db_common")) {
- $this->db =& $dsn;
- } else {
- return PEAR::raiseError("Invalid dsn or db object given");
- }
-
- if (DB::isError($this->db) || PEAR::isError($this->db)) {
- return PEAR::raiseError($this->db->getMessage(), $this->db->getCode());
- } else {
- return true;
- }
- }
-
- // }}}
- // {{{ _prepare()
-
- /**
- * Prepare database connection
- *
- * This function checks if we have already opened a connection to
- * the database. If that's not the case, a new connection is opened.
- *
- * @access private
- * @return mixed True or a DB error object.
- */
- function _prepare()
- {
- if (!DB::isConnection($this->db)) {
- $res = $this->_connect($this->options['dsn']);
- if (DB::isError($res) || PEAR::isError($res)) {
- return $res;
- }
- }
- if ($this->options['auto_quote'] && $this->db->dsn['phptype'] != 'sqlite') {
- $this->options['final_table'] = $this->db->quoteIdentifier($this->options['table']);
- $this->options['final_usernamecol'] = $this->db->quoteIdentifier($this->options['usernamecol']);
- $this->options['final_passwordcol'] = $this->db->quoteIdentifier($this->options['passwordcol']);
- } else {
- $this->options['final_table'] = $this->options['table'];
- $this->options['final_usernamecol'] = $this->options['usernamecol'];
- $this->options['final_passwordcol'] = $this->options['passwordcol'];
- }
- return true;
- }
-
- // }}}
- // {{{ _parseOptions()
-
- /**
- * Parse options passed to the container class
- *
- * @access private
- * @param array
- */
- function _parseOptions($array)
- {
- foreach ($array as $key => $value) {
- if (isset($this->options[$key])) {
- $this->options[$key] = $value;
- }
- }
- }
-
- // }}}
- // {{{ _quoteDBFields()
-
- /**
- * Quote the db_fields option to avoid the possibility of SQL injection.
- *
- * @access private
- * @return string A properly quoted string that can be concatenated into a
- * SELECT clause.
- */
- function _quoteDBFields()
- {
- if (isset($this->options['db_fields'])) {
- if (is_array($this->options['db_fields'])) {
- if ($this->options['auto_quote']) {
- $fields = array();
- foreach ($this->options['db_fields'] as $field) {
- $fields[] = $this->db->quoteIdentifier($field);
- }
- return implode(', ', $fields);
- } else {
- return implode(', ', $this->options['db_fields']);
- }
- } else {
- if (strlen($this->options['db_fields']) > 0) {
- if ($this->options['auto_quote']) {
- return $this->db->quoteIdentifier($this->options['db_fields']);
- } else {
- $this->options['db_fields'];
- }
- }
- }
- }
-
- return '';
- }
-
- // }}}
- // {{{ fetchData()
-
- /**
- * Get user information from database
- *
- * This function uses the given username to fetch
- * the corresponding login data from the database
- * table. If an account that matches the passed username
- * and password is found, the function returns true.
- * Otherwise it returns false.
- *
- * @param string Username
- * @param string Password
- * @return mixed Error object or boolean
- */
- function fetchData($username, $password)
- {
- $this->log('Auth_Container_DBLite::fetchData() called.', AUTH_LOG_DEBUG);
- // Prepare for a database query
- $err = $this->_prepare();
- if ($err !== true) {
- return PEAR::raiseError($err->getMessage(), $err->getCode());
- }
-
- // Find if db_fields contains a *, if so assume all col are selected
- if (is_string($this->options['db_fields'])
- && strstr($this->options['db_fields'], '*')) {
- $sql_from = "*";
- } else {
- $sql_from = $this->options['final_usernamecol'].
- ", ".$this->options['final_passwordcol'];
-
- if (strlen($fields = $this->_quoteDBFields()) > 0) {
- $sql_from .= ', '.$fields;
- }
- }
-
- $query = "SELECT ".$sql_from.
- " FROM ".$this->options['final_table'].
- " WHERE ".$this->options['final_usernamecol']." = ".$this->db->quoteSmart($username);
-
- // check if there is an optional parameter db_where
- if ($this->options['db_where'] != '') {
- // there is one, so add it to the query
- $query .= " AND ".$this->options['db_where'];
- }
-
- $this->log('Running SQL against DB: '.$query, AUTH_LOG_DEBUG);
-
- $res = $this->db->getRow($query, null, DB_FETCHMODE_ASSOC);
-
- if (DB::isError($res)) {
- return PEAR::raiseError($res->getMessage(), $res->getCode());
- }
- if (!is_array($res)) {
- $this->activeUser = '';
- return false;
- }
- if ($this->verifyPassword(trim($password, "\r\n"),
- trim($res[$this->options['passwordcol']], "\r\n"),
- $this->options['cryptType'])) {
- // Store additional field values in the session
- foreach ($res as $key => $value) {
- if ($key == $this->options['passwordcol'] ||
- $key == $this->options['usernamecol']) {
- continue;
- }
-
- $this->log('Storing additional field: '.$key, AUTH_LOG_DEBUG);
-
- // Use reference to the auth object if exists
- // This is because the auth session variable can change so a static call to setAuthData does not make sence
- if (is_object($this->_auth_obj)) {
- $this->_auth_obj->setAuthData($key, $value);
- } else {
- Auth::setAuthData($key, $value);
- }
- }
- $this->activeUser = $res[$this->options['usernamecol']];
- return true;
- }
- $this->activeUser = $res[$this->options['usernamecol']];
- return false;
- }
-
- // }}}
-
-}
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */
-
-/**
- * Storage driver for use against a generic password file
- *
- * PHP versions 4 and 5
- *
- * LICENSE: This source file is subject to version 3.01 of the PHP license
- * that is available through the world-wide-web at the following URI:
- * http://www.php.net/license/3_01.txt. If you did not receive a copy of
- * the PHP License and are unable to obtain it through the web, please
- * send a note to license@php.net so we can mail you a copy immediately.
- *
- * @category Authentication
- * @package Auth
- * @author Stefan Ekman <stekman@sedata.org>
- * @author Martin Jansen <mj@php.net>
- * @author Mika Tuupola <tuupola@appelsiini.net>
- * @author Michael Wallner <mike@php.net>
- * @author Adam Ashley <aashley@php.net>
- * @copyright 2001-2006 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version CVS: $Id: File.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- * @link http://pear.php.net/package/Auth
- */
-
-/**
- * Include PEAR File_Passwd package
- */
-require_once "File/Passwd.php";
-/**
- * Include Auth_Container base class
- */
-require_once "Auth/Container.php";
-/**
- * Include PEAR package for error handling
- */
-require_once "PEAR.php";
-
-/**
- * Storage driver for fetching login data from an encrypted password file.
- *
- * This storage container can handle CVS pserver style passwd files.
- *
- * @category Authentication
- * @package Auth
- * @author Stefan Ekman <stekman@sedata.org>
- * @author Martin Jansen <mj@php.net>
- * @author Mika Tuupola <tuupola@appelsiini.net>
- * @author Michael Wallner <mike@php.net>
- * @author Adam Ashley <aashley@php.net>
- * @copyright 2001-2006 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version Release: 1.5.4 File: $Revision: 1.1.1.1 $
- * @link http://pear.php.net/package/Auth
- */
-class Auth_Container_File extends Auth_Container
-{
-
- // {{{ properties
-
- /**
- * Path to passwd file
- *
- * @var string
- */
- var $pwfile = '';
-
- /**
- * Options for container
- *
- * @var array
- */
- var $options = array();
-
- // }}}
- // {{{ Auth_Container_File() [constructor]
-
- /**
- * Constructor of the container class
- *
- * @param string $filename path to passwd file
- * @return object Auth_Container_File new Auth_Container_File object
- */
- function Auth_Container_File($filename) {
- $this->_setDefaults();
-
- // Only file is a valid option here
- if(is_array($filename)) {
- $this->pwfile = $filename['file'];
- $this->_parseOptions($filename);
- } else {
- $this->pwfile = $filename;
- }
- }
-
- // }}}
- // {{{ fetchData()
-
- /**
- * Authenticate an user
- *
- * @param string username
- * @param string password
- * @return mixed boolean|PEAR_Error
- */
- function fetchData($user, $pass)
- {
- $this->log('Auth_Container_File::fetchData() called.', AUTH_LOG_DEBUG);
- return File_Passwd::staticAuth($this->options['type'], $this->pwfile, $user, $pass);
- }
-
- // }}}
- // {{{ listUsers()
-
- /**
- * List all available users
- *
- * @return array
- */
- function listUsers()
- {
- $this->log('Auth_Container_File::listUsers() called.', AUTH_LOG_DEBUG);
-
- $pw_obj = &$this->_load();
- if (PEAR::isError($pw_obj)) {
- return array();
- }
-
- $users = $pw_obj->listUser();
- if (!is_array($users)) {
- return array();
- }
-
- foreach ($users as $key => $value) {
- $retVal[] = array("username" => $key,
- "password" => $value['passwd'],
- "cvsuser" => $value['system']);
- }
-
- $this->log('Found '.count($retVal).' users.', AUTH_LOG_DEBUG);
-
- return $retVal;
- }
-
- // }}}
- // {{{ addUser()
-
- /**
- * Add a new user to the storage container
- *
- * @param string username
- * @param string password
- * @param mixed Additional parameters to File_Password_*::addUser()
- *
- * @return boolean
- */
- function addUser($user, $pass, $additional='')
- {
- $this->log('Auth_Container_File::addUser() called.', AUTH_LOG_DEBUG);
- $params = array($user, $pass);
- if (is_array($additional)) {
- foreach ($additional as $item) {
- $params[] = $item;
- }
- } else {
- $params[] = $additional;
- }
-
- $pw_obj = &$this->_load();
- if (PEAR::isError($pw_obj)) {
- return false;
- }
-
- $res = call_user_func_array(array(&$pw_obj, 'addUser'), $params);
- if (PEAR::isError($res)) {
- return false;
- }
-
- $res = $pw_obj->save();
- if (PEAR::isError($res)) {
- return false;
- }
-
- return true;
- }
-
- // }}}
- // {{{ removeUser()
-
- /**
- * Remove user from the storage container
- *
- * @param string Username
- * @return boolean
- */
- function removeUser($user)
- {
- $this->log('Auth_Container_File::removeUser() called.', AUTH_LOG_DEBUG);
- $pw_obj = &$this->_load();
- if (PEAR::isError($pw_obj)) {
- return false;
- }
-
- $res = $pw_obj->delUser($user);
- if (PEAR::isError($res)) {
- return false;
- }
-
- $res = $pw_obj->save();
- if (PEAR::isError($res)) {
- return false;
- }
-
- return true;
- }
-
- // }}}
- // {{{ changePassword()
-
- /**
- * Change password for user in the storage container
- *
- * @param string Username
- * @param string The new password
- */
- function changePassword($username, $password)
- {
- $this->log('Auth_Container_File::changePassword() called.', AUTH_LOG_DEBUG);
- $pw_obj = &$this->_load();
- if (PEAR::isError($pw_obj)) {
- return false;
- }
-
- $res = $pw_obj->changePasswd($username, $password);
- if (PEAR::isError($res)) {
- return false;
- }
-
- $res = $pw_obj->save();
- if (PEAR::isError($res)) {
- return false;
- }
-
- return true;
- }
-
- // }}}
- // {{{ _load()
-
- /**
- * Load and initialize the File_Passwd object
- *
- * @return object File_Passwd_Cvs|PEAR_Error
- */
- function &_load()
- {
- static $pw_obj;
-
- if (!isset($pw_obj)) {
- $this->log('Instanciating File_Password object of type '.$this->options['type'], AUTH_LOG_DEBUG);
- $pw_obj = File_Passwd::factory($this->options['type']);
- if (PEAR::isError($pw_obj)) {
- return $pw_obj;
- }
-
- $pw_obj->setFile($this->pwfile);
-
- $res = $pw_obj->load();
- if (PEAR::isError($res)) {
- return $res;
- }
- }
-
- return $pw_obj;
- }
-
- // }}}
- // {{{ _setDefaults()
-
- /**
- * Set some default options
- *
- * @access private
- * @return void
- */
- function _setDefaults()
- {
- $this->options['type'] = 'Cvs';
- }
-
- // }}}
- // {{{ _parseOptions()
-
- /**
- * Parse options passed to the container class
- *
- * @access private
- * @param array
- */
- function _parseOptions($array)
- {
- foreach ($array as $key => $value) {
- if (isset($this->options[$key])) {
- $this->options[$key] = $value;
- }
- }
- }
-
- // }}}
-
-}
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */
-
-/**
- * Storage driver for use against IMAP servers
- *
- * PHP versions 4 and 5
- *
- * LICENSE: This source file is subject to version 3.01 of the PHP license
- * that is available through the world-wide-web at the following URI:
- * http://www.php.net/license/3_01.txt. If you did not receive a copy of
- * the PHP License and are unable to obtain it through the web, please
- * send a note to license@php.net so we can mail you a copy immediately.
- *
- * @category Authentication
- * @package Auth
- * @author Jeroen Houben <jeroen@terena.nl>
- * @author Adam Ashley <aashley@php.net>
- * @copyright 2001-2006 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version CVS: $Id: IMAP.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- * @link http://pear.php.net/package/Auth
- * @since File available since Release 1.2.0
- */
-
-/**
- * Include Auth_Container base class
- */
-require_once "Auth/Container.php";
-
-/**
- * Include PEAR class for error handling
- */
-require_once "PEAR.php";
-
-/**
- * Storage driver for fetching login data from an IMAP server
- *
- * This class is based on LDAP containers, but it very simple.
- * By default it connects to localhost:143
- * The constructor will first check if the host:port combination is
- * actually reachable. This behaviour can be disabled.
- * It then tries to create an IMAP stream (without opening a mailbox)
- * If you wish to pass extended options to the connections, you may
- * do so by specifying protocol options.
- *
- * To use this storage containers, you have to use the
- * following syntax:
- *
- * <?php
- * ...
- * $params = array(
- * 'host' => 'mail.example.com',
- * 'port' => 143,
- * );
- * $myAuth = new Auth('IMAP', $params);
- * ...
- *
- * By default we connect without any protocol options set. However, some
- * servers require you to connect with the notls or norsh options set.
- * To do this you need to add the following value to the params array:
- * 'baseDSN' => '/imap/notls/norsh'
- *
- * To connect to an SSL IMAP server:
- * 'baseDSN' => '/imap/ssl'
- *
- * To connect to an SSL IMAP server with a self-signed certificate:
- * 'baseDSN' => '/imap/ssl/novalidate-cert'
- *
- * Further options may be available and can be found on the php site at
- * http://www.php.net/manual/function.imap-open.php
- *
- * @category Authentication
- * @package Auth
- * @author Jeroen Houben <jeroen@terena.nl>
- * @author Cipriano Groenendal <cipri@campai.nl>
- * @author Adam Ashley <aashley@php.net>
- * @copyright 2001-2006 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version Release: 1.5.4 File: $Revision: 1.1.1.1 $
- * @link http://pear.php.net/package/Auth
- * @since Class available since Release 1.2.0
- */
-class Auth_Container_IMAP extends Auth_Container
-{
-
- // {{{ properties
-
- /**
- * Options for the class
- * @var array
- */
- var $options = array();
-
- // }}}
- // {{{ Auth_Container_IMAP() [constructor]
-
- /**
- * Constructor of the container class
- *
- * @param $params associative array with host, port, baseDSN, checkServer
- * and userattr key
- * @return object Returns an error object if something went wrong
- * @todo Use PEAR Net_IMAP if IMAP extension not loaded
- */
- function Auth_Container_IMAP($params)
- {
- if (!extension_loaded('imap')) {
- return PEAR::raiseError('Cannot use IMAP authentication, '
- .'IMAP extension not loaded!', 41, PEAR_ERROR_DIE);
- }
- $this->_setDefaults();
-
- // set parameters (if any)
- if (is_array($params)) {
- $this->_parseOptions($params);
- }
-
- if ($this->options['checkServer']) {
- $this->_checkServer($this->options['timeout']);
- }
- return true;
- }
-
- // }}}
- // {{{ _setDefaults()
-
- /**
- * Set some default options
- *
- * @access private
- */
- function _setDefaults()
- {
- $this->options['host'] = 'localhost';
- $this->options['port'] = 143;
- $this->options['baseDSN'] = '';
- $this->options['checkServer'] = true;
- $this->options['timeout'] = 20;
- }
-
- // }}}
- // {{{ _checkServer()
-
- /**
- * Check if the given server and port are reachable
- *
- * @access private
- */
- function _checkServer() {
- $this->log('Auth_Container_IMAP::_checkServer() called.', AUTH_LOG_DEBUG);
- $fp = @fsockopen ($this->options['host'], $this->options['port'],
- $errno, $errstr, $this->options['timeout']);
- if (is_resource($fp)) {
- @fclose($fp);
- } else {
- $message = "Error connecting to IMAP server "
- . $this->options['host']
- . ":" . $this->options['port'];
- return PEAR::raiseError($message, 41);
- }
- }
-
- // }}}
- // {{{ _parseOptions()
-
- /**
- * Parse options passed to the container class
- *
- * @access private
- * @param array
- */
- function _parseOptions($array)
- {
- foreach ($array as $key => $value) {
- $this->options[$key] = $value;
- }
- }
-
- // }}}
- // {{{ fetchData()
-
- /**
- * Try to open a IMAP stream using $username / $password
- *
- * @param string Username
- * @param string Password
- * @return boolean
- */
- function fetchData($username, $password)
- {
- $this->log('Auth_Container_IMAP::fetchData() called.', AUTH_LOG_DEBUG);
- $dsn = '{'.$this->options['host'].':'.$this->options['port'].$this->options['baseDSN'].'}';
- $conn = @imap_open ($dsn, $username, $password, OP_HALFOPEN);
- if (is_resource($conn)) {
- $this->log('Successfully connected to IMAP server.', AUTH_LOG_DEBUG);
- $this->activeUser = $username;
- @imap_close($conn);
- return true;
- } else {
- $this->log('Connection to IMAP server failed.', AUTH_LOG_DEBUG);
- $this->activeUser = '';
- return false;
- }
- }
-
- // }}}
-
-}
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */
-
-/**
- * Storage driver for Authentication on a Kerberos V server.
- *
- * PHP versions 4 and 5
- *
- * LICENSE: This source file is subject to version 3.01 of the PHP license
- * that is available through the world-wide-web at the following URI:
- * http://www.php.net/license/3_01.txt. If you did not receive a copy of
- * the PHP License and are unable to obtain it through the web, please
- * send a note to license@php.net so we can mail you a copy immediately.
- *
- * @category Authentication
- * @package Auth
- * @author Andrew Teixeira <ateixeira@gmail.com>
- * @author Adam Ashley <aashley@php.net>
- * @copyright 2001-2006 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version CVS: $Id: KADM5.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- * @link http://pear.php.net/package/Auth
- * @since File available since Release 1.4.0
- */
-
-/**
- * Include Auth_Container base class
- */
-require_once 'Auth/Container.php';
-/**
- * Include PEAR for error handling
- */
-require_once 'PEAR.php';
-
-/**
- * Storage driver for Authentication on a Kerberos V server.
- *
- * Available options:
- * hostname: The hostname of the kerberos server
- * realm: The Kerberos V realm
- * timeout: The timeout for checking the server
- * checkServer: Set to true to check if the server is running when
- * constructing the object
- *
- * @category Authentication
- * @package Auth
- * @author Andrew Teixeira <ateixeira@gmail.com>
- * @author Adam Ashley <aashley@php.net>
- * @copyright 2001-2006 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version Release: 1.5.4 File: $Revision: 1.1.1.1 $
- * @link http://pear.php.net/package/Auth
- * @since Class available since Release 1.4.0
- */
-class Auth_Container_KADM5 extends Auth_Container {
-
- // {{{ properties
-
- /**
- * Options for the class
- * @var string
- */
- var $options = array();
-
- // }}}
- // {{{ Auth_Container_KADM5()
-
- /**
- * Constructor of the container class
- *
- * $options can have these keys:
- * 'hostname' The hostname of the kerberos server
- * 'realm' The Kerberos V realm
- * 'timeout' The timeout for checking the server
- * 'checkServer' Set to true to check if the server is running when
- * constructing the object
- *
- * @param $options associative array
- * @return object Returns an error object if something went wrong
- */
- function Auth_Container_KADM5($options) {
- if (!extension_loaded('kadm5')) {
- return PEAR::raiseError("Cannot use Kerberos V authentication, KADM5 extension not loaded!", 41, PEAR_ERROR_DIE);
- }
-
- $this->_setDefaults();
-
- if (isset($options['hostname'])) {
- $this->options['hostname'] = $options['hostname'];
- }
- if (isset($options['realm'])) {
- $this->options['realm'] = $options['realm'];
- }
- if (isset($options['timeout'])) {
- $this->options['timeout'] = $options['timeout'];
- }
- if (isset($options['checkServer'])) {
- $this->options['checkServer'] = $options['checkServer'];
- }
-
- if ($this->options['checkServer']) {
- $this->_checkServer();
- }
- }
-
- // }}}
- // {{{ fetchData()
-
- /**
- * Try to login to the KADM5 server
- *
- * @param string Username
- * @param string Password
- * @return boolean
- */
- function fetchData($username, $password) {
- $this->log('Auth_Container_KADM5::fetchData() called.', AUTH_LOG_DEBUG);
- if ( ($username == NULL) || ($password == NULL) ) {
- return false;
- }
-
- $server = $this->options['hostname'];
- $realm = $this->options['realm'];
- $check = @kadm5_init_with_password($server, $realm, $username, $password);
-
- if ($check == false) {
- return false;
- } else {
- return true;
- }
- }
-
- // }}}
- // {{{ _setDefaults()
-
- /**
- * Set some default options
- *
- * @access private
- */
- function _setDefaults() {
- $this->options['hostname'] = 'localhost';
- $this->options['realm'] = NULL;
- $this->options['timeout'] = 10;
- $this->options['checkServer'] = false;
- }
-
- // }}}
- // {{{ _checkServer()
-
- /**
- * Check if the given server and port are reachable
- *
- * @access private
- */
- function _checkServer() {
- $fp = @fsockopen ($this->options['hostname'], 88, $errno, $errstr, $this->options['timeout']);
- if (is_resource($fp)) {
- @fclose($fp);
- } else {
- $message = "Error connecting to Kerberos V server "
- .$this->options['hostname'].":".$this->options['port'];
- return PEAR::raiseError($message, 41, PEAR_ERROR_DIE);
- }
- }
-
- // }}}
-
-}
-
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */
-
-/**
- * Storage driver for use against an LDAP server
- *
- * PHP versions 4 and 5
- *
- * LICENSE: This source file is subject to version 3.01 of the PHP license
- * that is available through the world-wide-web at the following URI:
- * http://www.php.net/license/3_01.txt. If you did not receive a copy of
- * the PHP License and are unable to obtain it through the web, please
- * send a note to license@php.net so we can mail you a copy immediately.
- *
- * @category Authentication
- * @package Auth
- * @author Jan Wagner <wagner@netsols.de>
- * @author Adam Ashley <aashley@php.net>
- * @author Hugues Peeters <hugues.peeters@claroline.net>
- * @copyright 2001-2006 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version CVS: $Id: LDAP.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- * @link http://pear.php.net/package/Auth
- */
-
-/**
- * Include Auth_Container base class
- */
-require_once "Auth/Container.php";
-/**
- * Include PEAR package for error handling
- */
-require_once "PEAR.php";
-
-/**
- * Storage driver for fetching login data from LDAP
- *
- * This class is heavily based on the DB and File containers. By default it
- * connects to localhost:389 and searches for uid=$username with the scope
- * "sub". If no search base is specified, it will try to determine it via
- * the namingContexts attribute. It takes its parameters in a hash, connects
- * to the ldap server, binds anonymously, searches for the user, and tries
- * to bind as the user with the supplied password. When a group was set, it
- * will look for group membership of the authenticated user. If all goes
- * well the authentication was successful.
- *
- * Parameters:
- *
- * host: localhost (default), ldap.netsols.de or 127.0.0.1
- * port: 389 (default) or 636 or whereever your server runs
- * url: ldap://localhost:389/
- * useful for ldaps://, works only with openldap2 ?
- * it will be preferred over host and port
- * version: LDAP version to use, ususally 2 (default) or 3,
- * must be an integer!
- * referrals: If set, determines whether the LDAP library automatically
- * follows referrals returned by LDAP servers or not. Possible
- * values are true (default) or false.
- * binddn: If set, searching for user will be done after binding
- * as this user, if not set the bind will be anonymous.
- * This is reported to make the container work with MS
- * Active Directory, but should work with any server that
- * is configured this way.
- * This has to be a complete dn for now (basedn and
- * userdn will not be appended).
- * bindpw: The password to use for binding with binddn
- * basedn: the base dn of your server
- * userdn: gets prepended to basedn when searching for user
- * userscope: Scope for user searching: one, sub (default), or base
- * userattr: the user attribute to search for (default: uid)
- * userfilter: filter that will be added to the search filter
- * this way: (&(userattr=username)(userfilter))
- * default: (objectClass=posixAccount)
- * attributes: array of additional attributes to fetch from entry.
- * these will added to auth data and can be retrieved via
- * Auth::getAuthData(). An empty array will fetch all attributes,
- * array('') will fetch no attributes at all (default)
- * If you add 'dn' as a value to this array, the users DN that was
- * used for binding will be added to auth data as well.
- * attrformat: The returned format of the additional data defined in the
- * 'attributes' option. Two formats are available.
- * LDAP returns data formatted in a
- * multidimensional array where each array starts with a
- * 'count' element providing the number of attributes in the
- * entry, or the number of values for attributes. When set
- * to this format, the only way to retrieve data from the
- * Auth object is by calling getAuthData('attributes').
- * AUTH returns data formatted in a
- * structure more compliant with other Auth Containers,
- * where each attribute element can be directly called by
- * getAuthData() method from Auth.
- * For compatibily with previous LDAP container versions,
- * the default format is LDAP.
- * groupdn: gets prepended to basedn when searching for group
- * groupattr: the group attribute to search for (default: cn)
- * groupfilter: filter that will be added to the search filter when
- * searching for a group:
- * (&(groupattr=group)(memberattr=username)(groupfilter))
- * default: (objectClass=groupOfUniqueNames)
- * memberattr : the attribute of the group object where the user dn
- * may be found (default: uniqueMember)
- * memberisdn: whether the memberattr is the dn of the user (default)
- * or the value of userattr (usually uid)
- * group: the name of group to search for
- * groupscope: Scope for group searching: one, sub (default), or base
- * start_tls: enable/disable the use of START_TLS encrypted connection
- * (default: false)
- * debug: Enable/Disable debugging output (default: false)
- * try_all: Whether to try all user accounts returned from the search
- * or just the first one. (default: false)
- *
- * To use this storage container, you have to use the following syntax:
- *
- * <?php
- * ...
- *
- * $a1 = new Auth("LDAP", array(
- * 'host' => 'localhost',
- * 'port' => '389',
- * 'version' => 3,
- * 'basedn' => 'o=netsols,c=de',
- * 'userattr' => 'uid'
- * 'binddn' => 'cn=admin,o=netsols,c=de',
- * 'bindpw' => 'password'));
- *
- * $a2 = new Auth('LDAP', array(
- * 'url' => 'ldaps://ldap.netsols.de',
- * 'basedn' => 'o=netsols,c=de',
- * 'userscope' => 'one',
- * 'userdn' => 'ou=People',
- * 'groupdn' => 'ou=Groups',
- * 'groupfilter' => '(objectClass=posixGroup)',
- * 'memberattr' => 'memberUid',
- * 'memberisdn' => false,
- * 'group' => 'admin'
- * ));
- *
- * $a3 = new Auth('LDAP', array(
- * 'host' => 'ldap.netsols.de',
- * 'port' => 389,
- * 'version' => 3,
- * 'referrals' => false,
- * 'basedn' => 'dc=netsols,dc=de',
- * 'binddn' => 'cn=Jan Wagner,cn=Users,dc=netsols,dc=de',
- * 'bindpw' => 'password',
- * 'userattr' => 'samAccountName',
- * 'userfilter' => '(objectClass=user)',
- * 'attributes' => array(''),
- * 'group' => 'testing',
- * 'groupattr' => 'samAccountName',
- * 'groupfilter' => '(objectClass=group)',
- * 'memberattr' => 'member',
- * 'memberisdn' => true,
- * 'groupdn' => 'cn=Users',
- * 'groupscope' => 'one',
- * 'debug' => true);
- *
- * The parameter values have to correspond
- * to the ones for your LDAP server of course.
- *
- * When talking to a Microsoft ActiveDirectory server you have to
- * use 'samaccountname' as the 'userattr' and follow special rules
- * to translate the ActiveDirectory directory names into 'basedn'.
- * The 'basedn' for the default 'Users' folder on an ActiveDirectory
- * server for the ActiveDirectory Domain (which is not related to
- * its DNS name) "win2000.example.org" would be:
- * "CN=Users, DC=win2000, DC=example, DC=org'
- * where every component of the domain name becomes a DC attribute
- * of its own. If you want to use a custom users folder you have to
- * replace "CN=Users" with a sequence of "OU" attributes that specify
- * the path to your custom folder in reverse order.
- * So the ActiveDirectory folder
- * "win2000.example.org\Custom\Accounts"
- * would become
- * "OU=Accounts, OU=Custom, DC=win2000, DC=example, DC=org'
- *
- * It seems that binding anonymously to an Active Directory
- * is not allowed, so you have to set binddn and bindpw for
- * user searching.
- *
- * LDAP Referrals need to be set to false for AD to work sometimes.
- *
- * Example a3 shows a full blown and tested example for connection to
- * Windows 2000 Active Directory with group mebership checking
- *
- * Note also that if you want an encrypted connection to an MS LDAP
- * server, then, on your webserver, you must specify
- * TLS_REQCERT never
- * in /etc/ldap/ldap.conf or in the webserver user's ~/.ldaprc (which
- * may or may not be read depending on your configuration).
- *
- *
- * @category Authentication
- * @package Auth
- * @author Jan Wagner <wagner@netsols.de>
- * @author Adam Ashley <aashley@php.net>
- * @author Hugues Peeters <hugues.peeters@claroline.net>
- * @copyright 2001-2006 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version Release: 1.5.4 File: $Revision: 1.1.1.1 $
- * @link http://pear.php.net/package/Auth
- */
-class Auth_Container_LDAP extends Auth_Container
-{
-
- // {{{ properties
-
- /**
- * Options for the class
- * @var array
- */
- var $options = array();
-
- /**
- * Connection ID of LDAP Link
- * @var string
- */
- var $conn_id = false;
-
- // }}}
-
- // {{{ Auth_Container_LDAP() [constructor]
-
- /**
- * Constructor of the container class
- *
- * @param $params, associative hash with host,port,basedn and userattr key
- * @return object Returns an error object if something went wrong
- */
- function Auth_Container_LDAP($params)
- {
- if (false === extension_loaded('ldap')) {
- return PEAR::raiseError('Auth_Container_LDAP: LDAP Extension not loaded',
- 41, PEAR_ERROR_DIE);
- }
-
- $this->_setDefaults();
-
- if (is_array($params)) {
- $this->_parseOptions($params);
- }
- }
-
- // }}}
- // {{{ _prepare()
-
- /**
- * Prepare LDAP connection
- *
- * This function checks if we have already opened a connection to
- * the LDAP server. If that's not the case, a new connection is opened.
- *
- * @access private
- * @return mixed True or a PEAR error object.
- */
- function _prepare()
- {
- if (!$this->_isValidLink()) {
- $res = $this->_connect();
- if (PEAR::isError($res)) {
- return $res;
- }
- }
- return true;
- }
-
- // }}}
- // {{{ _connect()
-
- /**
- * Connect to the LDAP server using the global options
- *
- * @access private
- * @return object Returns a PEAR error object if an error occurs.
- */
- function _connect()
- {
- $this->log('Auth_Container_LDAP::_connect() called.', AUTH_LOG_DEBUG);
- // connect
- if (isset($this->options['url']) && $this->options['url'] != '') {
- $this->log('Connecting with URL', AUTH_LOG_DEBUG);
- $conn_params = array($this->options['url']);
- } else {
- $this->log('Connecting with host:port', AUTH_LOG_DEBUG);
- $conn_params = array($this->options['host'], $this->options['port']);
- }
-
- if (($this->conn_id = @call_user_func_array('ldap_connect', $conn_params)) === false) {
- $this->log('Connection to server failed.', AUTH_LOG_DEBUG);
- $this->log('LDAP ERROR: '.ldap_errno($this->conn_id).': '.ldap_error($this->conn_id), AUTH_LOG_DEBUG);
- return PEAR::raiseError('Auth_Container_LDAP: Could not connect to server.', 41);
- }
- $this->log('Successfully connected to server', AUTH_LOG_DEBUG);
-
- // switch LDAP version
- if (is_numeric($this->options['version']) && $this->options['version'] > 2) {
- $this->log("Switching to LDAP version {$this->options['version']}", AUTH_LOG_DEBUG);
- @ldap_set_option($this->conn_id, LDAP_OPT_PROTOCOL_VERSION, $this->options['version']);
-
- // start TLS if available
- if (isset($this->options['start_tls']) && $this->options['start_tls']) {
- $this->log("Starting TLS session", AUTH_LOG_DEBUG);
- if (@ldap_start_tls($this->conn_id) === false) {
- $this->log('Could not start TLS session', AUTH_LOG_DEBUG);
- $this->log('LDAP ERROR: '.ldap_errno($this->conn_id).': '.ldap_error($this->conn_id), AUTH_LOG_DEBUG);
- return PEAR::raiseError('Auth_Container_LDAP: Could not start tls.', 41);
- }
- }
- }
-
- // switch LDAP referrals
- if (is_bool($this->options['referrals'])) {
- $this->log("Switching LDAP referrals to " . (($this->options['referrals']) ? 'true' : 'false'), AUTH_LOG_DEBUG);
- if (@ldap_set_option($this->conn_id, LDAP_OPT_REFERRALS, $this->options['referrals']) === false) {
- $this->log('Could not change LDAP referrals options', AUTH_LOG_DEBUG);
- $this->log('LDAP ERROR: '.ldap_errno($this->conn_id).': '.ldap_error($this->conn_id), AUTH_LOG_DEBUG);
- }
- }
-
- // bind with credentials or anonymously
- if (strlen($this->options['binddn']) && strlen($this->options['bindpw'])) {
- $this->log('Binding with credentials', AUTH_LOG_DEBUG);
- $bind_params = array($this->conn_id, $this->options['binddn'], $this->options['bindpw']);
- } else {
- $this->log('Binding anonymously', AUTH_LOG_DEBUG);
- $bind_params = array($this->conn_id);
- }
-
- // bind for searching
- if ((@call_user_func_array('ldap_bind', $bind_params)) === false) {
- $this->log('Bind failed', AUTH_LOG_DEBUG);
- $this->log('LDAP ERROR: '.ldap_errno($this->conn_id).': '.ldap_error($this->conn_id), AUTH_LOG_DEBUG);
- $this->_disconnect();
- return PEAR::raiseError("Auth_Container_LDAP: Could not bind to LDAP server.", 41);
- }
- $this->log('Binding was successful', AUTH_LOG_DEBUG);
-
- return true;
- }
-
- // }}}
- // {{{ _disconnect()
-
- /**
- * Disconnects (unbinds) from ldap server
- *
- * @access private
- */
- function _disconnect()
- {
- $this->log('Auth_Container_LDAP::_disconnect() called.', AUTH_LOG_DEBUG);
- if ($this->_isValidLink()) {
- $this->log('disconnecting from server');
- @ldap_unbind($this->conn_id);
- }
- }
-
- // }}}
- // {{{ _getBaseDN()
-
- /**
- * Tries to find Basedn via namingContext Attribute
- *
- * @access private
- */
- function _getBaseDN()
- {
- $this->log('Auth_Container_LDAP::_getBaseDN() called.', AUTH_LOG_DEBUG);
- $err = $this->_prepare();
- if ($err !== true) {
- return PEAR::raiseError($err->getMessage(), $err->getCode());
- }
-
- if ($this->options['basedn'] == "" && $this->_isValidLink()) {
- $this->log("basedn not set, searching via namingContexts.", AUTH_LOG_DEBUG);
-
- $result_id = @ldap_read($this->conn_id, "", "(objectclass=*)", array("namingContexts"));
-
- if (@ldap_count_entries($this->conn_id, $result_id) == 1) {
-
- $this->log("got result for namingContexts", AUTH_LOG_DEBUG);
-
- $entry_id = @ldap_first_entry($this->conn_id, $result_id);
- $attrs = @ldap_get_attributes($this->conn_id, $entry_id);
- $basedn = $attrs['namingContexts'][0];
-
- if ($basedn != "") {
- $this->log("result for namingContexts was $basedn", AUTH_LOG_DEBUG);
- $this->options['basedn'] = $basedn;
- }
- }
- @ldap_free_result($result_id);
- }
-
- // if base ist still not set, raise error
- if ($this->options['basedn'] == "") {
- return PEAR::raiseError("Auth_Container_LDAP: LDAP search base not specified!", 41);
- }
- return true;
- }
-
- // }}}
- // {{{ _isValidLink()
-
- /**
- * determines whether there is a valid ldap conenction or not
- *
- * @accessd private
- * @return boolean
- */
- function _isValidLink()
- {
- if (is_resource($this->conn_id)) {
- if (get_resource_type($this->conn_id) == 'ldap link') {
- return true;
- }
- }
- return false;
- }
-
- // }}}
- // {{{ _setDefaults()
-
- /**
- * Set some default options
- *
- * @access private
- */
- function _setDefaults()
- {
- $this->options['url'] = '';
- $this->options['host'] = 'localhost';
- $this->options['port'] = '389';
- $this->options['version'] = 2;
- $this->options['referrals'] = true;
- $this->options['binddn'] = '';
- $this->options['bindpw'] = '';
- $this->options['basedn'] = '';
- $this->options['userdn'] = '';
- $this->options['userscope'] = 'sub';
- $this->options['userattr'] = 'uid';
- $this->options['userfilter'] = '(objectClass=posixAccount)';
- $this->options['attributes'] = array(''); // no attributes
- $this->options['attrformat'] = 'AUTH'; // returns attribute like other Auth containers
- $this->options['group'] = '';
- $this->options['groupdn'] = '';
- $this->options['groupscope'] = 'sub';
- $this->options['groupattr'] = 'cn';
- $this->options['groupfilter'] = '(objectClass=groupOfUniqueNames)';
- $this->options['memberattr'] = 'uniqueMember';
- $this->options['memberisdn'] = true;
- $this->options['start_tls'] = false;
- $this->options['debug'] = false;
- $this->options['try_all'] = false; // Try all user ids returned not just the first one
- }
-
- // }}}
- // {{{ _parseOptions()
-
- /**
- * Parse options passed to the container class
- *
- * @access private
- * @param array
- */
- function _parseOptions($array)
- {
- $array = $this->_setV12OptionsToV13($array);
-
- foreach ($array as $key => $value) {
- if (array_key_exists($key, $this->options)) {
- if ($key == 'attributes') {
- if (is_array($value)) {
- $this->options[$key] = $value;
- } else {
- $this->options[$key] = explode(',', $value);
- }
- } else {
- $this->options[$key] = $value;
- }
- }
- }
- }
-
- // }}}
- // {{{ _setV12OptionsToV13()
-
- /**
- * Adapt deprecated options from Auth 1.2 LDAP to Auth 1.3 LDAP
- *
- * @author Hugues Peeters <hugues.peeters@claroline.net>
- * @access private
- * @param array
- * @return array
- */
- function _setV12OptionsToV13($array)
- {
- if (isset($array['useroc']))
- $array['userfilter'] = "(objectClass=".$array['useroc'].")";
- if (isset($array['groupoc']))
- $array['groupfilter'] = "(objectClass=".$array['groupoc'].")";
- if (isset($array['scope']))
- $array['userscope'] = $array['scope'];
-
- return $array;
- }
-
- // }}}
- // {{{ _scope2function()
-
- /**
- * Get search function for scope
- *
- * @param string scope
- * @return string ldap search function
- */
- function _scope2function($scope)
- {
- switch($scope) {
- case 'one':
- $function = 'ldap_list';
- break;
- case 'base':
- $function = 'ldap_read';
- break;
- default:
- $function = 'ldap_search';
- break;
- }
- return $function;
- }
-
- // }}}
- // {{{ fetchData()
-
- /**
- * Fetch data from LDAP server
- *
- * Searches the LDAP server for the given username/password
- * combination. Escapes all LDAP meta characters in username
- * before performing the query.
- *
- * @param string Username
- * @param string Password
- * @return boolean
- */
- function fetchData($username, $password)
- {
- $this->log('Auth_Container_LDAP::fetchData() called.', AUTH_LOG_DEBUG);
- $err = $this->_prepare();
- if ($err !== true) {
- return PEAR::raiseError($err->getMessage(), $err->getCode());
- }
-
- $err = $this->_getBaseDN();
- if ($err !== true) {
- return PEAR::raiseError($err->getMessage(), $err->getCode());
- }
-
- // UTF8 Encode username for LDAPv3
- if (@ldap_get_option($this->conn_id, LDAP_OPT_PROTOCOL_VERSION, $ver) && $ver == 3) {
- $this->log('UTF8 encoding username for LDAPv3', AUTH_LOG_DEBUG);
- $username = utf8_encode($username);
- }
-
- // make search filter
- $filter = sprintf('(&(%s=%s)%s)',
- $this->options['userattr'],
- $this->_quoteFilterString($username),
- $this->options['userfilter']);
-
- // make search base dn
- $search_basedn = $this->options['userdn'];
- if ($search_basedn != '' && substr($search_basedn, -1) != ',') {
- $search_basedn .= ',';
- }
- $search_basedn .= $this->options['basedn'];
-
- // attributes
- $searchAttributes = $this->options['attributes'];
-
- // make functions params array
- $func_params = array($this->conn_id, $search_basedn, $filter, $searchAttributes);
-
- // search function to use
- $func_name = $this->_scope2function($this->options['userscope']);
-
- $this->log("Searching with $func_name and filter $filter in $search_basedn", AUTH_LOG_DEBUG);
-
- // search
- if (($result_id = @call_user_func_array($func_name, $func_params)) === false) {
- $this->log('User not found', AUTH_LOG_DEBUG);
- } elseif (@ldap_count_entries($this->conn_id, $result_id) >= 1) { // did we get some possible results?
-
- $this->log('User(s) found', AUTH_LOG_DEBUG);
-
- $first = true;
- $entry_id = null;
-
- do {
-
- // then get the user dn
- if ($first) {
- $entry_id = @ldap_first_entry($this->conn_id, $result_id);
- $first = false;
- } else {
- $entry_id = @ldap_next_entry($this->conn_id, $entry_id);
- if ($entry_id === false)
- break;
- }
- $user_dn = @ldap_get_dn($this->conn_id, $entry_id);
-
- // as the dn is not fetched as an attribute, we save it anyway
- if (is_array($searchAttributes) && in_array('dn', $searchAttributes)) {
- $this->log('Saving DN to AuthData', AUTH_LOG_DEBUG);
- $this->_auth_obj->setAuthData('dn', $user_dn);
- }
-
- // fetch attributes
- if ($attributes = @ldap_get_attributes($this->conn_id, $entry_id)) {
-
- if (is_array($attributes) && isset($attributes['count']) &&
- $attributes['count'] > 0) {
-
- // ldap_get_attributes() returns a specific multi dimensional array
- // format containing all the attributes and where each array starts
- // with a 'count' element providing the number of attributes in the
- // entry, or the number of values for attribute. For compatibility
- // reasons, it remains the default format returned by LDAP container
- // setAuthData().
- // The code below optionally returns attributes in another format,
- // more compliant with other Auth containers, where each attribute
- // element are directly set in the 'authData' list. This option is
- // enabled by setting 'attrformat' to
- // 'AUTH' in the 'options' array.
- // eg. $this->options['attrformat'] = 'AUTH'
-
- if ( strtoupper($this->options['attrformat']) == 'AUTH' ) {
- $this->log('Saving attributes to Auth data in AUTH format', AUTH_LOG_DEBUG);
- unset ($attributes['count']);
- foreach ($attributes as $attributeName => $attributeValue ) {
- if (is_int($attributeName)) continue;
- if (is_array($attributeValue) && isset($attributeValue['count'])) {
- unset ($attributeValue['count']);
- }
- if (count($attributeValue)<=1) $attributeValue = $attributeValue[0];
- $this->log('Storing additional field: '.$attributeName, AUTH_LOG_DEBUG);
- $this->_auth_obj->setAuthData($attributeName, $attributeValue);
- }
- }
- else
- {
- $this->log('Saving attributes to Auth data in LDAP format', AUTH_LOG_DEBUG);
- $this->_auth_obj->setAuthData('attributes', $attributes);
- }
- }
- }
- @ldap_free_result($result_id);
-
- // need to catch an empty password as openldap seems to return TRUE
- // if anonymous binding is allowed
- if ($password != "") {
- $this->log("Bind as $user_dn", AUTH_LOG_DEBUG);
-
- // try binding as this user with the supplied password
- if (@ldap_bind($this->conn_id, $user_dn, $password)) {
- $this->log('Bind successful', AUTH_LOG_DEBUG);
-
- // check group if appropiate
- if (strlen($this->options['group'])) {
- // decide whether memberattr value is a dn or the username
- $this->log('Checking group membership', AUTH_LOG_DEBUG);
- $return = $this->checkGroup(($this->options['memberisdn']) ? $user_dn : $username);
- $this->_disconnect();
- return $return;
- } else {
- $this->log('Authenticated', AUTH_LOG_DEBUG);
- $this->_disconnect();
- return true; // user authenticated
- } // checkGroup
- } // bind
- } // non-empty password
- } while ($this->options['try_all'] == true); // interate through entries
- } // get results
- // default
- $this->log('NOT authenticated!', AUTH_LOG_DEBUG);
- $this->_disconnect();
- return false;
- }
-
- // }}}
- // {{{ checkGroup()
-
- /**
- * Validate group membership
- *
- * Searches the LDAP server for group membership of the
- * supplied username. Quotes all LDAP filter meta characters in
- * the user name before querying the LDAP server.
- *
- * @param string Distinguished Name of the authenticated User
- * @return boolean
- */
- function checkGroup($user)
- {
- $this->log('Auth_Container_LDAP::checkGroup() called.', AUTH_LOG_DEBUG);
- $err = $this->_prepare();
- if ($err !== true) {
- return PEAR::raiseError($err->getMessage(), $err->getCode());
- }
-
- // make filter
- $filter = sprintf('(&(%s=%s)(%s=%s)%s)',
- $this->options['groupattr'],
- $this->options['group'],
- $this->options['memberattr'],
- $this->_quoteFilterString($user),
- $this->options['groupfilter']);
-
- // make search base dn
- $search_basedn = $this->options['groupdn'];
- if ($search_basedn != '' && substr($search_basedn, -1) != ',') {
- $search_basedn .= ',';
- }
- $search_basedn .= $this->options['basedn'];
-
- $func_params = array($this->conn_id, $search_basedn, $filter,
- array($this->options['memberattr']));
- $func_name = $this->_scope2function($this->options['groupscope']);
-
- $this->log("Searching with $func_name and filter $filter in $search_basedn", AUTH_LOG_DEBUG);
-
- // search
- if (($result_id = @call_user_func_array($func_name, $func_params)) != false) {
- if (@ldap_count_entries($this->conn_id, $result_id) == 1) {
- @ldap_free_result($result_id);
- $this->log('User is member of group', AUTH_LOG_DEBUG);
- return true;
- }
- }
- // default
- $this->log('User is NOT member of group', AUTH_LOG_DEBUG);
- return false;
- }
-
- // }}}
- // {{{ _quoteFilterString()
-
- /**
- * Escapes LDAP filter special characters as defined in RFC 2254.
- *
- * @access private
- * @param string Filter String
- */
- function _quoteFilterString($filter_str)
- {
- $metas = array( '\\', '*', '(', ')', "\x00");
- $quoted_metas = array('\\\\', '\*', '\(', '\)', "\\\x00");
- return str_replace($metas, $quoted_metas, $filter_str);
- }
-
- // }}}
-
-}
-
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */
-
-/**
- * Storage driver for use against PEAR MDB
- *
- * PHP versions 4 and 5
- *
- * LICENSE: This source file is subject to version 3.01 of the PHP license
- * that is available through the world-wide-web at the following URI:
- * http://www.php.net/license/3_01.txt. If you did not receive a copy of
- * the PHP License and are unable to obtain it through the web, please
- * send a note to license@php.net so we can mail you a copy immediately.
- *
- * @category Authentication
- * @package Auth
- * @author Lorenzo Alberton <l.alberton@quipo.it>
- * @author Adam Ashley <aashley@php.net>
- * @copyright 2001-2006 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version CVS: $Id: MDB.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- * @link http://pear.php.net/package/Auth
- * @since File available since Release 1.2.3
- */
-
-/**
- * Include Auth_Container base class
- */
-require_once 'Auth/Container.php';
-/**
- * Include PEAR MDB package
- */
-require_once 'MDB.php';
-
-/**
- * Storage driver for fetching login data from a database
- *
- * This storage driver can use all databases which are supported
- * by the PEAR MDB abstraction layer to fetch login data.
- *
- * @category Authentication
- * @package Auth
- * @author Lorenzo Alberton <l.alberton@quipo.it>
- * @author Adam Ashley <aashley@php.net>
- * @copyright 2001-2006 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version Release: 1.5.4 File: $Revision: 1.1.1.1 $
- * @link http://pear.php.net/package/Auth
- * @since Class available since Release 1.2.3
- */
-class Auth_Container_MDB extends Auth_Container
-{
-
- // {{{ properties
-
- /**
- * Additional options for the storage container
- * @var array
- */
- var $options = array();
-
- /**
- * MDB object
- * @var object
- */
- var $db = null;
- var $dsn = '';
-
- /**
- * User that is currently selected from the DB.
- * @var string
- */
- var $activeUser = '';
-
- // }}}
- // {{{ Auth_Container_MDB() [constructor]
-
- /**
- * Constructor of the container class
- *
- * Initate connection to the database via PEAR::MDB
- *
- * @param string Connection data or MDB object
- * @return object Returns an error object if something went wrong
- */
- function Auth_Container_MDB($dsn)
- {
- $this->_setDefaults();
-
- if (is_array($dsn)) {
- $this->_parseOptions($dsn);
- if (empty($this->options['dsn'])) {
- PEAR::raiseError('No connection parameters specified!');
- }
- } else {
- $this->options['dsn'] = $dsn;
- }
- }
-
- // }}}
- // {{{ _connect()
-
- /**
- * Connect to database by using the given DSN string
- *
- * @access private
- * @param mixed DSN string | array | mdb object
- * @return mixed Object on error, otherwise bool
- */
- function _connect($dsn)
- {
- $this->log('Auth_Container_MDB::_connect() called.', AUTH_LOG_DEBUG);
- if (is_string($dsn) || is_array($dsn)) {
- $this->db =& MDB::connect($dsn, $this->options['db_options']);
- } elseif (is_subclass_of($dsn, 'mdb_common')) {
- $this->db = $dsn;
- } elseif (is_object($dsn) && MDB::isError($dsn)) {
- return PEAR::raiseError($dsn->getMessage(), $dsn->code);
- } else {
- return PEAR::raiseError('The given dsn was not valid in file ' . __FILE__ . ' at line ' . __LINE__,
- 41,
- PEAR_ERROR_RETURN,
- null,
- null
- );
-
- }
-
- if (MDB::isError($this->db) || PEAR::isError($this->db)) {
- return PEAR::raiseError($this->db->getMessage(), $this->db->code);
- }
-
- if ($this->options['auto_quote']) {
- $this->options['final_table'] = $this->db->quoteIdentifier($this->options['table']);
- $this->options['final_usernamecol'] = $this->db->quoteIdentifier($this->options['usernamecol']);
- $this->options['final_passwordcol'] = $this->db->quoteIdentifier($this->options['passwordcol']);
- } else {
- $this->options['final_table'] = $this->options['table'];
- $this->options['final_usernamecol'] = $this->options['usernamecol'];
- $this->options['final_passwordcol'] = $this->options['passwordcol'];
- }
-
- return true;
- }
-
- // }}}
- // {{{ _prepare()
-
- /**
- * Prepare database connection
- *
- * This function checks if we have already opened a connection to
- * the database. If that's not the case, a new connection is opened.
- *
- * @access private
- * @return mixed True or a MDB error object.
- */
- function _prepare()
- {
- if (is_subclass_of($this->db, 'mdb_common')) {
- return true;
- }
- return $this->_connect($this->options['dsn']);
- }
-
- // }}}
- // {{{ query()
-
- /**
- * Prepare query to the database
- *
- * This function checks if we have already opened a connection to
- * the database. If that's not the case, a new connection is opened.
- * After that the query is passed to the database.
- *
- * @access public
- * @param string Query string
- * @return mixed a MDB_result object or MDB_OK on success, a MDB
- * or PEAR error on failure
- */
- function query($query)
- {
- $this->log('Auth_Container_MDB::query() called.', AUTH_LOG_DEBUG);
- $err = $this->_prepare();
- if ($err !== true) {
- return $err;
- }
- return $this->db->query($query);
- }
-
- // }}}
- // {{{ _setDefaults()
-
- /**
- * Set some default options
- *
- * @access private
- * @return void
- */
- function _setDefaults()
- {
- $this->options['table'] = 'auth';
- $this->options['usernamecol'] = 'username';
- $this->options['passwordcol'] = 'password';
- $this->options['dsn'] = '';
- $this->options['db_fields'] = '';
- $this->options['cryptType'] = 'md5';
- $this->options['db_options'] = array();
- $this->options['db_where'] = '';
- $this->options['auto_quote'] = true;
- }
-
- // }}}
- // {{{ _parseOptions()
-
- /**
- * Parse options passed to the container class
- *
- * @access private
- * @param array
- */
- function _parseOptions($array)
- {
- foreach ($array as $key => $value) {
- if (isset($this->options[$key])) {
- $this->options[$key] = $value;
- }
- }
- }
-
- // }}}
- // {{{ _quoteDBFields()
-
- /**
- * Quote the db_fields option to avoid the possibility of SQL injection.
- *
- * @access private
- * @return string A properly quoted string that can be concatenated into a
- * SELECT clause.
- */
- function _quoteDBFields()
- {
- if (isset($this->options['db_fields'])) {
- if (is_array($this->options['db_fields'])) {
- if ($this->options['auto_quote']) {
- $fields = array();
- foreach ($this->options['db_fields'] as $field) {
- $fields[] = $this->db->quoteIdentifier($field);
- }
- return implode(', ', $fields);
- } else {
- return implode(', ', $this->options['db_fields']);
- }
- } else {
- if (strlen($this->options['db_fields']) > 0) {
- if ($this->options['auto_quote']) {
- return $this->db->quoteIdentifier($this->options['db_fields']);
- } else {
- return $this->options['db_fields'];
- }
- }
- }
- }
-
- return '';
- }
-
- // }}}
- // {{{ fetchData()
-
- /**
- * Get user information from database
- *
- * This function uses the given username to fetch
- * the corresponding login data from the database
- * table. If an account that matches the passed username
- * and password is found, the function returns true.
- * Otherwise it returns false.
- *
- * @param string Username
- * @param string Password
- * @param boolean If true password is secured using a md5 hash
- * the frontend and auth are responsible for making sure the container supports
- * challenge response password authentication
- * @return mixed Error object or boolean
- */
- function fetchData($username, $password, $isChallengeResponse=false)
- {
- $this->log('Auth_Container_MDB::fetchData() called.', AUTH_LOG_DEBUG);
- // Prepare for a database query
- $err = $this->_prepare();
- if ($err !== true) {
- return PEAR::raiseError($err->getMessage(), $err->getCode());
- }
-
- //Check if db_fields contains a *, if so assume all columns are selected
- if (is_string($this->options['db_fields'])
- && strstr($this->options['db_fields'], '*')) {
- $sql_from = '*';
- } else {
- $sql_from = $this->options['final_usernamecol'].
- ", ".$this->options['final_passwordcol'];
-
- if (strlen($fields = $this->_quoteDBFields()) > 0) {
- $sql_from .= ', '.$fields;
- }
- }
-
- $query = sprintf("SELECT %s FROM %s WHERE %s = %s",
- $sql_from,
- $this->options['final_table'],
- $this->options['final_usernamecol'],
- $this->db->getTextValue($username)
- );
-
- // check if there is an optional parameter db_where
- if ($this->options['db_where'] != '') {
- // there is one, so add it to the query
- $query .= " AND ".$this->options['db_where'];
- }
-
- $this->log('Running SQL against MDB: '.$query, AUTH_LOG_DEBUG);
-
- $res = $this->db->getRow($query, null, null, null, MDB_FETCHMODE_ASSOC);
-
- if (MDB::isError($res) || PEAR::isError($res)) {
- return PEAR::raiseError($res->getMessage(), $res->getCode());
- }
- if (!is_array($res)) {
- $this->activeUser = '';
- return false;
- }
-
- // Perform trimming here before the hashing
- $password = trim($password, "\r\n");
- $res[$this->options['passwordcol']] = trim($res[$this->options['passwordcol']], "\r\n");
-
- // If using Challenge Response md5 the pass with the secret
- if ($isChallengeResponse) {
- $res[$this->options['passwordcol']] =
- md5($res[$this->options['passwordcol']].$this->_auth_obj->session['loginchallenege']);
- // UGLY cannot avoid without modifying verifyPassword
- if ($this->options['cryptType'] == 'md5') {
- $res[$this->options['passwordcol']] = md5($res[$this->options['passwordcol']]);
- }
- }
-
- if ($this->verifyPassword($password,
- $res[$this->options['passwordcol']],
- $this->options['cryptType'])) {
- // Store additional field values in the session
- foreach ($res as $key => $value) {
- if ($key == $this->options['passwordcol'] ||
- $key == $this->options['usernamecol']) {
- continue;
- }
-
- $this->log('Storing additional field: '.$key, AUTH_LOG_DEBUG);
- // Use reference to the auth object if exists
- // This is because the auth session variable can change so a static
- // call to setAuthData does not make sense
- $this->_auth_obj->setAuthData($key, $value);
- }
- return true;
- }
-
- $this->activeUser = $res[$this->options['usernamecol']];
- return false;
- }
-
- // }}}
- // {{{ listUsers()
-
- /**
- * Returns a list of users from the container
- *
- * @return mixed array|PEAR_Error
- * @access public
- */
- function listUsers()
- {
- $this->log('Auth_Container_MDB::listUsers() called.', AUTH_LOG_DEBUG);
- $err = $this->_prepare();
- if ($err !== true) {
- return PEAR::raiseError($err->getMessage(), $err->getCode());
- }
-
- $retVal = array();
-
- //Check if db_fields contains a *, if so assume all columns are selected
- if ( is_string($this->options['db_fields'])
- && strstr($this->options['db_fields'], '*')) {
- $sql_from = '*';
- } else {
- $sql_from = $this->options['final_usernamecol']
- .', '.$this->options['final_passwordcol'];
-
- if (strlen($fields = $this->_quoteDBFields()) > 0) {
- $sql_from .= ', '.$fields;
- }
- }
-
- $query = sprintf('SELECT %s FROM %s',
- $sql_from,
- $this->options['final_table']
- );
-
- // check if there is an optional parameter db_where
- if ($this->options['db_where'] != '') {
- // there is one, so add it to the query
- $query .= " WHERE ".$this->options['db_where'];
- }
-
- $this->log('Running SQL against MDB: '.$query, AUTH_LOG_DEBUG);
-
- $res = $this->db->getAll($query, null, null, null, MDB_FETCHMODE_ASSOC);
-
- if (MDB::isError($res)) {
- return PEAR::raiseError($res->getMessage(), $res->getCode());
- } else {
- foreach ($res as $user) {
- $user['username'] = $user[$this->options['usernamecol']];
- $retVal[] = $user;
- }
- }
- $this->log('Found '.count($retVal).' users.', AUTH_LOG_DEBUG);
- return $retVal;
- }
-
- // }}}
- // {{{ addUser()
-
- /**
- * Add user to the storage container
- *
- * @access public
- * @param string Username
- * @param string Password
- * @param mixed Additional information that are stored in the DB
- *
- * @return mixed True on success, otherwise error object
- */
- function addUser($username, $password, $additional = "")
- {
- $this->log('Auth_Container_MDB::addUser() called.', AUTH_LOG_DEBUG);
- $err = $this->_prepare();
- if ($err !== true) {
- return PEAR::raiseError($err->getMessage(), $err->getCode());
- }
-
- if (isset($this->options['cryptType']) && $this->options['cryptType'] == 'none') {
- $cryptFunction = 'strval';
- } elseif (isset($this->options['cryptType']) && function_exists($this->options['cryptType'])) {
- $cryptFunction = $this->options['cryptType'];
- } else {
- $cryptFunction = 'md5';
- }
-
- $password = $cryptFunction($password);
-
- $additional_key = '';
- $additional_value = '';
-
- if (is_array($additional)) {
- foreach ($additional as $key => $value) {
- if ($this->options['auto_quote']) {
- $additional_key .= ', ' . $this->db->quoteIdentifier($key);
- } else {
- $additional_key .= ', ' . $key;
- }
- $additional_value .= ', ' . $this->db->getTextValue($value);
- }
- }
-
- $query = sprintf("INSERT INTO %s (%s, %s%s) VALUES (%s, %s%s)",
- $this->options['final_table'],
- $this->options['final_usernamecol'],
- $this->options['final_passwordcol'],
- $additional_key,
- $this->db->getTextValue($username),
- $this->db->getTextValue($password),
- $additional_value
- );
-
- $this->log('Running SQL against MDB: '.$query, AUTH_LOG_DEBUG);
-
- $res = $this->query($query);
-
- if (MDB::isError($res)) {
- return PEAR::raiseError($res->getMessage(), $res->code);
- }
- return true;
- }
-
- // }}}
- // {{{ removeUser()
-
- /**
- * Remove user from the storage container
- *
- * @access public
- * @param string Username
- *
- * @return mixed True on success, otherwise error object
- */
- function removeUser($username)
- {
- $this->log('Auth_Container_MDB::removeUser() called.', AUTH_LOG_DEBUG);
- $err = $this->_prepare();
- if ($err !== true) {
- return PEAR::raiseError($err->getMessage(), $err->getCode());
- }
-
- $query = sprintf("DELETE FROM %s WHERE %s = %s",
- $this->options['final_table'],
- $this->options['final_usernamecol'],
- $this->db->getTextValue($username)
- );
-
- // check if there is an optional parameter db_where
- if ($this->options['db_where'] != '') {
- // there is one, so add it to the query
- $query .= " AND ".$this->options['db_where'];
- }
-
- $this->log('Running SQL against MDB: '.$query, AUTH_LOG_DEBUG);
-
- $res = $this->query($query);
-
- if (MDB::isError($res)) {
- return PEAR::raiseError($res->getMessage(), $res->code);
- }
- return true;
- }
-
- // }}}
- // {{{ changePassword()
-
- /**
- * Change password for user in the storage container
- *
- * @param string Username
- * @param string The new password (plain text)
- */
- function changePassword($username, $password)
- {
- $this->log('Auth_Container_MDB::changePassword() called.', AUTH_LOG_DEBUG);
- $err = $this->_prepare();
- if ($err !== true) {
- return PEAR::raiseError($err->getMessage(), $err->getCode());
- }
-
- if (isset($this->options['cryptType']) && $this->options['cryptType'] == 'none') {
- $cryptFunction = 'strval';
- } elseif (isset($this->options['cryptType']) && function_exists($this->options['cryptType'])) {
- $cryptFunction = $this->options['cryptType'];
- } else {
- $cryptFunction = 'md5';
- }
-
- $password = $cryptFunction($password);
-
- $query = sprintf("UPDATE %s SET %s = %s WHERE %s = %s",
- $this->options['final_table'],
- $this->options['final_passwordcol'],
- $this->db->getTextValue($password),
- $this->options['final_usernamecol'],
- $this->db->getTextValue($username)
- );
-
- // check if there is an optional parameter db_where
- if ($this->options['db_where'] != '') {
- // there is one, so add it to the query
- $query .= " AND ".$this->options['db_where'];
- }
-
- $this->log('Running SQL against MDB: '.$query, AUTH_LOG_DEBUG);
-
- $res = $this->query($query);
-
- if (MDB::isError($res)) {
- return PEAR::raiseError($res->getMessage(), $res->code);
- }
- return true;
- }
-
- // }}}
- // {{{ supportsChallengeResponse()
-
- /**
- * Determine if this container supports
- * password authentication with challenge response
- *
- * @return bool
- * @access public
- */
- function supportsChallengeResponse()
- {
- return in_array($this->options['cryptType'], array('md5', 'none', ''));
- }
-
- // }}}
- // {{{ getCryptType()
-
- /**
- * Returns the selected crypt type for this container
- *
- * @return string Function used to crypt the password
- */
- function getCryptType()
- {
- return $this->options['cryptType'];
- }
-
- // }}}
-
-}
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */
-
-/**
- * Storage driver for use against PEAR MDB2
- *
- * PHP versions 4 and 5
- *
- * LICENSE: This source file is subject to version 3.01 of the PHP license
- * that is available through the world-wide-web at the following URI:
- * http://www.php.net/license/3_01.txt. If you did not receive a copy of
- * the PHP License and are unable to obtain it through the web, please
- * send a note to license@php.net so we can mail you a copy immediately.
- *
- * @category Authentication
- * @package Auth
- * @author Lorenzo Alberton <l.alberton@quipo.it>
- * @author Adam Ashley <aashley@php.net>
- * @copyright 2001-2006 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version CVS: $Id: MDB2.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- * @link http://pear.php.net/package/Auth
- * @since File available since Release 1.3.0
- */
-
-/**
- * Include Auth_Container base class
- */
-require_once 'Auth/Container.php';
-/**
- * Include PEAR MDB2 package
- */
-require_once 'MDB2.php';
-
-/**
- * Storage driver for fetching login data from a database
- *
- * This storage driver can use all databases which are supported
- * by the PEAR MDB2 abstraction layer to fetch login data.
- *
- * @category Authentication
- * @package Auth
- * @author Lorenzo Alberton <l.alberton@quipo.it>
- * @author Adam Ashley <aashley@php.net>
- * @copyright 2001-2006 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version Release: 1.5.4 File: $Revision: 1.1.1.1 $
- * @link http://pear.php.net/package/Auth
- * @since Class available since Release 1.3.0
- */
-class Auth_Container_MDB2 extends Auth_Container
-{
-
- // {{{ properties
-
- /**
- * Additional options for the storage container
- * @var array
- */
- var $options = array();
-
- /**
- * MDB object
- * @var object
- */
- var $db = null;
- var $dsn = '';
-
- /**
- * User that is currently selected from the DB.
- * @var string
- */
- var $activeUser = '';
-
- // }}}
- // {{{ Auth_Container_MDB2() [constructor]
-
- /**
- * Constructor of the container class
- *
- * Initate connection to the database via PEAR::MDB2
- *
- * @param string Connection data or MDB2 object
- * @return object Returns an error object if something went wrong
- */
- function Auth_Container_MDB2($dsn)
- {
- $this->_setDefaults();
-
- if (is_array($dsn)) {
- $this->_parseOptions($dsn);
- if (empty($this->options['dsn'])) {
- PEAR::raiseError('No connection parameters specified!');
- }
- } else {
- $this->options['dsn'] = $dsn;
- }
- }
-
- // }}}
- // {{{ _connect()
-
- /**
- * Connect to database by using the given DSN string
- *
- * @access private
- * @param mixed DSN string | array | mdb object
- * @return mixed Object on error, otherwise bool
- */
- function _connect($dsn)
- {
- $this->log('Auth_Container_MDB2::_connect() called.', AUTH_LOG_DEBUG);
- if (is_string($dsn) || is_array($dsn)) {
- $this->db =& MDB2::connect($dsn, $this->options['db_options']);
- } elseif (is_subclass_of($dsn, 'MDB2_Driver_Common')) {
- $this->db = $dsn;
- } elseif (is_object($dsn) && MDB2::isError($dsn)) {
- return PEAR::raiseError($dsn->getMessage(), $dsn->code);
- } else {
- return PEAR::raiseError('The given dsn was not valid in file ' . __FILE__ . ' at line ' . __LINE__,
- 41,
- PEAR_ERROR_RETURN,
- null,
- null
- );
-
- }
-
- if (MDB2::isError($this->db) || PEAR::isError($this->db)) {
- return PEAR::raiseError($this->db->getMessage(), $this->db->code);
- }
-
- if ($this->options['auto_quote']) {
- $this->options['final_table'] = $this->db->quoteIdentifier($this->options['table'], true);
- $this->options['final_usernamecol'] = $this->db->quoteIdentifier($this->options['usernamecol'], true);
- $this->options['final_passwordcol'] = $this->db->quoteIdentifier($this->options['passwordcol'], true);
- } else {
- $this->options['final_table'] = $this->options['table'];
- $this->options['final_usernamecol'] = $this->options['usernamecol'];
- $this->options['final_passwordcol'] = $this->options['passwordcol'];
- }
-
- return true;
- }
-
- // }}}
- // {{{ _prepare()
-
- /**
- * Prepare database connection
- *
- * This function checks if we have already opened a connection to
- * the database. If that's not the case, a new connection is opened.
- *
- * @access private
- * @return mixed True or a MDB error object.
- */
- function _prepare()
- {
- if (is_subclass_of($this->db, 'MDB2_Driver_Common')) {
- return true;
- }
- return $this->_connect($this->options['dsn']);
- }
-
- // }}}
- // {{{ query()
-
- /**
- * Prepare query to the database
- *
- * This function checks if we have already opened a connection to
- * the database. If that's not the case, a new connection is opened.
- * After that the query is passed to the database.
- *
- * @access public
- * @param string Query string
- * @return mixed a MDB_result object or MDB_OK on success, a MDB
- * or PEAR error on failure
- */
- function query($query)
- {
- $this->log('Auth_Container_MDB2::query() called.', AUTH_LOG_DEBUG);
- $err = $this->_prepare();
- if ($err !== true) {
- return $err;
- }
- return $this->db->exec($query);
- }
-
- // }}}
- // {{{ _setDefaults()
-
- /**
- * Set some default options
- *
- * @access private
- * @return void
- */
- function _setDefaults()
- {
- $this->options['table'] = 'auth';
- $this->options['usernamecol'] = 'username';
- $this->options['passwordcol'] = 'password';
- $this->options['dsn'] = '';
- $this->options['db_fields'] = '';
- $this->options['cryptType'] = 'md5';
- $this->options['db_options'] = array();
- $this->options['db_where'] = '';
- $this->options['auto_quote'] = true;
- }
-
- // }}}
- // {{{ _parseOptions()
-
- /**
- * Parse options passed to the container class
- *
- * @access private
- * @param array
- */
- function _parseOptions($array)
- {
- foreach ($array as $key => $value) {
- if (isset($this->options[$key])) {
- $this->options[$key] = $value;
- }
- }
- }
-
- // }}}
- // {{{ _quoteDBFields()
-
- /**
- * Quote the db_fields option to avoid the possibility of SQL injection.
- *
- * @access private
- * @return string A properly quoted string that can be concatenated into a
- * SELECT clause.
- */
- function _quoteDBFields()
- {
- if (isset($this->options['db_fields'])) {
- if (is_array($this->options['db_fields'])) {
- if ($this->options['auto_quote']) {
- $fields = array();
- foreach ($this->options['db_fields'] as $field) {
- $fields[] = $this->db->quoteIdentifier($field, true);
- }
- return implode(', ', $fields);
- } else {
- return implode(', ', $this->options['db_fields']);
- }
- } else {
- if (strlen($this->options['db_fields']) > 0) {
- if ($this->options['auto_quote']) {
- return $this->db->quoteIdentifier($this->options['db_fields'], true);
- } else {
- return $this->options['db_fields'];
- }
- }
- }
- }
-
- return '';
- }
-
- // }}}
- // {{{ fetchData()
-
- /**
- * Get user information from database
- *
- * This function uses the given username to fetch
- * the corresponding login data from the database
- * table. If an account that matches the passed username
- * and password is found, the function returns true.
- * Otherwise it returns false.
- *
- * @param string Username
- * @param string Password
- * @param boolean If true password is secured using a md5 hash
- * the frontend and auth are responsible for making sure the container supports
- * challenge response password authentication
- * @return mixed Error object or boolean
- */
- function fetchData($username, $password, $isChallengeResponse=false)
- {
- $this->log('Auth_Container_MDB2::fetchData() called.', AUTH_LOG_DEBUG);
- // Prepare for a database query
- $err = $this->_prepare();
- if ($err !== true) {
- return PEAR::raiseError($err->getMessage(), $err->getCode());
- }
-
- //Check if db_fields contains a *, if so assume all columns are selected
- if (is_string($this->options['db_fields'])
- && strstr($this->options['db_fields'], '*')) {
- $sql_from = '*';
- } else {
- $sql_from = $this->options['final_usernamecol'].
- ", ".$this->options['final_passwordcol'];
-
- if (strlen($fields = $this->_quoteDBFields()) > 0) {
- $sql_from .= ', '.$fields;
- }
- }
- $query = sprintf("SELECT %s FROM %s WHERE %s = %s",
- $sql_from,
- $this->options['final_table'],
- $this->options['final_usernamecol'],
- $this->db->quote($username, 'text')
- );
-
- // check if there is an optional parameter db_where
- if ($this->options['db_where'] != '') {
- // there is one, so add it to the query
- $query .= " AND ".$this->options['db_where'];
- }
-
- $this->log('Running SQL against MDB2: '.$query, AUTH_LOG_DEBUG);
-
- $res = $this->db->queryRow($query, null, MDB2_FETCHMODE_ASSOC);
- if (MDB2::isError($res) || PEAR::isError($res)) {
- return PEAR::raiseError($res->getMessage(), $res->getCode());
- }
- if (!is_array($res)) {
- $this->activeUser = '';
- return false;
- }
-
- // Perform trimming here before the hashing
- $password = trim($password, "\r\n");
- $res[$this->options['passwordcol']] = trim($res[$this->options['passwordcol']], "\r\n");
- // If using Challenge Response md5 the pass with the secret
- if ($isChallengeResponse) {
- $res[$this->options['passwordcol']] =
- md5($res[$this->options['passwordcol']].$this->_auth_obj->session['loginchallenege']);
- // UGLY cannot avoid without modifying verifyPassword
- if ($this->options['cryptType'] == 'md5') {
- $res[$this->options['passwordcol']] = md5($res[$this->options['passwordcol']]);
- }
- }
- if ($this->verifyPassword($password,
- $res[$this->options['passwordcol']],
- $this->options['cryptType'])) {
- // Store additional field values in the session
- foreach ($res as $key => $value) {
- if ($key == $this->options['passwordcol'] ||
- $key == $this->options['usernamecol']) {
- continue;
- }
-
- $this->log('Storing additional field: '.$key, AUTH_LOG_DEBUG);
-
- // Use reference to the auth object if exists
- // This is because the auth session variable can change so a static call to setAuthData does not make sense
- $this->_auth_obj->setAuthData($key, $value);
- }
- return true;
- }
-
- $this->activeUser = $res[$this->options['usernamecol']];
- return false;
- }
-
- // }}}
- // {{{ listUsers()
-
- /**
- * Returns a list of users from the container
- *
- * @return mixed array|PEAR_Error
- * @access public
- */
- function listUsers()
- {
- $this->log('Auth_Container_MDB2::listUsers() called.', AUTH_LOG_DEBUG);
- $err = $this->_prepare();
- if ($err !== true) {
- return PEAR::raiseError($err->getMessage(), $err->getCode());
- }
-
- $retVal = array();
-
- //Check if db_fields contains a *, if so assume all columns are selected
- if ( is_string($this->options['db_fields'])
- && strstr($this->options['db_fields'], '*')) {
- $sql_from = '*';
- } else {
- $sql_from = $this->options['final_usernamecol'].
- ", ".$this->options['final_passwordcol'];
-
- if (strlen($fields = $this->_quoteDBFields()) > 0) {
- $sql_from .= ', '.$fields;
- }
- }
-
- $query = sprintf('SELECT %s FROM %s',
- $sql_from,
- $this->options['final_table']
- );
-
- // check if there is an optional parameter db_where
- if ($this->options['db_where'] != '') {
- // there is one, so add it to the query
- $query .= " WHERE ".$this->options['db_where'];
- }
-
- $this->log('Running SQL against MDB2: '.$query, AUTH_LOG_DEBUG);
-
- $res = $this->db->queryAll($query, null, MDB2_FETCHMODE_ASSOC);
- if (MDB2::isError($res)) {
- return PEAR::raiseError($res->getMessage(), $res->getCode());
- } else {
- foreach ($res as $user) {
- $user['username'] = $user[$this->options['usernamecol']];
- $retVal[] = $user;
- }
- }
- $this->log('Found '.count($retVal).' users.', AUTH_LOG_DEBUG);
- return $retVal;
- }
-
- // }}}
- // {{{ addUser()
-
- /**
- * Add user to the storage container
- *
- * @access public
- * @param string Username
- * @param string Password
- * @param mixed Additional information that are stored in the DB
- *
- * @return mixed True on success, otherwise error object
- */
- function addUser($username, $password, $additional = "")
- {
- $this->log('Auth_Container_MDB2::addUser() called.', AUTH_LOG_DEBUG);
-
- // Prepare for a database query
- $err = $this->_prepare();
- if ($err !== true) {
- return PEAR::raiseError($err->getMessage(), $err->getCode());
- }
-
- if (isset($this->options['cryptType']) && $this->options['cryptType'] == 'none') {
- $cryptFunction = 'strval';
- } elseif (isset($this->options['cryptType']) && function_exists($this->options['cryptType'])) {
- $cryptFunction = $this->options['cryptType'];
- } else {
- $cryptFunction = 'md5';
- }
-
- $password = $cryptFunction($password);
-
- $additional_key = '';
- $additional_value = '';
-
- if (is_array($additional)) {
- foreach ($additional as $key => $value) {
- if ($this->options['auto_quote']) {
- $additional_key .= ', ' . $this->db->quoteIdentifier($key, true);
- } else {
- $additional_key .= ', ' . $key;
- }
- $additional_value .= ', ' . $this->db->quote($value, 'text');
- }
- }
-
- $query = sprintf("INSERT INTO %s (%s, %s%s) VALUES (%s, %s%s)",
- $this->options['final_table'],
- $this->options['final_usernamecol'],
- $this->options['final_passwordcol'],
- $additional_key,
- $this->db->quote($username, 'text'),
- $this->db->quote($password, 'text'),
- $additional_value
- );
-
- $this->log('Running SQL against MDB2: '.$query, AUTH_LOG_DEBUG);
-
- $res = $this->query($query);
-
- if (MDB2::isError($res)) {
- return PEAR::raiseError($res->getMessage(), $res->code);
- }
- return true;
- }
-
- // }}}
- // {{{ removeUser()
-
- /**
- * Remove user from the storage container
- *
- * @access public
- * @param string Username
- *
- * @return mixed True on success, otherwise error object
- */
- function removeUser($username)
- {
- $this->log('Auth_Container_MDB2::removeUser() called.', AUTH_LOG_DEBUG);
- // Prepare for a database query
- $err = $this->_prepare();
- if ($err !== true) {
- return PEAR::raiseError($err->getMessage(), $err->getCode());
- }
-
- $query = sprintf("DELETE FROM %s WHERE %s = %s",
- $this->options['final_table'],
- $this->options['final_usernamecol'],
- $this->db->quote($username, 'text')
- );
-
- // check if there is an optional parameter db_where
- if ($this->options['db_where'] != '') {
- // there is one, so add it to the query
- $query .= " AND ".$this->options['db_where'];
- }
-
- $this->log('Running SQL against MDB2: '.$query, AUTH_LOG_DEBUG);
-
- $res = $this->query($query);
-
- if (MDB2::isError($res)) {
- return PEAR::raiseError($res->getMessage(), $res->code);
- }
- return true;
- }
-
- // }}}
- // {{{ changePassword()
-
- /**
- * Change password for user in the storage container
- *
- * @param string Username
- * @param string The new password (plain text)
- */
- function changePassword($username, $password)
- {
- $this->log('Auth_Container_MDB2::changePassword() called.', AUTH_LOG_DEBUG);
- // Prepare for a database query
- $err = $this->_prepare();
- if ($err !== true) {
- return PEAR::raiseError($err->getMessage(), $err->getCode());
- }
-
- if (isset($this->options['cryptType']) && $this->options['cryptType'] == 'none') {
- $cryptFunction = 'strval';
- } elseif (isset($this->options['cryptType']) && function_exists($this->options['cryptType'])) {
- $cryptFunction = $this->options['cryptType'];
- } else {
- $cryptFunction = 'md5';
- }
-
- $password = $cryptFunction($password);
-
- $query = sprintf("UPDATE %s SET %s = %s WHERE %s = %s",
- $this->options['final_table'],
- $this->options['final_passwordcol'],
- $this->db->quote($password, 'text'),
- $this->options['final_usernamecol'],
- $this->db->quote($username, 'text')
- );
-
- // check if there is an optional parameter db_where
- if ($this->options['db_where'] != '') {
- // there is one, so add it to the query
- $query .= " AND ".$this->options['db_where'];
- }
-
- $this->log('Running SQL against MDB2: '.$query, AUTH_LOG_DEBUG);
-
- $res = $this->query($query);
-
- if (MDB2::isError($res)) {
- return PEAR::raiseError($res->getMessage(), $res->code);
- }
- return true;
- }
-
- // }}}
- // {{{ supportsChallengeResponse()
-
- /**
- * Determine if this container supports
- * password authentication with challenge response
- *
- * @return bool
- * @access public
- */
- function supportsChallengeResponse()
- {
- return in_array($this->options['cryptType'], array('md5', 'none', ''));
- }
-
- // }}}
- // {{{ getCryptType()
-
- /**
- * Returns the selected crypt type for this container
- *
- * @return string Function used to crypt the password
- */
- function getCryptType()
- {
- return $this->options['cryptType'];
- }
-
- // }}}
-
-}
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */
-
-/**
- * Storage driver for using multiple storage drivers in a fall through fashion
- *
- * PHP versions 4 and 5
- *
- * LICENSE: This source file is subject to version 3.01 of the PHP license
- * that is available through the world-wide-web at the following URI:
- * http://www.php.net/license/3_01.txt. If you did not receive a copy of
- * the PHP License and are unable to obtain it through the web, please
- * send a note to license@php.net so we can mail you a copy immediately.
- *
- * @category Authentication
- * @package Auth
- * @author Adam Ashley <aashley@php.net>
- * @copyright 2001-2006 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version CVS: $Id: Multiple.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- * @since File available since Release 1.5.0
- */
-
-/**
- * Include Auth_Container base class
- */
-require_once "Auth/Container.php";
-/**
- * Include PEAR package for error handling
- */
-require_once "PEAR.php";
-
-/**
- * Storage driver for using multiple storage drivers in a fall through fashion
- *
- * This storage driver provides a mechanism for working through multiple
- * storage drivers until either one allows successful login or the list is
- * exhausted.
- *
- * This container takes an array of options of the following form:
- *
- * array(
- * array(
- * 'type' => <standard container type name>,
- * 'options' => <normal array of options for container>,
- * ),
- * );
- *
- * Full example:
- *
- * $options = array(
- * array(
- * 'type' => 'DB',
- * 'options' => array(
- * 'dsn' => "mysql://user:password@localhost/database",
- * ),
- * ),
- * array(
- * 'type' => 'Array',
- * 'options' => array(
- * 'cryptType' => 'md5',
- * 'users' => array(
- * 'admin' => md5('password'),
- * ),
- * ),
- * ),
- * );
- *
- * $auth = new Auth('Multiple', $options);
- *
- * @category Authentication
- * @package Auth
- * @author Adam Ashley <aashley@php.net>
- * @copyright 2001-2006 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version Release: 1.5.4 File: $Revision: 1.1.1.1 $
- * @since File available since Release 1.5.0
- */
-
-class Auth_Container_Multiple extends Auth_Container {
-
- // {{{ properties
-
- /**
- * The options for each container
- *
- * @var array $options
- */
- var $options = array();
-
- /**
- * The instanciated containers
- *
- * @var array $containers
- */
- var $containers = array();
-
- // }}}
- // {{{ Auth_Container_Multiple()
-
- /**
- * Constructor for Array Container
- *
- * @param array $data Options for the container
- * @return void
- */
- function Auth_Container_Multiple($options)
- {
- if (!is_array($options)) {
- PEAR::raiseError('The options for Auth_Container_Multiple must be an array');
- }
- if (count($options) < 1) {
- PEAR::raiseError('You must define at least one sub container to use in Auth_Container_Multiple');
- }
- foreach ($options as $option) {
- if (!isset($option['type'])) {
- PEAR::raiseError('No type defined for sub container');
- }
- }
- $this->options = $options;
- }
-
- // }}}
- // {{{ fetchData()
-
- /**
- * Get user information from array
- *
- * This function uses the given username to fetch the corresponding
- * login data from the array. If an account that matches the passed
- * username and password is found, the function returns true.
- * Otherwise it returns false.
- *
- * @param string Username
- * @param string Password
- * @return boolean|PEAR_Error Error object or boolean
- */
- function fetchData($user, $pass)
- {
- $this->log('Auth_Container_Multiple::fetchData() called.', AUTH_LOG_DEBUG);
-
- foreach ($this->options as $key => $options) {
-
- $this->log('Using Container '.$key.' of type '.$options['type'].'.', AUTH_LOG_DEBUG);
-
- if (isset($this->containers[$key]) && is_a($this->containers[$key], 'Auth_Container')) {
-
- $container = &$this->containers[$key];
-
- } else {
-
- $this->containers[$key] = &$this->_auth_obj->_factory($options['type'], $options['options']);
- $this->containers[$key]->_auth_obj = &$this->_auth_obj;
- $container = &$this->containers[$key];
-
- }
-
- $result = $container->fetchData($user, $pass);
-
- if (PEAR::isError($result)) {
-
- $this->log('Container '.$key.': '.$result->getMessage(), AUTH_LOG_ERR);
- return $result;
-
- } elseif ($result == true) {
-
- $this->log('Container '.$key.': Authentication successful.', AUTH_LOG_DEBUG);
- return true;
-
- } else {
-
- $this->log('Container '.$key.': Authentication failed.', AUTH_LOG_DEBUG);
-
- }
-
- }
-
- $this->log('Auth_Container_Multiple: All containers rejected user credentials.', AUTH_LOG_DEBUG);
-
- return false;
-
- }
-
- // }}}
-
-}
-
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */
-
-/**
- * Storage driver for use against PEAR website
- *
- * PHP versions 4 and 5
- *
- * LICENSE: This source file is subject to version 3.01 of the PHP license
- * that is available through the world-wide-web at the following URI:
- * http://www.php.net/license/3_01.txt. If you did not receive a copy of
- * the PHP License and are unable to obtain it through the web, please
- * send a note to license@php.net so we can mail you a copy immediately.
- *
- * @category Authentication
- * @package Auth
- * @author Yavor Shahpasov <yavo@netsmart.com.cy>
- * @author Adam Ashley <aashley@php.net>
- * @copyright 2001-2006 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version CVS: $Id: PEAR.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- * @link http://pear.php.net/package/Auth
- * @since File available since Release 1.3.0
- */
-
-/**
- * Include PEAR HTTP_Client.
- */
-require_once 'HTTP/Client.php';
-/**
- * Include Auth_Container base class
- */
-require_once 'Auth/Container.php';
-
-/**
- * Storage driver for authenticating against PEAR website
- *
- * This driver provides a method for authenticating against the pear.php.net
- * authentication system.
- *
- * @category Authentication
- * @package Auth
- * @author Yavor Shahpasov <yavo@netsmart.com.cy>
- * @author Adam Ashley <aashley@php.net>
- * @author Adam Harvey <aharvey@php.net>
- * @copyright 2001-2007 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version Release: 1.5.4 File: $Revision: 1.1.1.1 $
- * @link http://pear.php.net/package/Auth
- * @since Class available since Release 1.3.0
- */
-class Auth_Container_Pear extends Auth_Container
-{
-
- // {{{ Auth_Container_Pear() [constructor]
-
- /**
- * Constructor
- *
- * Currently does nothing
- *
- * @return void
- */
- function Auth_Container_Pear()
- {
-
- }
-
- // }}}
- // {{{ fetchData()
-
- /**
- * Get user information from pear.php.net
- *
- * This function uses the given username and password to authenticate
- * against the pear.php.net website
- *
- * @param string Username
- * @param string Password
- * @return mixed Error object or boolean
- */
- function fetchData($username, $password)
- {
- $this->log('Auth_Container_PEAR::fetchData() called.', AUTH_LOG_DEBUG);
-
- $client = new HTTP_Client;
-
- $this->log('Auth_Container_PEAR::fetchData() getting salt.', AUTH_LOG_DEBUG);
- $code = $client->get('https://pear.php.net/rest-login.php/getsalt');
- if ($code != 200) {
- return PEAR::raiseError('Bad response to salt request.', $code);
- }
- $resp = $client->currentResponse();
- $salt = $resp['body'];
-
- $this->log('Auth_Container_PEAR::fetchData() calling validate.', AUTH_LOG_DEBUG);
- $code = $client->post('https://pear.php.net/rest-login.php/validate',
- array('username' => $username,
- 'password' => md5($salt.md5($password))));
- if ($code != 200) {
- return PEAR::raiseError('Bad response to validate request.', $code);
- }
- $resp = $client->currentResponse();
-
- list($code, $message) = explode(' ', $resp['body'], 1);
- if ($code != 8) {
- return PEAR::raiseError($message, $code);
- }
- return true;
- }
-
- // }}}
-
-}
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */
-
-/**
- * Storage driver for use against a POP3 server
- *
- * PHP versions 4 and 5
- *
- * LICENSE: This source file is subject to version 3.01 of the PHP license
- * that is available through the world-wide-web at the following URI:
- * http://www.php.net/license/3_01.txt. If you did not receive a copy of
- * the PHP License and are unable to obtain it through the web, please
- * send a note to license@php.net so we can mail you a copy immediately.
- *
- * @category Authentication
- * @package Auth
- * @author Stefan Ekman <stekman@sedata.org>
- * @author Martin Jansen <mj@php.net>
- * @author Mika Tuupola <tuupola@appelsiini.net>
- * @author Adam Ashley <aashley@php.net>
- * @copyright 2001-2006 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version CVS: $Id: POP3.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- * @link http://pear.php.net/package/Auth
- * @since File available since Release 1.2.0
- */
-
-/**
- * Include Auth_Container base class
- */
-require_once 'Auth/Container.php';
-/**
- * Include PEAR package for error handling
- */
-require_once 'PEAR.php';
-/**
- * Include PEAR Net_POP3 package
- */
-require_once 'Net/POP3.php';
-
-/**
- * Storage driver for Authentication on a POP3 server.
- *
- * @category Authentication
- * @package Auth
- * @author Martin Jansen <mj@php.net>
- * @author Mika Tuupola <tuupola@appelsiini.net>
- * @author Adam Ashley <aashley@php.net>
- * @copyright 2001-2006 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version Release: 1.5.4 File: $Revision: 1.1.1.1 $
- * @link http://pear.php.net/package/Auth
- * @since Class available since Release 1.2.0
- */
-class Auth_Container_POP3 extends Auth_Container
-{
-
- // {{{ properties
-
- /**
- * POP3 Server
- * @var string
- */
- var $server='localhost';
-
- /**
- * POP3 Server port
- * @var string
- */
- var $port='110';
-
- /**
- * POP3 Authentication method
- *
- * Prefered POP3 authentication method. Acceptable values:
- * Boolean TRUE - Use Net_POP3's autodetection
- * String 'DIGEST-MD5','CRAM-MD5','LOGIN','PLAIN','APOP','USER'
- * - Attempt this authentication style first
- * then fallback to autodetection.
- * @var mixed
- */
- var $method=true;
-
- // }}}
- // {{{ Auth_Container_POP3() [constructor]
-
- /**
- * Constructor of the container class
- *
- * @param $server string server or server:port combination
- * @return object Returns an error object if something went wrong
- */
- function Auth_Container_POP3($server=null)
- {
- if (isset($server) && !is_null($server)) {
- if (is_array($server)) {
- if (isset($server['host'])) {
- $this->server = $server['host'];
- }
- if (isset($server['port'])) {
- $this->port = $server['port'];
- }
- if (isset($server['method'])) {
- $this->method = $server['method'];
- }
- } else {
- if (strstr($server, ':')) {
- $serverparts = explode(':', trim($server));
- $this->server = $serverparts[0];
- $this->port = $serverparts[1];
- } else {
- $this->server = $server;
- }
- }
- }
- }
-
- // }}}
- // {{{ fetchData()
-
- /**
- * Try to login to the POP3 server
- *
- * @param string Username
- * @param string Password
- * @return boolean
- */
- function fetchData($username, $password)
- {
- $this->log('Auth_Container_POP3::fetchData() called.', AUTH_LOG_DEBUG);
- $pop3 =& new Net_POP3();
- $res = $pop3->connect($this->server, $this->port, $this->method);
- if (!$res) {
- $this->log('Connection to POP3 server failed.', AUTH_LOG_DEBUG);
- return $res;
- }
- $result = $pop3->login($username, $password);
- $pop3->disconnect();
- return $result;
- }
-
- // }}}
-
-}
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */
-
-/**
- * Storage driver for use against RADIUS servers
- *
- * PHP versions 4 and 5
- *
- * LICENSE: This source file is subject to version 3.01 of the PHP license
- * that is available through the world-wide-web at the following URI:
- * http://www.php.net/license/3_01.txt. If you did not receive a copy of
- * the PHP License and are unable to obtain it through the web, please
- * send a note to license@php.net so we can mail you a copy immediately.
- *
- * @category Authentication
- * @package Auth
- * @author Michael Bretterklieber <michael@bretterklieber.com>
- * @author Adam Ashley <aashley@php.net>
- * @copyright 2001-2006 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version CVS: $Id: RADIUS.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- * @link http://pear.php.net/package/Auth
- * @since File available since Release 1.2.0
- */
-
-/**
- * Include Auth_Container base class
- */
-require_once "Auth/Container.php";
-/**
- * Include PEAR Auth_RADIUS package
- */
-require_once "Auth/RADIUS.php";
-
-/**
- * Storage driver for authenticating users against RADIUS servers.
- *
- * @category Authentication
- * @package Auth
- * @author Michael Bretterklieber <michael@bretterklieber.com>
- * @author Adam Ashley <aashley@php.net>
- * @copyright 2001-2006 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version Release: 1.5.4 File: $Revision: 1.1.1.1 $
- * @link http://pear.php.net/package/Auth
- * @since Class available since Release 1.2.0
- */
-class Auth_Container_RADIUS extends Auth_Container
-{
-
- // {{{ properties
-
- /**
- * Contains a RADIUS object
- * @var object
- */
- var $radius;
-
- /**
- * Contains the authentication type
- * @var string
- */
- var $authtype;
-
- // }}}
- // {{{ Auth_Container_RADIUS() [constructor]
-
- /**
- * Constructor of the container class.
- *
- * $options can have these keys:
- * 'servers' an array containing an array: servername, port,
- * sharedsecret, timeout, maxtries
- * 'configfile' The filename of the configuration file
- * 'authtype' The type of authentication, one of: PAP, CHAP_MD5,
- * MSCHAPv1, MSCHAPv2, default is PAP
- *
- * @param $options associative array
- * @return object Returns an error object if something went wrong
- */
- function Auth_Container_RADIUS($options)
- {
- $this->authtype = 'PAP';
- if (isset($options['authtype'])) {
- $this->authtype = $options['authtype'];
- }
- $classname = 'Auth_RADIUS_' . $this->authtype;
- if (!class_exists($classname)) {
- PEAR::raiseError("Unknown Authtype, please use one of: "
- ."PAP, CHAP_MD5, MSCHAPv1, MSCHAPv2!", 41, PEAR_ERROR_DIE);
- }
-
- $this->radius = new $classname;
-
- if (isset($options['configfile'])) {
- $this->radius->setConfigfile($options['configfile']);
- }
-
- $servers = $options['servers'];
- if (is_array($servers)) {
- foreach ($servers as $server) {
- $servername = $server[0];
- $port = isset($server[1]) ? $server[1] : 0;
- $sharedsecret = isset($server[2]) ? $server[2] : 'testing123';
- $timeout = isset($server[3]) ? $server[3] : 3;
- $maxtries = isset($server[4]) ? $server[4] : 3;
- $this->radius->addServer($servername, $port, $sharedsecret, $timeout, $maxtries);
- }
- }
-
- if (!$this->radius->start()) {
- PEAR::raiseError($this->radius->getError(), 41, PEAR_ERROR_DIE);
- }
- }
-
- // }}}
- // {{{ fetchData()
-
- /**
- * Authenticate
- *
- * @param string Username
- * @param string Password
- * @return bool true on success, false on reject
- */
- function fetchData($username, $password, $challenge = null)
- {
- $this->log('Auth_Container_RADIUS::fetchData() called.', AUTH_LOG_DEBUG);
-
- switch($this->authtype) {
- case 'CHAP_MD5':
- case 'MSCHAPv1':
- if (isset($challenge)) {
- $this->radius->challenge = $challenge;
- $this->radius->chapid = 1;
- $this->radius->response = pack('H*', $password);
- } else {
- require_once 'Crypt/CHAP.php';
- $classname = 'Crypt_' . $this->authtype;
- $crpt = new $classname;
- $crpt->password = $password;
- $this->radius->challenge = $crpt->challenge;
- $this->radius->chapid = $crpt->chapid;
- $this->radius->response = $crpt->challengeResponse();
- }
- break;
-
- case 'MSCHAPv2':
- require_once 'Crypt/CHAP.php';
- $crpt = new Crypt_MSCHAPv2;
- $crpt->username = $username;
- $crpt->password = $password;
- $this->radius->challenge = $crpt->authChallenge;
- $this->radius->peerChallenge = $crpt->peerChallenge;
- $this->radius->chapid = $crpt->chapid;
- $this->radius->response = $crpt->challengeResponse();
- break;
-
- default:
- $this->radius->password = $password;
- break;
- }
-
- $this->radius->username = $username;
-
- $this->radius->putAuthAttributes();
- $result = $this->radius->send();
- if (PEAR::isError($result)) {
- return false;
- }
-
- $this->radius->getAttributes();
-// just for debugging
-// $this->radius->dumpAttributes();
-
- return $result;
- }
-
- // }}}
-
-}
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */
-
-/**
- * Storage driver for use against a SAP system using the SAPRFC PHP extension.
- *
- * Requires the SAPRFC ext available at http://saprfc.sourceforge.net/
- *
- * PHP version 5
- *
- * LICENSE: This source file is subject to version 3.01 of the PHP license
- * that is available through the world-wide-web at the following URI:
- * http://www.php.net/license/3_01.txt. If you did not receive a copy of
- * the PHP License and are unable to obtain it through the web, please
- * send a note to license@php.net so we can mail you a copy immediately.
- *
- * @category Authentication
- * @package Auth
- * @author Stoyan Stefanov <ssttoo@gmail.com>
- * @author Adam Ashley <aashley@php.net>
- * @copyright 2001-2006 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version CVS: $Id: SAP.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- * @link http://pear.php.net/package/Auth
- * @since File available since Release 1.4.0
- */
-
-/**
- * Include Auth_Container base class
- */
-require_once 'Auth/Container.php';
-/**
- * Include PEAR for error handling
- */
-require_once 'PEAR.php';
-
-/**
- * Performs authentication against a SAP system using the SAPRFC PHP extension.
- *
- * When the option GETSSO2 is TRUE (default)
- * the Single Sign-On (SSO) ticket is retrieved
- * and stored as an Auth attribute called 'sap'
- * in order to be reused for consecutive connections.
- *
- * @category Authentication
- * @package Auth
- * @author Stoyan Stefanov <ssttoo@gmail.com>
- * @author Adam Ashley <aashley@php.net>
- * @copyright 2001-2006 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version Release: 1.5.4 File: $Revision: 1.1.1.1 $
- * @since Class available since Release 1.4.0
- */
-class Auth_Container_SAP extends Auth_Container {
-
- // {{{ properties
-
- /**
- * @var array Default options
- */
- var $options = array(
- 'CLIENT' => '000',
- 'LANG' => 'EN',
- 'GETSSO2' => true,
- );
-
- // }}}
- // {{{ Auth_Container_SAP()
-
- /**
- * Class constructor. Checks that required options
- * are present and that the SAPRFC extension is loaded
- *
- * Options that can be passed and their defaults:
- * <pre>
- * array(
- * 'ASHOST' => "",
- * 'SYSNR' => "",
- * 'CLIENT' => "000",
- * 'GWHOST' =>"",
- * 'GWSERV' =>"",
- * 'MSHOST' =>"",
- * 'R3NAME' =>"",
- * 'GROUP' =>"",
- * 'LANG' =>"EN",
- * 'TRACE' =>"",
- * 'GETSSO2'=> true
- * )
- * </pre>
- *
- * @param array array of options.
- * @return void
- */
- function Auth_Container_SAP($options)
- {
- $saprfc_loaded = PEAR::loadExtension('saprfc');
- if (!$saprfc_loaded) {
- return PEAR::raiseError('Cannot use SAP authentication, '
- .'SAPRFC extension not loaded!');
- }
- if (empty($options['R3NAME']) && empty($options['ASHOST'])) {
- return PEAR::raiseError('R3NAME or ASHOST required for authentication');
- }
- $this->options = array_merge($this->options, $options);
- }
-
- // }}}
- // {{{ fetchData()
-
- /**
- * Performs username and password check
- *
- * @param string Username
- * @param string Password
- * @return boolean TRUE on success (valid user), FALSE otherwise
- */
- function fetchData($username, $password)
- {
- $this->log('Auth_Container_SAP::fetchData() called.', AUTH_LOG_DEBUG);
- $connection_options = $this->options;
- $connection_options['USER'] = $username;
- $connection_options['PASSWD'] = $password;
- $rfc = saprfc_open($connection_options);
- if (!$rfc) {
- $message = "Couldn't connect to the SAP system.";
- $error = $this->getError();
- if ($error['message']) {
- $message .= ': ' . $error['message'];
- }
- PEAR::raiseError($message, null, null, null, @$erorr['all']);
- return false;
- } else {
- if (!empty($this->options['GETSSO2'])) {
- $this->log('Attempting to retrieve SSO2 ticket.', AUTH_LOG_DEBUG);
- if ($ticket = @saprfc_get_ticket($rfc)) {
- $this->options['MYSAPSSO2'] = $ticket;
- unset($this->options['GETSSO2']);
- $this->_auth_obj->setAuthData('sap', $this->options);
- } else {
- PEAR::raiseError("SSO ticket retrieval failed");
- }
- }
- @saprfc_close($rfc);
- return true;
- }
-
- }
-
- // }}}
- // {{{ getError()
-
- /**
- * Retrieves the last error from the SAP connection
- * and returns it as an array.
- *
- * @return array Array of error information
- */
- function getError()
- {
-
- $error = array();
- $sap_error = saprfc_error();
- if (empty($err)) {
- return $error;
- }
- $err = explode("n", $sap_error);
- foreach ($err AS $line) {
- $item = split(':', $line);
- $error[strtolower(trim($item[0]))] = trim($item[1]);
- }
- $error['all'] = $sap_error;
- return $error;
- }
-
- // }}}
-
-}
-
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */
-
-/**
- * Storage driver for use against Samba password files
- *
- * PHP versions 4 and 5
- *
- * LICENSE: This source file is subject to version 3.01 of the PHP license
- * that is available through the world-wide-web at the following URI:
- * http://www.php.net/license/3_01.txt. If you did not receive a copy of
- * the PHP License and are unable to obtain it through the web, please
- * send a note to license@php.net so we can mail you a copy immediately.
- *
- * @category Authentication
- * @package Auth
- * @author Michael Bretterklieber <michael@bretterklieber.com>
- * @author Adam Ashley <aashley@php.net>
- * @copyright 2001-2006 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version CVS: $Id: SMBPasswd.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- * @link http://pear.php.net/package/Auth
- * @since File available since Release 1.2.3
- */
-
-/**
- * Include PEAR File_SMBPasswd
- */
-require_once "File/SMBPasswd.php";
-/**
- * Include Auth_Container Base file
- */
-require_once "Auth/Container.php";
-/**
- * Include PEAR class for error handling
- */
-require_once "PEAR.php";
-
-/**
- * Storage driver for fetching login data from an SAMBA smbpasswd file.
- *
- * This storage container can handle SAMBA smbpasswd files.
- *
- * Example:
- * $a = new Auth("SMBPasswd", '/usr/local/private/smbpasswd');
- * $a->start();
- * if ($a->getAuth()) {
- * printf ("AUTH OK<br>\n");
- * $a->logout();
- * }
- *
- * @category Authentication
- * @package Auth
- * @author Michael Bretterklieber <michael@bretterklieber.com>
- * @author Adam Ashley <aashley@php.net>
- * @package Auth
- * @copyright 2001-2006 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version Release: 1.5.4 File: $Revision: 1.1.1.1 $
- * @link http://pear.php.net/package/Auth
- * @since Class available since Release 1.2.3
- */
-class Auth_Container_SMBPasswd extends Auth_Container
-{
-
- // {{{ properties
-
- /**
- * File_SMBPasswd object
- * @var object
- */
- var $pwfile;
-
- // }}}
-
- // {{{ Auth_Container_SMBPasswd() [constructor]
-
- /**
- * Constructor of the container class
- *
- * @param $filename string filename for a passwd type file
- * @return object Returns an error object if something went wrong
- */
- function Auth_Container_SMBPasswd($filename)
- {
- $this->pwfile = new File_SMBPasswd($filename,0);
-
- if (!$this->pwfile->load()) {
- PEAR::raiseError("Error while reading file contents.", 41, PEAR_ERROR_DIE);
- return;
- }
-
- }
-
- // }}}
- // {{{ fetchData()
-
- /**
- * Get user information from pwfile
- *
- * @param string Username
- * @param string Password
- * @return boolean
- */
- function fetchData($username, $password)
- {
- $this->log('Auth_Container_SMBPasswd::fetchData() called.', AUTH_LOG_DEBUG);
- return $this->pwfile->verifyAccount($username, $password);
- }
-
- // }}}
- // {{{ listUsers()
-
- function listUsers()
- {
- $this->log('Auth_Container_SMBPasswd::fetchData() called.', AUTH_LOG_DEBUG);
- return $this->pwfile->getAccounts();
- }
-
- // }}}
- // {{{ addUser()
-
- /**
- * Add a new user to the storage container
- *
- * @param string Username
- * @param string Password
- * @param array Additional information
- *
- * @return boolean
- */
- function addUser($username, $password, $additional = '')
- {
- $this->log('Auth_Container_SMBPasswd::addUser() called.', AUTH_LOG_DEBUG);
- $res = $this->pwfile->addUser($user, $additional['userid'], $pass);
- if ($res === true) {
- return $this->pwfile->save();
- }
- return $res;
- }
-
- // }}}
- // {{{ removeUser()
-
- /**
- * Remove user from the storage container
- *
- * @param string Username
- */
- function removeUser($username)
- {
- $this->log('Auth_Container_SMBPasswd::removeUser() called.', AUTH_LOG_DEBUG);
- $res = $this->pwfile->delUser($username);
- if ($res === true) {
- return $this->pwfile->save();
- }
- return $res;
- }
-
- // }}}
- // {{{ changePassword()
-
- /**
- * Change password for user in the storage container
- *
- * @param string Username
- * @param string The new password
- */
- function changePassword($username, $password)
- {
- $this->log('Auth_Container_SMBPasswd::changePassword() called.', AUTH_LOG_DEBUG);
- $res = $this->pwfile->modUser($username, '', $password);
- if ($res === true) {
- return $this->pwfile->save();
- }
- return $res;
- }
-
- // }}}
-
-}
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */
-
-/**
- * Storage driver for use against a SOAP service
- *
- * PHP versions 4 and 5
- *
- * LICENSE: This source file is subject to version 3.01 of the PHP license
- * that is available through the world-wide-web at the following URI:
- * http://www.php.net/license/3_01.txt. If you did not receive a copy of
- * the PHP License and are unable to obtain it through the web, please
- * send a note to license@php.net so we can mail you a copy immediately.
- *
- * @category Authentication
- * @package Auth
- * @author Bruno Pedro <bpedro@co.sapo.pt>
- * @author Adam Ashley <aashley@php.net>
- * @copyright 2001-2006 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version CVS: $Id: SOAP.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- * @link http://pear.php.net/package/Auth
- * @since File available since Release 1.2.0
- */
-
-/**
- * Include Auth_Container base class
- */
-require_once "Auth/Container.php";
-/**
- * Include PEAR package for error handling
- */
-require_once "PEAR.php";
-/**
- * Include PEAR SOAP_Client
- */
-require_once 'SOAP/Client.php';
-
-/**
- * Storage driver for fetching login data from SOAP
- *
- * This class takes one parameter (options), where
- * you specify the following fields: endpoint, namespace,
- * method, encoding, usernamefield and passwordfield.
- *
- * You can use specify features of your SOAP service
- * by providing its parameters in an associative manner by
- * using the '_features' array through the options parameter.
- *
- * The 'matchpassword' option should be set to false if your
- * webservice doesn't return (username,password) pairs, but
- * instead returns error when the login is invalid.
- *
- * Example usage:
- *
- * <?php
- *
- * ...
- *
- * $options = array (
- * 'endpoint' => 'http://your.soap.service/endpoint',
- * 'namespace' => 'urn:/Your/Namespace',
- * 'method' => 'get',
- * 'encoding' => 'UTF-8',
- * 'usernamefield' => 'login',
- * 'passwordfield' => 'password',
- * 'matchpasswords' => false,
- * '_features' => array (
- * 'example_feature' => 'example_value',
- * 'another_example' => ''
- * )
- * );
- * $auth = new Auth('SOAP', $options, 'loginFunction');
- * $auth->start();
- *
- * ...
- *
- * ?>
- *
- * @category Authentication
- * @package Auth
- * @author Bruno Pedro <bpedro@co.sapo.pt>
- * @author Adam Ashley <aashley@php.net>
- * @copyright 2001-2006 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version Release: 1.5.4 File: $Revision: 1.1.1.1 $
- * @link http://pear.php.net/package/Auth
- * @since Class available since Release 1.2.0
- */
-class Auth_Container_SOAP extends Auth_Container
-{
-
- // {{{ properties
-
- /**
- * Required options for the class
- * @var array
- * @access private
- */
- var $_requiredOptions = array(
- 'endpoint',
- 'namespace',
- 'method',
- 'encoding',
- 'usernamefield',
- 'passwordfield',
- );
-
- /**
- * Options for the class
- * @var array
- * @access private
- */
- var $_options = array();
-
- /**
- * Optional SOAP features
- * @var array
- * @access private
- */
- var $_features = array();
-
- /**
- * The SOAP response
- * @var array
- * @access public
- */
- var $soapResponse = array();
-
- /**
- * The SOAP client
- * @var mixed
- * @access public
- */
- var $soapClient = null;
-
- // }}}
- // {{{ Auth_Container_SOAP() [constructor]
-
- /**
- * Constructor of the container class
- *
- * @param $options, associative array with endpoint, namespace, method,
- * usernamefield, passwordfield and optional features
- */
- function Auth_Container_SOAP($options)
- {
- $this->_options = $options;
- if (!isset($this->_options['matchpasswords'])) {
- $this->_options['matchpasswords'] = true;
- }
- if (!empty($this->_options['_features'])) {
- $this->_features = $this->_options['_features'];
- unset($this->_options['_features']);
- }
- }
-
- // }}}
- // {{{ fetchData()
-
- /**
- * Fetch data from SOAP service
- *
- * Requests the SOAP service for the given username/password
- * combination.
- *
- * @param string Username
- * @param string Password
- * @return mixed Returns the SOAP response or false if something went wrong
- */
- function fetchData($username, $password)
- {
- $this->log('Auth_Container_SOAP::fetchData() called.', AUTH_LOG_DEBUG);
- // check if all required options are set
- if (array_intersect($this->_requiredOptions, array_keys($this->_options)) != $this->_requiredOptions) {
- return false;
- } else {
- // create a SOAP client and set encoding
- $this->soapClient = new SOAP_Client($this->_options['endpoint']);
- $this->soapClient->setEncoding($this->_options['encoding']);
- }
-
- // set the trace option if requested
- if (isset($this->_options['trace'])) {
- $this->soapClient->__options['trace'] = true;
- }
-
- // set the timeout option if requested
- if (isset($this->_options['timeout'])) {
- $this->soapClient->__options['timeout'] = $this->_options['timeout'];
- }
-
- // assign username and password fields
- $usernameField = new SOAP_Value($this->_options['usernamefield'],'string', $username);
- $passwordField = new SOAP_Value($this->_options['passwordfield'],'string', $password);
- $SOAPParams = array($usernameField, $passwordField);
-
- // assign optional features
- foreach ($this->_features as $fieldName => $fieldValue) {
- $SOAPParams[] = new SOAP_Value($fieldName, 'string', $fieldValue);
- }
-
- // make SOAP call
- $this->soapResponse = $this->soapClient->call(
- $this->_options['method'],
- $SOAPParams,
- array('namespace' => $this->_options['namespace'])
- );
-
- if (!PEAR::isError($this->soapResponse)) {
- if ($this->_options['matchpasswords']) {
- // check if passwords match
- if ($password == $this->soapResponse->{$this->_options['passwordfield']}) {
- return true;
- } else {
- return false;
- }
- } else {
- return true;
- }
- } else {
- return false;
- }
- }
-
- // }}}
-
-}
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */
-
-/**
- * Storage driver for use against a SOAP service using PHP5 SoapClient
- *
- * PHP version 5
- *
- * LICENSE: This source file is subject to version 3.01 of the PHP license
- * that is available through the world-wide-web at the following URI:
- * http://www.php.net/license/3_01.txt. If you did not receive a copy of
- * the PHP License and are unable to obtain it through the web, please
- * send a note to license@php.net so we can mail you a copy immediately.
- *
- * @category Authentication
- * @package Auth
- * @author Based upon Auth_Container_SOAP by Bruno Pedro <bpedro@co.sapo.pt>
- * @author Marcel Oelke <puRe@rednoize.com>
- * @author Adam Ashley <aashley@php.net>
- * @copyright 2001-2006 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version CVS: $Id: SOAP5.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- * @since File available since Release 1.4.0
- */
-
-/**
- * Include Auth_Container base class
- */
-require_once "Auth/Container.php";
-/**
- * Include PEAR package for error handling
- */
-require_once "PEAR.php";
-
-/**
- * Storage driver for fetching login data from SOAP using the PHP5 Builtin SOAP
- * functions. This is a modification of the SOAP Storage driver from Bruno Pedro
- * thats using the PEAR SOAP Package.
- *
- * This class takes one parameter (options), where
- * you specify the following fields:
- * * location and uri, or wsdl file
- * * method to call on the SOAP service
- * * usernamefield, the name of the parameter where the username is supplied
- * * passwordfield, the name of the parameter where the password is supplied
- * * matchpassword, whether to look for the password in the response from
- * the function call or assume that no errors means user
- * authenticated.
- *
- * See http://www.php.net/manual/en/ref.soap.php for further details
- * on options for the PHP5 SoapClient which are passed through.
- *
- * Example usage without WSDL:
- *
- * <?php
- *
- * $options = array (
- * 'wsdl' => NULL,
- * 'location' => 'http://your.soap.service/endpoint',
- * 'uri' => 'urn:/Your/Namespace',
- * 'method' => 'checkAuth',
- * 'usernamefield' => 'username',
- * 'passwordfield' => 'password',
- * 'matchpasswords' => false,
- * '_features' => array (
- * 'extra_parameter' => 'example_value',
- * 'another_parameter' => 'foobar'
- * )
- * );
- *
- * $auth = new Auth('SOAP5', $options);
- * $auth->start();
- *
- * ?>
- *
- * Example usage with WSDL:
- *
- * <?php
- *
- * $options = array (
- * 'wsdl' => 'http://your.soap.service/wsdl',
- * 'method' => 'checkAuth',
- * 'usernamefield' => 'username',
- * 'passwordfield' => 'password',
- * 'matchpasswords' => false,
- * '_features' => array (
- * 'extra_parameter' => 'example_value',
- * 'another_parameter' => 'foobar'
- * )
- * );
- *
- * $auth = new Auth('SOAP5', $options);
- * $auth->start();
- *
- * ?>
- *
- * @category Authentication
- * @package Auth
- * @author Based upon Auth_Container_SOAP by Bruno Pedro <bpedro@co.sapo.pt>
- * @author Marcel Oelke <puRe@rednoize.com>
- * @author Adam Ashley <aashley@php.net>
- * @copyright 2001-2006 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version Release: 1.5.4 File: $Revision: 1.1.1.1 $
- * @since Class available since Release 1.4.0
- */
-class Auth_Container_SOAP5 extends Auth_Container
-{
-
- // {{{ properties
-
- /**
- * Required options for the class
- * @var array
- * @access private
- */
- var $_requiredOptions = array(
- 'location',
- 'uri',
- 'method',
- 'usernamefield',
- 'passwordfield',
- 'wsdl',
- );
-
- /**
- * Options for the class
- * @var array
- * @access private
- */
- var $_options = array();
-
- /**
- * Optional SOAP features
- * @var array
- * @access private
- */
- var $_features = array();
-
- /**
- * The SOAP response
- * @var array
- * @access public
- */
- var $soapResponse = array();
-
- // }}}
- // {{{ Auth_Container_SOAP5()
-
- /**
- * Constructor of the container class
- *
- * @param $options, associative array with endpoint, namespace, method,
- * usernamefield, passwordfield and optional features
- */
- function Auth_Container_SOAP5($options)
- {
- $this->_setDefaults();
-
- foreach ($options as $name => $value) {
- $this->_options[$name] = $value;
- }
-
- if (!empty($this->_options['_features'])) {
- $this->_features = $this->_options['_features'];
- unset($this->_options['_features']);
- }
- }
-
- // }}}
- // {{{ fetchData()
-
- /**
- * Fetch data from SOAP service
- *
- * Requests the SOAP service for the given username/password
- * combination.
- *
- * @param string Username
- * @param string Password
- * @return mixed Returns the SOAP response or false if something went wrong
- */
- function fetchData($username, $password)
- {
- $this->log('Auth_Container_SOAP5::fetchData() called.', AUTH_LOG_DEBUG);
- $result = $this->_validateOptions();
- if (PEAR::isError($result))
- return $result;
-
- // create a SOAP client
- $soapClient = new SoapClient($this->_options["wsdl"], $this->_options);
-
- $params = array();
- // first, assign the optional features
- foreach ($this->_features as $fieldName => $fieldValue) {
- $params[$fieldName] = $fieldValue;
- }
- // assign username and password ...
- $params[$this->_options['usernamefield']] = $username;
- $params[$this->_options['passwordfield']] = $password;
-
- try {
- $this->soapResponse = $soapClient->__soapCall($this->_options['method'], $params);
-
- if ($this->_options['matchpasswords']) {
- // check if passwords match
- if ($password == $this->soapResponse[$this->_options['passwordfield']]) {
- return true;
- } else {
- return false;
- }
- } else {
- return true;
- }
- } catch (SoapFault $e) {
- return PEAR::raiseError("Error retrieving authentication data. Received SOAP Fault: ".$e->faultstring, $e->faultcode);
- }
- }
-
- // }}}
- // {{{ _validateOptions()
-
- /**
- * Validate that the options passed to the container class are enough for us to proceed
- *
- * @access private
- * @param array
- */
- function _validateOptions()
- {
- if ( ( is_null($this->_options['wsdl'])
- && is_null($this->_options['location'])
- && is_null($this->_options['uri']))
- || ( is_null($this->_options['wsdl'])
- && ( is_null($this->_options['location'])
- || is_null($this->_options['uri'])))) {
- return PEAR::raiseError('Either a WSDL file or a location/uri pair must be specified.');
- }
- if (is_null($this->_options['method'])) {
- return PEAR::raiseError('A method to call on the soap service must be specified.');
- }
- return true;
- }
-
- // }}}
- // {{{ _setDefaults()
-
- /**
- * Set some default options
- *
- * @access private
- * @return void
- */
- function _setDefaults()
- {
- $this->_options['wsdl'] = null;
- $this->_options['location'] = null;
- $this->_options['uri'] = null;
- $this->_options['method'] = null;
- $this->_options['usernamefield'] = 'username';
- $this->_options['passwordfield'] = 'password';
- $this->_options['matchpasswords'] = true;
- }
-
- // }}}
-
-}
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */
-
-/**
- * Storage driver for use against vpopmail setups
- *
- * PHP versions 4 and 5
- *
- * LICENSE: This source file is subject to version 3.01 of the PHP license
- * that is available through the world-wide-web at the following URI:
- * http://www.php.net/license/3_01.txt. If you did not receive a copy of
- * the PHP License and are unable to obtain it through the web, please
- * send a note to license@php.net so we can mail you a copy immediately.
- *
- * @category Authentication
- * @package Auth
- * @author Stanislav Grozev <tacho@orbitel.bg>
- * @author Adam Ashley <aashley@php.net>
- * @copyright 2001-2006 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version CVS: $Id: vpopmail.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- * @link http://pear.php.net/package/Auth
- * @since File available since Release 1.2.0
- */
-
-/**
- * Include Auth_Container base class
- */
-require_once "Auth/Container.php";
-/**
- * Include PEAR package for error handling
- */
-require_once "PEAR.php";
-
-/**
- * Storage driver for fetching login data from vpopmail
- *
- * @category Authentication
- * @package Auth
- * @author Stanislav Grozev <tacho@orbitel.bg>
- * @author Adam Ashley <aashley@php.net>
- * @copyright 2001-2006 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version Release: 1.5.4 File: $Revision: 1.1.1.1 $
- * @link http://pear.php.net/package/Auth
- * @since Class available since Release 1.2.0
- */
-class Auth_Container_vpopmail extends Auth_Container {
-
- // {{{ Constructor
-
- /**
- * Constructor of the container class
- *
- * @return void
- */
- function Auth_Container_vpopmail()
- {
- if (!extension_loaded('vpopmail')) {
- return PEAR::raiseError('Cannot use VPOPMail authentication, '
- .'VPOPMail extension not loaded!', 41, PEAR_ERROR_DIE);
- }
- }
-
- // }}}
- // {{{ fetchData()
-
- /**
- * Get user information from vpopmail
- *
- * @param string Username - has to be valid email address
- * @param string Password
- * @return boolean
- */
- function fetchData($username, $password)
- {
- $this->log('Auth_Container_vpopmail::fetchData() called.', AUTH_LOG_DEBUG);
- $userdata = array();
- $userdata = preg_split("/@/", $username, 2);
- $result = @vpopmail_auth_user($userdata[0], $userdata[1], $password);
-
- return $result;
- }
-
- // }}}
-
-}
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 foldmethod=marker: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Stig Bakken <ssb@php.net> |
-// | Tomas V.V.Cox <cox@idecnet.com> |
-// | Maintainer: Daniel Convissor <danielc@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: DB.php,v 1.1.1.1 2008/04/28 15:20:46 jamie Exp $
-//
-// Database independent query interface.
-
-
-require_once 'PEAR.php';
-
-// {{{ constants
-// {{{ error codes
-
-/*
- * The method mapErrorCode in each DB_dbtype implementation maps
- * native error codes to one of these.
- *
- * If you add an error code here, make sure you also add a textual
- * version of it in DB::errorMessage().
- */
-define('DB_OK', 1);
-define('DB_ERROR', -1);
-define('DB_ERROR_SYNTAX', -2);
-define('DB_ERROR_CONSTRAINT', -3);
-define('DB_ERROR_NOT_FOUND', -4);
-define('DB_ERROR_ALREADY_EXISTS', -5);
-define('DB_ERROR_UNSUPPORTED', -6);
-define('DB_ERROR_MISMATCH', -7);
-define('DB_ERROR_INVALID', -8);
-define('DB_ERROR_NOT_CAPABLE', -9);
-define('DB_ERROR_TRUNCATED', -10);
-define('DB_ERROR_INVALID_NUMBER', -11);
-define('DB_ERROR_INVALID_DATE', -12);
-define('DB_ERROR_DIVZERO', -13);
-define('DB_ERROR_NODBSELECTED', -14);
-define('DB_ERROR_CANNOT_CREATE', -15);
-define('DB_ERROR_CANNOT_DELETE', -16);
-define('DB_ERROR_CANNOT_DROP', -17);
-define('DB_ERROR_NOSUCHTABLE', -18);
-define('DB_ERROR_NOSUCHFIELD', -19);
-define('DB_ERROR_NEED_MORE_DATA', -20);
-define('DB_ERROR_NOT_LOCKED', -21);
-define('DB_ERROR_VALUE_COUNT_ON_ROW', -22);
-define('DB_ERROR_INVALID_DSN', -23);
-define('DB_ERROR_CONNECT_FAILED', -24);
-define('DB_ERROR_EXTENSION_NOT_FOUND',-25);
-define('DB_ERROR_ACCESS_VIOLATION', -26);
-define('DB_ERROR_NOSUCHDB', -27);
-define('DB_ERROR_CONSTRAINT_NOT_NULL',-29);
-
-
-// }}}
-// {{{ prepared statement-related
-
-
-/*
- * These constants are used when storing information about prepared
- * statements (using the "prepare" method in DB_dbtype).
- *
- * The prepare/execute model in DB is mostly borrowed from the ODBC
- * extension, in a query the "?" character means a scalar parameter.
- * There are two extensions though, a "&" character means an opaque
- * parameter. An opaque parameter is simply a file name, the real
- * data are in that file (useful for putting uploaded files into your
- * database and such). The "!" char means a parameter that must be
- * left as it is.
- * They modify the quote behavoir:
- * DB_PARAM_SCALAR (?) => 'original string quoted'
- * DB_PARAM_OPAQUE (&) => 'string from file quoted'
- * DB_PARAM_MISC (!) => original string
- */
-define('DB_PARAM_SCALAR', 1);
-define('DB_PARAM_OPAQUE', 2);
-define('DB_PARAM_MISC', 3);
-
-
-// }}}
-// {{{ binary data-related
-
-
-/*
- * These constants define different ways of returning binary data
- * from queries. Again, this model has been borrowed from the ODBC
- * extension.
- *
- * DB_BINMODE_PASSTHRU sends the data directly through to the browser
- * when data is fetched from the database.
- * DB_BINMODE_RETURN lets you return data as usual.
- * DB_BINMODE_CONVERT returns data as well, only it is converted to
- * hex format, for example the string "123" would become "313233".
- */
-define('DB_BINMODE_PASSTHRU', 1);
-define('DB_BINMODE_RETURN', 2);
-define('DB_BINMODE_CONVERT', 3);
-
-
-// }}}
-// {{{ fetch modes
-
-
-/**
- * This is a special constant that tells DB the user hasn't specified
- * any particular get mode, so the default should be used.
- */
-define('DB_FETCHMODE_DEFAULT', 0);
-
-/**
- * Column data indexed by numbers, ordered from 0 and up
- */
-define('DB_FETCHMODE_ORDERED', 1);
-
-/**
- * Column data indexed by column names
- */
-define('DB_FETCHMODE_ASSOC', 2);
-
-/**
- * Column data as object properties
- */
-define('DB_FETCHMODE_OBJECT', 3);
-
-/**
- * For multi-dimensional results: normally the first level of arrays
- * is the row number, and the second level indexed by column number or name.
- * DB_FETCHMODE_FLIPPED switches this order, so the first level of arrays
- * is the column name, and the second level the row number.
- */
-define('DB_FETCHMODE_FLIPPED', 4);
-
-/* for compatibility */
-define('DB_GETMODE_ORDERED', DB_FETCHMODE_ORDERED);
-define('DB_GETMODE_ASSOC', DB_FETCHMODE_ASSOC);
-define('DB_GETMODE_FLIPPED', DB_FETCHMODE_FLIPPED);
-
-
-// }}}
-// {{{ tableInfo() && autoPrepare()-related
-
-
-/**
- * these are constants for the tableInfo-function
- * they are bitwised or'ed. so if there are more constants to be defined
- * in the future, adjust DB_TABLEINFO_FULL accordingly
- */
-define('DB_TABLEINFO_ORDER', 1);
-define('DB_TABLEINFO_ORDERTABLE', 2);
-define('DB_TABLEINFO_FULL', 3);
-
-/*
- * Used by autoPrepare()
- */
-define('DB_AUTOQUERY_INSERT', 1);
-define('DB_AUTOQUERY_UPDATE', 2);
-
-
-// }}}
-// {{{ portability modes
-
-
-/**
- * Portability: turn off all portability features.
- * @see DB_common::setOption()
- */
-define('DB_PORTABILITY_NONE', 0);
-
-/**
- * Portability: convert names of tables and fields to lower case
- * when using the get*(), fetch*() and tableInfo() methods.
- * @see DB_common::setOption()
- */
-define('DB_PORTABILITY_LOWERCASE', 1);
-
-/**
- * Portability: right trim the data output by get*() and fetch*().
- * @see DB_common::setOption()
- */
-define('DB_PORTABILITY_RTRIM', 2);
-
-/**
- * Portability: force reporting the number of rows deleted.
- * @see DB_common::setOption()
- */
-define('DB_PORTABILITY_DELETE_COUNT', 4);
-
-/**
- * Portability: enable hack that makes numRows() work in Oracle.
- * @see DB_common::setOption()
- */
-define('DB_PORTABILITY_NUMROWS', 8);
-
-/**
- * Portability: makes certain error messages in certain drivers compatible
- * with those from other DBMS's.
- *
- * + mysql, mysqli: change unique/primary key constraints
- * DB_ERROR_ALREADY_EXISTS -> DB_ERROR_CONSTRAINT
- *
- * + odbc(access): MS's ODBC driver reports 'no such field' as code
- * 07001, which means 'too few parameters.' When this option is on
- * that code gets mapped to DB_ERROR_NOSUCHFIELD.
- *
- * @see DB_common::setOption()
- */
-define('DB_PORTABILITY_ERRORS', 16);
-
-/**
- * Portability: convert null values to empty strings in data output by
- * get*() and fetch*().
- * @see DB_common::setOption()
- */
-define('DB_PORTABILITY_NULL_TO_EMPTY', 32);
-
-/**
- * Portability: turn on all portability features.
- * @see DB_common::setOption()
- */
-define('DB_PORTABILITY_ALL', 63);
-
-// }}}
-
-
-// }}}
-// {{{ class DB
-
-/**
- * The main "DB" class is simply a container class with some static
- * methods for creating DB objects as well as some utility functions
- * common to all parts of DB.
- *
- * The object model of DB is as follows (indentation means inheritance):
- *
- * DB The main DB class. This is simply a utility class
- * with some "static" methods for creating DB objects as
- * well as common utility functions for other DB classes.
- *
- * DB_common The base for each DB implementation. Provides default
- * | implementations (in OO lingo virtual methods) for
- * | the actual DB implementations as well as a bunch of
- * | query utility functions.
- * |
- * +-DB_mysql The DB implementation for MySQL. Inherits DB_common.
- * When calling DB::factory or DB::connect for MySQL
- * connections, the object returned is an instance of this
- * class.
- *
- * @package DB
- * @author Stig Bakken <ssb@php.net>
- * @author Tomas V.V.Cox <cox@idecnet.com>
- * @since PHP 4.0
- * @version $Id: DB.php,v 1.1.1.1 2008/04/28 15:20:46 jamie Exp $
- * @category Database
- */
-class DB
-{
- // {{{ &factory()
-
- /**
- * Create a new DB object for the specified database type.
- *
- * Allows creation of a DB_<driver> object from which the object's
- * methods can be utilized without actually connecting to a database.
- *
- * @param string $type database type, for example "mysql"
- * @param array $options associative array of option names and values
- *
- * @return object a new DB object. On error, an error object.
- *
- * @see DB_common::setOption()
- * @access public
- */
- function &factory($type, $options = false)
- {
- if (!is_array($options)) {
- $options = array('persistent' => $options);
- }
-
- if (isset($options['debug']) && $options['debug'] >= 2) {
- // expose php errors with sufficient debug level
- include_once "DB/{$type}.php";
- } else {
- @include_once "DB/{$type}.php";
- }
-
- $classname = "DB_${type}";
-
- if (!class_exists($classname)) {
- $tmp = PEAR::raiseError(null, DB_ERROR_NOT_FOUND, null, null,
- "Unable to include the DB/{$type}.php file",
- 'DB_Error', true);
- return $tmp;
- }
-
- @$obj =& new $classname;
-
- foreach ($options as $option => $value) {
- $test = $obj->setOption($option, $value);
- if (DB::isError($test)) {
- return $test;
- }
- }
-
- return $obj;
- }
-
- // }}}
- // {{{ &connect()
-
- /**
- * Create a new DB object and connect to the specified database.
- *
- * Example 1.
- * <code> <?php
- * require_once 'DB.php';
- *
- * $dsn = 'mysql://user:password@host/database'
- * $options = array(
- * 'debug' => 2,
- * 'portability' => DB_PORTABILITY_ALL,
- * );
- *
- * $dbh =& DB::connect($dsn, $options);
- * if (DB::isError($dbh)) {
- * die($dbh->getMessage());
- * }
- * ?></code>
- *
- * @param mixed $dsn string "data source name" or an array in the
- * format returned by DB::parseDSN()
- *
- * @param array $options an associative array of option names and
- * their values
- *
- * @return object a newly created DB connection object, or a DB
- * error object on error
- *
- * @see DB::parseDSN(), DB_common::setOption(), DB::isError()
- * @access public
- */
- function &connect($dsn, $options = array())
- {
- $dsninfo = DB::parseDSN($dsn);
- $type = $dsninfo['phptype'];
-
- if (!is_array($options)) {
- /*
- * For backwards compatibility. $options used to be boolean,
- * indicating whether the connection should be persistent.
- */
- $options = array('persistent' => $options);
- }
-
- if (isset($options['debug']) && $options['debug'] >= 2) {
- // expose php errors with sufficient debug level
- include_once "DB/${type}.php";
- } else {
- @include_once "DB/${type}.php";
- }
-
- $classname = "DB_${type}";
- if (!class_exists($classname)) {
- $tmp = PEAR::raiseError(null, DB_ERROR_NOT_FOUND, null, null,
- "Unable to include the DB/{$type}.php file for `$dsn'",
- 'DB_Error', true);
- return $tmp;
- }
-
- @$obj =& new $classname;
-
- foreach ($options as $option => $value) {
- $test = $obj->setOption($option, $value);
- if (DB::isError($test)) {
- return $test;
- }
- }
-
- $err = $obj->connect($dsninfo, $obj->getOption('persistent'));
- if (DB::isError($err)) {
- $err->addUserInfo($dsn);
- return $err;
- }
-
- return $obj;
- }
-
- // }}}
- // {{{ apiVersion()
-
- /**
- * Return the DB API version
- *
- * @return int the DB API version number
- *
- * @access public
- */
- function apiVersion()
- {
- return 2;
- }
-
- // }}}
- // {{{ isError()
-
- /**
- * Tell whether a result code from a DB method is an error
- *
- * @param int $value result code
- *
- * @return bool whether $value is an error
- *
- * @access public
- */
- function isError($value)
- {
- return is_a($value, 'DB_Error');
- }
-
- // }}}
- // {{{ isConnection()
-
- /**
- * Tell whether a value is a DB connection
- *
- * @param mixed $value value to test
- *
- * @return bool whether $value is a DB connection
- *
- * @access public
- */
- function isConnection($value)
- {
- return (is_object($value) &&
- is_subclass_of($value, 'db_common') &&
- method_exists($value, 'simpleQuery'));
- }
-
- // }}}
- // {{{ isManip()
-
- /**
- * Tell whether a query is a data manipulation query (insert,
- * update or delete) or a data definition query (create, drop,
- * alter, grant, revoke).
- *
- * @access public
- *
- * @param string $query the query
- *
- * @return boolean whether $query is a data manipulation query
- */
- function isManip($query)
- {
- $manips = 'INSERT|UPDATE|DELETE|LOAD DATA|'.'REPLACE|CREATE|DROP|'.
- 'ALTER|GRANT|REVOKE|'.'LOCK|UNLOCK';
- if (preg_match('/^\s*"?('.$manips.')\s+/i', $query)) {
- return true;
- }
- return false;
- }
-
- // }}}
- // {{{ errorMessage()
-
- /**
- * Return a textual error message for a DB error code
- *
- * @param integer $value error code
- *
- * @return string error message, or false if the error code was
- * not recognized
- */
- function errorMessage($value)
- {
- static $errorMessages;
- if (!isset($errorMessages)) {
- $errorMessages = array(
- DB_ERROR => 'unknown error',
- DB_ERROR_ALREADY_EXISTS => 'already exists',
- DB_ERROR_CANNOT_CREATE => 'can not create',
- DB_ERROR_CANNOT_DELETE => 'can not delete',
- DB_ERROR_CANNOT_DROP => 'can not drop',
- DB_ERROR_CONSTRAINT => 'constraint violation',
- DB_ERROR_CONSTRAINT_NOT_NULL=> 'null value violates not-null constraint',
- DB_ERROR_DIVZERO => 'division by zero',
- DB_ERROR_INVALID => 'invalid',
- DB_ERROR_INVALID_DATE => 'invalid date or time',
- DB_ERROR_INVALID_NUMBER => 'invalid number',
- DB_ERROR_MISMATCH => 'mismatch',
- DB_ERROR_NODBSELECTED => 'no database selected',
- DB_ERROR_NOSUCHFIELD => 'no such field',
- DB_ERROR_NOSUCHTABLE => 'no such table',
- DB_ERROR_NOT_CAPABLE => 'DB backend not capable',
- DB_ERROR_NOT_FOUND => 'not found',
- DB_ERROR_NOT_LOCKED => 'not locked',
- DB_ERROR_SYNTAX => 'syntax error',
- DB_ERROR_UNSUPPORTED => 'not supported',
- DB_ERROR_VALUE_COUNT_ON_ROW => 'value count on row',
- DB_ERROR_INVALID_DSN => 'invalid DSN',
- DB_ERROR_CONNECT_FAILED => 'connect failed',
- DB_OK => 'no error',
- DB_ERROR_NEED_MORE_DATA => 'insufficient data supplied',
- DB_ERROR_EXTENSION_NOT_FOUND=> 'extension not found',
- DB_ERROR_NOSUCHDB => 'no such database',
- DB_ERROR_ACCESS_VIOLATION => 'insufficient permissions',
- DB_ERROR_TRUNCATED => 'truncated'
- );
- }
-
- if (DB::isError($value)) {
- $value = $value->getCode();
- }
-
- return isset($errorMessages[$value]) ? $errorMessages[$value] : $errorMessages[DB_ERROR];
- }
-
- // }}}
- // {{{ parseDSN()
-
- /**
- * Parse a data source name.
- *
- * Additional keys can be added by appending a URI query string to the
- * end of the DSN.
- *
- * The format of the supplied DSN is in its fullest form:
- * <code>
- * phptype(dbsyntax)://username:password@protocol+hostspec/database?option=8&another=true
- * </code>
- *
- * Most variations are allowed:
- * <code>
- * phptype://username:password@protocol+hostspec:110//usr/db_file.db?mode=0644
- * phptype://username:password@hostspec/database_name
- * phptype://username:password@hostspec
- * phptype://username@hostspec
- * phptype://hostspec/database
- * phptype://hostspec
- * phptype(dbsyntax)
- * phptype
- * </code>
- *
- * @param string $dsn Data Source Name to be parsed
- *
- * @return array an associative array with the following keys:
- * + phptype: Database backend used in PHP (mysql, odbc etc.)
- * + dbsyntax: Database used with regards to SQL syntax etc.
- * + protocol: Communication protocol to use (tcp, unix etc.)
- * + hostspec: Host specification (hostname[:port])
- * + database: Database to use on the DBMS server
- * + username: User name for login
- * + password: Password for login
- *
- * @author Tomas V.V.Cox <cox@idecnet.com>
- */
- function parseDSN($dsn)
- {
- $parsed = array(
- 'phptype' => false,
- 'dbsyntax' => false,
- 'username' => false,
- 'password' => false,
- 'protocol' => false,
- 'hostspec' => false,
- 'port' => false,
- 'socket' => false,
- 'database' => false,
- );
-
- if (is_array($dsn)) {
- $dsn = array_merge($parsed, $dsn);
- if (!$dsn['dbsyntax']) {
- $dsn['dbsyntax'] = $dsn['phptype'];
- }
- return $dsn;
- }
-
- // Find phptype and dbsyntax
- if (($pos = strpos($dsn, '://')) !== false) {
- $str = substr($dsn, 0, $pos);
- $dsn = substr($dsn, $pos + 3);
- } else {
- $str = $dsn;
- $dsn = null;
- }
-
- // Get phptype and dbsyntax
- // $str => phptype(dbsyntax)
- if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
- $parsed['phptype'] = $arr[1];
- $parsed['dbsyntax'] = !$arr[2] ? $arr[1] : $arr[2];
- } else {
- $parsed['phptype'] = $str;
- $parsed['dbsyntax'] = $str;
- }
-
- if (!count($dsn)) {
- return $parsed;
- }
-
- // Get (if found): username and password
- // $dsn => username:password@protocol+hostspec/database
- if (($at = strrpos($dsn,'@')) !== false) {
- $str = substr($dsn, 0, $at);
- $dsn = substr($dsn, $at + 1);
- if (($pos = strpos($str, ':')) !== false) {
- $parsed['username'] = rawurldecode(substr($str, 0, $pos));
- $parsed['password'] = rawurldecode(substr($str, $pos + 1));
- } else {
- $parsed['username'] = rawurldecode($str);
- }
- }
-
- // Find protocol and hostspec
-
- // $dsn => proto(proto_opts)/database
- if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) {
- $proto = $match[1];
- $proto_opts = $match[2] ? $match[2] : false;
- $dsn = $match[3];
-
- // $dsn => protocol+hostspec/database (old format)
- } else {
- if (strpos($dsn, '+') !== false) {
- list($proto, $dsn) = explode('+', $dsn, 2);
- }
- if (strpos($dsn, '/') !== false) {
- list($proto_opts, $dsn) = explode('/', $dsn, 2);
- } else {
- $proto_opts = $dsn;
- $dsn = null;
- }
- }
-
- // process the different protocol options
- $parsed['protocol'] = (!empty($proto)) ? $proto : 'tcp';
- $proto_opts = rawurldecode($proto_opts);
- if ($parsed['protocol'] == 'tcp') {
- if (strpos($proto_opts, ':') !== false) {
- list($parsed['hostspec'], $parsed['port']) = explode(':', $proto_opts);
- } else {
- $parsed['hostspec'] = $proto_opts;
- }
- } elseif ($parsed['protocol'] == 'unix') {
- $parsed['socket'] = $proto_opts;
- }
-
- // Get dabase if any
- // $dsn => database
- if ($dsn) {
- // /database
- if (($pos = strpos($dsn, '?')) === false) {
- $parsed['database'] = $dsn;
- // /database?param1=value1¶m2=value2
- } else {
- $parsed['database'] = substr($dsn, 0, $pos);
- $dsn = substr($dsn, $pos + 1);
- if (strpos($dsn, '&') !== false) {
- $opts = explode('&', $dsn);
- } else { // database?param1=value1
- $opts = array($dsn);
- }
- foreach ($opts as $opt) {
- list($key, $value) = explode('=', $opt);
- if (!isset($parsed[$key])) {
- // don't allow params overwrite
- $parsed[$key] = rawurldecode($value);
- }
- }
- }
- }
-
- return $parsed;
- }
-
- // }}}
- // {{{ assertExtension()
-
- /**
- * Load a PHP database extension if it is not loaded already.
- *
- * @access public
- *
- * @param string $name the base name of the extension (without the .so or
- * .dll suffix)
- *
- * @return boolean true if the extension was already or successfully
- * loaded, false if it could not be loaded
- */
- function assertExtension($name)
- {
- if (!extension_loaded($name)) {
- $dlext = OS_WINDOWS ? '.dll' : '.so';
- $dlprefix = OS_WINDOWS ? 'php_' : '';
- @dl($dlprefix . $name . $dlext);
- return extension_loaded($name);
- }
- return true;
- }
- // }}}
-}
-
-// }}}
-// {{{ class DB_Error
-
-/**
- * DB_Error implements a class for reporting portable database error
- * messages.
- *
- * @package DB
- * @author Stig Bakken <ssb@php.net>
- */
-class DB_Error extends PEAR_Error
-{
- // {{{ constructor
-
- /**
- * DB_Error constructor.
- *
- * @param mixed $code DB error code, or string with error message.
- * @param integer $mode what "error mode" to operate in
- * @param integer $level what error level to use for $mode & PEAR_ERROR_TRIGGER
- * @param mixed $debuginfo additional debug info, such as the last query
- *
- * @access public
- *
- * @see PEAR_Error
- */
- function DB_Error($code = DB_ERROR, $mode = PEAR_ERROR_RETURN,
- $level = E_USER_NOTICE, $debuginfo = null)
- {
- if (is_int($code)) {
- $this->PEAR_Error('DB Error: ' . DB::errorMessage($code), $code, $mode, $level, $debuginfo);
- } else {
- $this->PEAR_Error("DB Error: $code", DB_ERROR, $mode, $level, $debuginfo);
- }
- }
- // }}}
-}
-
-// }}}
-// {{{ class DB_result
-
-/**
- * This class implements a wrapper for a DB result set.
- * A new instance of this class will be returned by the DB implementation
- * after processing a query that returns data.
- *
- * @package DB
- * @author Stig Bakken <ssb@php.net>
- */
-class DB_result
-{
- // {{{ properties
-
- var $dbh;
- var $result;
- var $row_counter = null;
-
- /**
- * for limit queries, the row to start fetching
- * @var integer
- */
- var $limit_from = null;
-
- /**
- * for limit queries, the number of rows to fetch
- * @var integer
- */
- var $limit_count = null;
-
- // }}}
- // {{{ constructor
-
- /**
- * DB_result constructor.
- * @param resource &$dbh DB object reference
- * @param resource $result result resource id
- * @param array $options assoc array with optional result options
- */
- function DB_result(&$dbh, $result, $options = array())
- {
- $this->dbh = &$dbh;
- $this->result = $result;
- foreach ($options as $key => $value) {
- $this->setOption($key, $value);
- }
- $this->limit_type = $dbh->features['limit'];
- $this->autofree = $dbh->options['autofree'];
- $this->fetchmode = $dbh->fetchmode;
- $this->fetchmode_object_class = $dbh->fetchmode_object_class;
- }
-
- function setOption($key, $value = null)
- {
- switch ($key) {
- case 'limit_from':
- $this->limit_from = $value; break;
- case 'limit_count':
- $this->limit_count = $value; break;
- }
- }
-
- // }}}
- // {{{ fetchRow()
-
- /**
- * Fetch a row of data and return it by reference into an array.
- *
- * The type of array returned can be controlled either by setting this
- * method's <var>$fetchmode</var> parameter or by changing the default
- * fetch mode setFetchMode() before calling this method.
- *
- * There are two options for standardizing the information returned
- * from databases, ensuring their values are consistent when changing
- * DBMS's. These portability options can be turned on when creating a
- * new DB object or by using setOption().
- *
- * + <samp>DB_PORTABILITY_LOWERCASE</samp>
- * convert names of fields to lower case
- *
- * + <samp>DB_PORTABILITY_RTRIM</samp>
- * right trim the data
- *
- * @param int $fetchmode how the resulting array should be indexed
- * @param int $rownum the row number to fetch
- *
- * @return array a row of data, null on no more rows or PEAR_Error
- * object on error
- *
- * @see DB_common::setOption(), DB_common::setFetchMode()
- * @access public
- */
- function &fetchRow($fetchmode = DB_FETCHMODE_DEFAULT, $rownum=null)
- {
- if ($fetchmode === DB_FETCHMODE_DEFAULT) {
- $fetchmode = $this->fetchmode;
- }
- if ($fetchmode === DB_FETCHMODE_OBJECT) {
- $fetchmode = DB_FETCHMODE_ASSOC;
- $object_class = $this->fetchmode_object_class;
- }
- if ($this->limit_from !== null) {
- if ($this->row_counter === null) {
- $this->row_counter = $this->limit_from;
- // Skip rows
- if ($this->limit_type == false) {
- $i = 0;
- while ($i++ < $this->limit_from) {
- $this->dbh->fetchInto($this->result, $arr, $fetchmode);
- }
- }
- }
- if ($this->row_counter >= (
- $this->limit_from + $this->limit_count))
- {
- if ($this->autofree) {
- $this->free();
- }
- $tmp = null;
- return $tmp;
- }
- if ($this->limit_type == 'emulate') {
- $rownum = $this->row_counter;
- }
- $this->row_counter++;
- }
- $res = $this->dbh->fetchInto($this->result, $arr, $fetchmode, $rownum);
- if ($res === DB_OK) {
- if (isset($object_class)) {
- // default mode specified in DB_common::fetchmode_object_class property
- if ($object_class == 'stdClass') {
- $arr = (object) $arr;
- } else {
- $arr = &new $object_class($arr);
- }
- }
- return $arr;
- }
- if ($res == null && $this->autofree) {
- $this->free();
- }
- return $res;
- }
-
- // }}}
- // {{{ fetchInto()
-
- /**
- * Fetch a row of data into an array which is passed by reference.
- *
- * The type of array returned can be controlled either by setting this
- * method's <var>$fetchmode</var> parameter or by changing the default
- * fetch mode setFetchMode() before calling this method.
- *
- * There are two options for standardizing the information returned
- * from databases, ensuring their values are consistent when changing
- * DBMS's. These portability options can be turned on when creating a
- * new DB object or by using setOption().
- *
- * + <samp>DB_PORTABILITY_LOWERCASE</samp>
- * convert names of fields to lower case
- *
- * + <samp>DB_PORTABILITY_RTRIM</samp>
- * right trim the data
- *
- * @param array &$arr (reference) array where data from the row
- * should be placed
- * @param int $fetchmode how the resulting array should be indexed
- * @param int $rownum the row number to fetch
- *
- * @return mixed DB_OK on success, null on no more rows or
- * a DB_Error object on error
- *
- * @see DB_common::setOption(), DB_common::setFetchMode()
- * @access public
- */
- function fetchInto(&$arr, $fetchmode = DB_FETCHMODE_DEFAULT, $rownum=null)
- {
- if ($fetchmode === DB_FETCHMODE_DEFAULT) {
- $fetchmode = $this->fetchmode;
- }
- if ($fetchmode === DB_FETCHMODE_OBJECT) {
- $fetchmode = DB_FETCHMODE_ASSOC;
- $object_class = $this->fetchmode_object_class;
- }
- if ($this->limit_from !== null) {
- if ($this->row_counter === null) {
- $this->row_counter = $this->limit_from;
- // Skip rows
- if ($this->limit_type == false) {
- $i = 0;
- while ($i++ < $this->limit_from) {
- $this->dbh->fetchInto($this->result, $arr, $fetchmode);
- }
- }
- }
- if ($this->row_counter >= (
- $this->limit_from + $this->limit_count))
- {
- if ($this->autofree) {
- $this->free();
- }
- return null;
- }
- if ($this->limit_type == 'emulate') {
- $rownum = $this->row_counter;
- }
-
- $this->row_counter++;
- }
- $res = $this->dbh->fetchInto($this->result, $arr, $fetchmode, $rownum);
- if ($res === DB_OK) {
- if (isset($object_class)) {
- // default mode specified in DB_common::fetchmode_object_class property
- if ($object_class == 'stdClass') {
- $arr = (object) $arr;
- } else {
- $arr = new $object_class($arr);
- }
- }
- return DB_OK;
- }
- if ($res == null && $this->autofree) {
- $this->free();
- }
- return $res;
- }
-
- // }}}
- // {{{ numCols()
-
- /**
- * Get the the number of columns in a result set.
- *
- * @return int the number of columns, or a DB error
- *
- * @access public
- */
- function numCols()
- {
- return $this->dbh->numCols($this->result);
- }
-
- // }}}
- // {{{ numRows()
-
- /**
- * Get the number of rows in a result set.
- *
- * @return int the number of rows, or a DB error
- *
- * @access public
- */
- function numRows()
- {
- return $this->dbh->numRows($this->result);
- }
-
- // }}}
- // {{{ nextResult()
-
- /**
- * Get the next result if a batch of queries was executed.
- *
- * @return bool true if a new result is available or false if not.
- *
- * @access public
- */
- function nextResult()
- {
- return $this->dbh->nextResult($this->result);
- }
-
- // }}}
- // {{{ free()
-
- /**
- * Frees the resources allocated for this result set.
- * @return int error code
- *
- * @access public
- */
- function free()
- {
- $err = $this->dbh->freeResult($this->result);
- if (DB::isError($err)) {
- return $err;
- }
- $this->result = false;
- return true;
- }
-
- // }}}
- // {{{ tableInfo()
-
- /**
- * @deprecated
- * @internal
- * @see DB_common::tableInfo()
- */
- function tableInfo($mode = null)
- {
- if (is_string($mode)) {
- return $this->dbh->raiseError(DB_ERROR_NEED_MORE_DATA);
- }
- return $this->dbh->tableInfo($this, $mode);
- }
-
- // }}}
- // {{{ getRowCounter()
-
- /**
- * returns the actual row number
- * @return integer
- */
- function getRowCounter()
- {
- return $this->row_counter;
- }
- // }}}
-}
-
-// }}}
-// {{{ class DB_row
-
-/**
- * Pear DB Row Object
- * @see DB_common::setFetchMode()
- */
-class DB_row
-{
- // {{{ constructor
-
- /**
- * constructor
- *
- * @param resource row data as array
- */
- function DB_row(&$arr)
- {
- foreach ($arr as $key => $value) {
- $this->$key = &$arr[$key];
- }
- }
-
- // }}}
-}
-
-// }}}
-
-/*
- * Local variables:
- * tab-width: 4
- * c-basic-offset: 4
- * End:
- */
-
-?>
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Alan Knowles <alan@akbkhome.com>
-// +----------------------------------------------------------------------+
-/**
- * Object Based Database Query Builder and data store
- *
- * @package DB_DataObject
- * @category DB
- *
- * $Id: DataObject.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
- */
-
-/* ===========================================================================
-*
-* !!!!!!!!!!!!! W A R N I N G !!!!!!!!!!!
-*
-* THIS MAY SEGFAULT PHP IF YOU ARE USING THE ZEND OPTIMIZER (to fix it,
-* just add "define('DB_DATAOBJECT_NO_OVERLOAD',true);" before you include
-* this file. reducing the optimization level may also solve the segfault.
-* ===========================================================================
-*/
-
-/**
- * The main "DB_DataObject" class is really a base class for your own tables classes
- *
- * // Set up the class by creating an ini file (refer to the manual for more details
- * [DB_DataObject]
- * database = mysql:/username:password@host/database
- * schema_location = /home/myapplication/database
- * class_location = /home/myapplication/DBTables/
- * clase_prefix = DBTables_
- *
- *
- * //Start and initialize...................... - dont forget the &
- * $config = parse_ini_file('example.ini',true);
- * $options = &PEAR::getStaticProperty('DB_DataObject','options');
- * $options = $config['DB_DataObject'];
- *
- * // example of a class (that does not use the 'auto generated tables data')
- * class mytable extends DB_DataObject {
- * // mandatory - set the table
- * var $_database_dsn = "mysql://username:password@localhost/database";
- * var $__table = "mytable";
- * function table() {
- * return array(
- * 'id' => 1, // integer or number
- * 'name' => 2, // string
- * );
- * }
- * function keys() {
- * return array('id');
- * }
- * }
- *
- * // use in the application
- *
- *
- * Simple get one row
- *
- * $instance = new mytable;
- * $instance->get("id",12);
- * echo $instance->somedata;
- *
- *
- * Get multiple rows
- *
- * $instance = new mytable;
- * $instance->whereAdd("ID > 12");
- * $instance->whereAdd("ID < 14");
- * $instance->find();
- * while ($instance->fetch()) {
- * echo $instance->somedata;
- * }
-
-
-/**
- * Needed classes
- * - we use getStaticProperty from PEAR pretty extensively (cant remove it ATM)
- */
-
-require_once 'PEAR.php';
-
-/**
- * these are constants for the get_table array
- * user to determine what type of escaping is required around the object vars.
- */
-define('DB_DATAOBJECT_INT', 1); // does not require ''
-define('DB_DATAOBJECT_STR', 2); // requires ''
-
-define('DB_DATAOBJECT_DATE', 4); // is date #TODO
-define('DB_DATAOBJECT_TIME', 8); // is time #TODO
-define('DB_DATAOBJECT_BOOL', 16); // is boolean #TODO
-define('DB_DATAOBJECT_TXT', 32); // is long text #TODO
-define('DB_DATAOBJECT_BLOB', 64); // is blob type
-
-
-define('DB_DATAOBJECT_NOTNULL', 128); // not null col.
-define('DB_DATAOBJECT_MYSQLTIMESTAMP' , 256); // mysql timestamps (ignored by update/insert)
-/*
- * Define this before you include DataObjects.php to disable overload - if it segfaults due to Zend optimizer..
- */
-//define('DB_DATAOBJECT_NO_OVERLOAD',true)
-
-
-/**
- * Theses are the standard error codes, most methods will fail silently - and return false
- * to access the error message either use $table->_lastError
- * or $last_error = PEAR::getStaticProperty('DB_DataObject','lastError');
- * the code is $last_error->code, and the message is $last_error->message (a standard PEAR error)
- */
-
-define('DB_DATAOBJECT_ERROR_INVALIDARGS', -1); // wrong args to function
-define('DB_DATAOBJECT_ERROR_NODATA', -2); // no data available
-define('DB_DATAOBJECT_ERROR_INVALIDCONFIG', -3); // something wrong with the config
-define('DB_DATAOBJECT_ERROR_NOCLASS', -4); // no class exists
-define('DB_DATAOBJECT_ERROR_NOTSUPPORTED' ,-6); // limit queries on unsuppored databases
-define('DB_DATAOBJECT_ERROR_INVALID_CALL' ,-7); // overlad getter/setter failure
-
-/**
- * Used in methods like delete() and count() to specify that the method should
- * build the condition only out of the whereAdd's and not the object parameters.
- */
-define('DB_DATAOBJECT_WHEREADD_ONLY', true);
-
-/**
- *
- * storage for connection and result objects,
- * it is done this way so that print_r()'ing the is smaller, and
- * it reduces the memory size of the object.
- * -- future versions may use $this->_connection = & PEAR object..
- * although will need speed tests to see how this affects it.
- * - includes sub arrays
- * - connections = md5 sum mapp to pear db object
- * - results = [id] => map to pear db object
- * - resultseq = sequence id for results & results field
- * - resultfields = [id] => list of fields return from query (for use with toArray())
- * - ini = mapping of database to ini file results
- * - links = mapping of database to links file
- * - lasterror = pear error objects for last error event.
- * - config = aliased view of PEAR::getStaticPropery('DB_DataObject','options') * done for performance.
- * - array of loaded classes by autoload method - to stop it doing file access request over and over again!
- */
-$GLOBALS['_DB_DATAOBJECT']['RESULTS'] = array();
-$GLOBALS['_DB_DATAOBJECT']['RESULTSEQ'] = 1;
-$GLOBALS['_DB_DATAOBJECT']['RESULTFIELDS'] = array();
-$GLOBALS['_DB_DATAOBJECT']['CONNECTIONS'] = array();
-$GLOBALS['_DB_DATAOBJECT']['INI'] = array();
-$GLOBALS['_DB_DATAOBJECT']['LINKS'] = array();
-$GLOBALS['_DB_DATAOBJECT']['SEQUENCE'] = array();
-$GLOBALS['_DB_DATAOBJECT']['LASTERROR'] = null;
-$GLOBALS['_DB_DATAOBJECT']['CONFIG'] = array();
-$GLOBALS['_DB_DATAOBJECT']['CACHE'] = array();
-$GLOBALS['_DB_DATAOBJECT']['OVERLOADED'] = false;
-$GLOBALS['_DB_DATAOBJECT']['QUERYENDTIME'] = 0;
-
-
-
-// this will be horrifically slow!!!!
-// NOTE: Overload SEGFAULTS ON PHP4 + Zend Optimizer (see define before..)
-// these two are BC/FC handlers for call in PHP4/5
-
-if ( substr(phpversion(),0,1) == 5) {
- class DB_DataObject_Overload {
- function __call($method,$args) {
- $return = null;
- $this->_call($method,$args,$return);
- return $return;
- }
- }
-} else {
- if (!function_exists('clone')) {
- eval('function clone($t) { return $t; }');
- }
- eval('
- class DB_DataObject_Overload {
- function __call($method,$args,&$return) {
- return $this->_call($method,$args,$return);
- }
- }
- ');
-}
-
-
-
-
-
-
- /*
- *
- * @package DB_DataObject
- * @author Alan Knowles <alan@akbkhome.com>
- * @since PHP 4.0
- */
-
-class DB_DataObject extends DB_DataObject_Overload
-{
- /**
- * The Version - use this to check feature changes
- *
- * @access private
- * @var string
- */
- var $_DB_DataObject_version = "1.7.2";
-
- /**
- * The Database table (used by table extends)
- *
- * @access private
- * @var string
- */
- var $__table = ''; // database table
-
- /**
- * The Number of rows returned from a query
- *
- * @access public
- * @var int
- */
- var $N = 0; // Number of rows returned from a query
-
-
- /* ============================================================= */
- /* Major Public Methods */
- /* (designed to be optionally then called with parent::method()) */
- /* ============================================================= */
-
-
- /**
- * Get a result using key, value.
- *
- * for example
- * $object->get("ID",1234);
- * Returns Number of rows located (usually 1) for success,
- * and puts all the table columns into this classes variables
- *
- * see the fetch example on how to extend this.
- *
- * if no value is entered, it is assumed that $key is a value
- * and get will then use the first key in keys()
- * to obtain the key.
- *
- * @param string $k column
- * @param string $v value
- * @access public
- * @return int No. of rows
- */
- function get($k = null, $v = null)
- {
- global $_DB_DATAOBJECT;
- if (empty($_DB_DATAOBJECT['CONFIG'])) {
- DB_DataObject::_loadConfig();
- }
- $keys = array();
-
- if ($v === null) {
- $v = $k;
- $keys = $this->keys();
- if (!$keys) {
- $this->raiseError("No Keys available for {$this->__table}", DB_DATAOBJECT_ERROR_INVALIDCONFIG);
- return false;
- }
- $k = $keys[0];
- }
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug("$k $v " .print_r($keys,true), "GET");
- }
-
- if ($v === null) {
- $this->raiseError("No Value specified for get", DB_DATAOBJECT_ERROR_INVALIDARGS);
- return false;
- }
- $this->$k = $v;
- return $this->find(1);
- }
-
- /**
- * An autoloading, caching static get method using key, value (based on get)
- *
- * Usage:
- * $object = DB_DataObject::staticGet("DbTable_mytable",12);
- * or
- * $object = DB_DataObject::staticGet("DbTable_mytable","name","fred");
- *
- * or write it into your extended class:
- * function &staticGet($k,$v=NULL) { return DB_DataObject::staticGet("This_Class",$k,$v); }
- *
- * @param string $class class name
- * @param string $k column (or value if using keys)
- * @param string $v value (optional)
- * @access public
- * @return object
- */
- function &staticGet($class, $k, $v = null)
- {
- $lclass = strtolower($class);
- global $_DB_DATAOBJECT;
- if (empty($_DB_DATAOBJECT['CONFIG'])) {
- DB_DataObject::_loadConfig();
- }
-
-
-
- $key = "$k:$v";
- if ($v === null) {
- $key = $k;
- }
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- DB_DataObject::debug("$class $key","STATIC GET - TRY CACHE");
- }
- if (!empty($_DB_DATAOBJECT['CACHE'][$lclass][$key])) {
- return $_DB_DATAOBJECT['CACHE'][$lclass][$key];
- }
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- DB_DataObject::debug("$class $key","STATIC GET - NOT IN CACHE");
- }
-
- $obj = DB_DataObject::factory(substr($class,strlen($_DB_DATAOBJECT['CONFIG']['class_prefix'])));
- if (PEAR::isError($obj)) {
- DB_DataObject::raiseError("could not autoload $class", DB_DATAOBJECT_ERROR_NOCLASS);
- return false;
- }
-
- if (!isset($_DB_DATAOBJECT['CACHE'][$lclass])) {
- $_DB_DATAOBJECT['CACHE'][$lclass] = array();
- }
- if (!$obj->get($k,$v)) {
- DB_DataObject::raiseError("No Data return from get $k $v", DB_DATAOBJECT_ERROR_NODATA);
- return false;
- }
- $_DB_DATAOBJECT['CACHE'][$lclass][$key] = $obj;
- return $_DB_DATAOBJECT['CACHE'][$lclass][$key];
- }
-
- /**
- * find results, either normal or crosstable
- *
- * for example
- *
- * $object = new mytable();
- * $object->ID = 1;
- * $object->find();
- *
- *
- * will set $object->N to number of rows, and expects next command to fetch rows
- * will return $object->N
- *
- * @param boolean $n Fetch first result
- * @access public
- * @return int
- */
- function find($n = false)
- {
- global $_DB_DATAOBJECT;
- if (!isset($this->_query)) {
- $this->raiseError(
- "You cannot do two queries on the same object (copy it before finding)",
- DB_DATAOBJECT_ERROR_INVALIDARGS);
- return false;
- }
-
- if (empty($_DB_DATAOBJECT['CONFIG'])) {
- DB_DataObject::_loadConfig();
- }
-
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug($n, "__find",1);
- }
- if (!$this->__table) {
- echo "NO \$__table SPECIFIED in class definition";
- exit;
- }
- $this->N = 0;
- $query_before = $this->_query;
- $this->_build_condition($this->table()) ;
-
- $quoteIdentifiers = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
- $this->_connect();
- $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
-
-
- $this->_query('SELECT ' .
- $this->_query['data_select'] .
- ' FROM ' . ($quoteIdentifiers ? $DB->quoteIdentifier($this->__table) : $this->__table) . " " .
- $this->_join .
- $this->_query['condition'] . ' '.
- $this->_query['group_by'] . ' '.
- $this->_query['having'] . ' '.
- $this->_query['order_by'] . ' '.
-
- $this->_query['limit']); // is select
-
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug("CHECK autofetchd $n", "__find", 1);
- }
- // unset the
-
-
- if ($n && $this->N > 0 ) {
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug("ABOUT TO AUTOFETCH", "__find", 1);
- }
- $this->fetch() ;
- }
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug("DONE", "__find", 1);
- }
- $this->_query = $query_before;
- return $this->N;
- }
-
- /**
- * fetches next row into this objects var's
- *
- * returns 1 on success 0 on failure
- *
- *
- *
- * Example
- * $object = new mytable();
- * $object->name = "fred";
- * $object->find();
- * $store = array();
- * while ($object->fetch()) {
- * echo $this->ID;
- * $store[] = $object; // builds an array of object lines.
- * }
- *
- * to add features to a fetch
- * function fetch () {
- * $ret = parent::fetch();
- * $this->date_formated = date('dmY',$this->date);
- * return $ret;
- * }
- *
- * @access public
- * @return boolean on success
- */
- function fetch()
- {
-
- global $_DB_DATAOBJECT;
- if (empty($_DB_DATAOBJECT['CONFIG'])) {
- DB_DataObject::_loadConfig();
- }
- if (empty($this->N)) {
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug("No data returned from FIND (eg. N is 0)","FETCH", 3);
- }
- return false;
- }
-
- if (empty($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid]) ||
- !is_object($result = &$_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid]))
- {
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug('fetched on object after fetch completed (no results found)');
- }
- return false;
- }
-
-
- $array = $result->fetchRow(DB_FETCHMODE_ASSOC);
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug(serialize($array),"FETCH");
- }
-
- if ($array === null) {
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $t= explode(' ',microtime());
-
- $this->debug("Last Data Fetch'ed after " .
- ($t[0]+$t[1]- $_DB_DATAOBJECT['QUERYENDTIME'] ) .
- " seconds",
- "FETCH", 1);
- }
- // reduce the memory usage a bit... (but leave the id in, so count() works ok on it)
- unset($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid]);
-
- // this is probably end of data!!
- //DB_DataObject::raiseError("fetch: no data returned", DB_DATAOBJECT_ERROR_NODATA);
- return false;
- }
-
- if (!isset($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid])) {
- // note: we dont declare this to keep the print_r size down.
- $_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid]= array_flip(array_keys($array));
- }
-
- foreach($array as $k=>$v) {
- $kk = str_replace(".", "_", $k);
- $kk = str_replace(" ", "_", $kk);
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug("$kk = ". $array[$k], "fetchrow LINE", 3);
- }
- $this->$kk = $array[$k];
- }
-
- // set link flag
- $this->_link_loaded=false;
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug("{$this->__table} DONE", "fetchrow",2);
- }
- if (isset($this->_query) && empty($_DB_DATAOBJECT['CONFIG']['keep_query_after_fetch'])) {
- unset($this->_query);
- }
- return true;
- }
-
- /**
- * Adds a condition to the WHERE statement, defaults to AND
- *
- * $object->whereAdd(); //reset or cleaer ewhwer
- * $object->whereAdd("ID > 20");
- * $object->whereAdd("age > 20","OR");
- *
- * @param string $cond condition
- * @param string $logic optional logic "OR" (defaults to "AND")
- * @access public
- * @return string|PEAR::Error - previous condition or Error when invalid args found
- */
- function whereAdd($cond = false, $logic = 'AND')
- {
- if (!isset($this->_query)) {
- return $this->raiseError(
- "You cannot do two queries on the same object (clone it before finding)",
- DB_DATAOBJECT_ERROR_INVALIDARGS);
- }
-
- if ($cond === false) {
- $r = $this->_query['condition'];
- $this->_query['condition'] = '';
- return $r;
- }
- // check input...= 0 or ' ' == error!
- if (!trim($cond)) {
- return $this->raiseError("WhereAdd: No Valid Arguments", DB_DATAOBJECT_ERROR_INVALIDARGS);
- }
- $r = $this->_query['condition'];
- if ($this->_query['condition']) {
- $this->_query['condition'] .= " {$logic} {$cond}";
- return $r;
- }
- $this->_query['condition'] = " WHERE {$cond}";
- return $r;
- }
-
- /**
- * Adds a order by condition
- *
- * $object->orderBy(); //clears order by
- * $object->orderBy("ID");
- * $object->orderBy("ID,age");
- *
- * @param string $order Order
- * @access public
- * @return none|PEAR::Error - invalid args only
- */
- function orderBy($order = false)
- {
- if (!isset($this->_query)) {
- $this->raiseError(
- "You cannot do two queries on the same object (copy it before finding)",
- DB_DATAOBJECT_ERROR_INVALIDARGS);
- return false;
- }
- if ($order === false) {
- $this->_query['order_by'] = '';
- return;
- }
- // check input...= 0 or ' ' == error!
- if (!trim($order)) {
- return $this->raiseError("orderBy: No Valid Arguments", DB_DATAOBJECT_ERROR_INVALIDARGS);
- }
-
- if (!$this->_query['order_by']) {
- $this->_query['order_by'] = " ORDER BY {$order} ";
- return;
- }
- $this->_query['order_by'] .= " , {$order}";
- }
-
- /**
- * Adds a group by condition
- *
- * $object->groupBy(); //reset the grouping
- * $object->groupBy("ID DESC");
- * $object->groupBy("ID,age");
- *
- * @param string $group Grouping
- * @access public
- * @return none|PEAR::Error - invalid args only
- */
- function groupBy($group = false)
- {
- if (!isset($this->_query)) {
- $this->raiseError(
- "You cannot do two queries on the same object (copy it before finding)",
- DB_DATAOBJECT_ERROR_INVALIDARGS);
- return false;
- }
- if ($group === false) {
- $this->_query['group_by'] = '';
- return;
- }
- // check input...= 0 or ' ' == error!
- if (!trim($group)) {
- return $this->raiseError("groupBy: No Valid Arguments", DB_DATAOBJECT_ERROR_INVALIDARGS);
- }
-
-
- if (!$this->_query['group_by']) {
- $this->_query['group_by'] = " GROUP BY {$group} ";
- return;
- }
- $this->_query['group_by'] .= " , {$group}";
- }
-
- /**
- * Adds a having clause
- *
- * $object->having(); //reset the grouping
- * $object->having("sum(value) > 0 ");
- *
- * @param string $having condition
- * @access public
- * @return none|PEAR::Error - invalid args only
- */
- function having($having = false)
- {
- if (!isset($this->_query)) {
- $this->raiseError(
- "You cannot do two queries on the same object (copy it before finding)",
- DB_DATAOBJECT_ERROR_INVALIDARGS);
- return false;
- }
- if ($having === false) {
- $this->_query['having'] = '';
- return;
- }
- // check input...= 0 or ' ' == error!
- if (!trim($having)) {
- return $this->raiseError("Having: No Valid Arguments", DB_DATAOBJECT_ERROR_INVALIDARGS);
- }
-
-
- if (!$this->_query['having']) {
- $this->_query['having'] = " HAVING {$having} ";
- return;
- }
- $this->_query['having'] .= " , {$having}";
- }
-
- /**
- * Sets the Limit
- *
- * $boject->limit(); // clear limit
- * $object->limit(12);
- * $object->limit(12,10);
- *
- * Note this will emit an error on databases other than mysql/postgress
- * as there is no 'clean way' to implement it. - you should consider refering to
- * your database manual to decide how you want to implement it.
- *
- * @param string $a limit start (or number), or blank to reset
- * @param string $b number
- * @access public
- * @return none|PEAR::Error - invalid args only
- */
- function limit($a = null, $b = null)
- {
- if (!isset($this->_query)) {
- $this->raiseError(
- "You cannot do two queries on the same object (copy it before finding)",
- DB_DATAOBJECT_ERROR_INVALIDARGS);
- return false;
- }
-
- if ($a === null) {
- $this->_query['limit'] = '';
- return;
- }
- // check input...= 0 or ' ' == error!
- if ((!is_int($a) && ((string)((int)$a) !== (string)$a))
- || (($b !== null) && (!is_int($b) && ((string)((int)$b) !== (string)$b)))) {
- return $this->raiseError("limit: No Valid Arguments", DB_DATAOBJECT_ERROR_INVALIDARGS);
- }
- global $_DB_DATAOBJECT;
- $this->_connect();
- $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
-
- if (($DB->features['limit'] == 'alter') && ($DB->phptype != 'oci8')) {
- if ($b === null) {
- $this->_query['limit'] = " LIMIT $a";
- return;
- }
-
- $this->_query['limit'] = $DB->modifyLimitQuery('',$a,$b);
-
- } else {
- $this->raiseError(
- "DB_DataObjects only supports limit queries on some databases,\n".
- "Check with pear bugs for the package, or the dataobjects manual.\n",
- "or Refer to your Database manual to find out how to do limit queries manually.\n",
- DB_DATAOBJECT_ERROR_NOTSUPPORTED, PEAR_ERROR_DIE);
- }
- }
-
- /**
- * Adds a select columns
- *
- * $object->selectAdd(); // resets select to nothing!
- * $object->selectAdd("*"); // default select
- * $object->selectAdd("unixtime(DATE) as udate");
- * $object->selectAdd("DATE");
- *
- * to prepend distict:
- * $object->selectAdd('distinct ' . $object->selectAdd());
- *
- * @param string $k
- * @access public
- * @return mixed null or old string if you reset it.
- */
- function selectAdd($k = null)
- {
- if (!isset($this->_query)) {
- $this->raiseError(
- "You cannot do two queries on the same object (copy it before finding)",
- DB_DATAOBJECT_ERROR_INVALIDARGS);
- return false;
- }
- if ($k === null) {
- $old = $this->_query['data_select'];
- $this->_query['data_select'] = '';
- return $old;
- }
-
- // check input...= 0 or ' ' == error!
- if (!trim($k)) {
- return $this->raiseError("selectAdd: No Valid Arguments", DB_DATAOBJECT_ERROR_INVALIDARGS);
- }
-
- if ($this->_query['data_select']) {
- $this->_query['data_select'] .= ', ';
- }
- $this->_query['data_select'] .= " $k ";
- }
- /**
- * Adds multiple Columns or objects to select with formating.
- *
- * $object->selectAs(null); // adds "table.colnameA as colnameA,table.colnameB as colnameB,......"
- * // note with null it will also clear the '*' default select
- * $object->selectAs(array('a','b'),'%s_x'); // adds "a as a_x, b as b_x"
- * $object->selectAs(array('a','b'),'ddd_%s','ccc'); // adds "ccc.a as ddd_a, ccc.b as ddd_b"
- * $object->selectAdd($object,'prefix_%s'); // calls $object->get_table and adds it all as
- * objectTableName.colnameA as prefix_colnameA
- *
- * @param array|object|null the array or object to take column names from.
- * @param string format in sprintf format (use %s for the colname)
- * @param string table name eg. if you have joinAdd'd or send $from as an array.
- * @access public
- * @return void
- */
- function selectAs($from = null,$format = '%s',$tableName=false)
- {
- global $_DB_DATAOBJECT;
-
- if (!isset($this->_query)) {
- $this->raiseError(
- "You cannot do two queries on the same object (copy it before finding)",
- DB_DATAOBJECT_ERROR_INVALIDARGS);
- return false;
- }
-
- if ($from === null) {
- // blank the '*'
- $this->selectAdd();
- $from = $this;
- }
-
-
- $table = $this->__table;
- if (is_object($from)) {
- $table = $from->__table;
- $from = array_keys($from->table());
- }
-
- if ($tableName !== false) {
- $table = $tableName;
- }
- $s = '%s';
- if (!empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers'])) {
- $this->_connect();
- $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
- $s = $DB->quoteIdentifier($s);
- }
- foreach ($from as $k) {
- $this->selectAdd(sprintf("{$s}.{$s} as {$format}",$table,$k,$k));
- }
- $this->_query['data_select'] .= "\n";
- }
- /**
- * Insert the current objects variables into the database
- *
- * Returns the ID of the inserted element - mysql specific = fixme?
- *
- * for example
- *
- * Designed to be extended
- *
- * $object = new mytable();
- * $object->name = "fred";
- * echo $object->insert();
- *
- * @access public
- * @return mixed True on success, false on failure, 0 on no data affected
- */
- function insert()
- {
- global $_DB_DATAOBJECT;
-
- // we need to write to the connection (For nextid) - so us the real
- // one not, a copyied on (as ret-by-ref fails with overload!)
-
- if (!isset($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
- $this->_connect();
- }
-
- $quoteIdentifiers = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
-
- $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
-
- $items = isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table]) ?
- $_DB_DATAOBJECT['INI'][$this->_database][$this->__table] : $this->table();
-
- if (!$items) {
- $this->raiseError("insert:No table definition for {$this->__table}", DB_DATAOBJECT_ERROR_INVALIDCONFIG);
- return false;
- }
- $options= &$_DB_DATAOBJECT['CONFIG'];
-
-
- $datasaved = 1;
- $leftq = '';
- $rightq = '';
-
- $seqKeys = isset($_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->__table]) ?
- $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->__table] :
- $this->sequenceKey();
-
- $key = isset($seqKeys[0]) ? $seqKeys[0] : false;
- $useNative = isset($seqKeys[1]) ? $seqKeys[1] : false;
- $seq = isset($seqKeys[2]) ? $seqKeys[2] : false;
-
- $dbtype = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn["phptype"];
-
-
- // nativeSequences or Sequences..
-
- // big check for using sequences
-
- if (($key !== false) && !$useNative) {
-
- if (!$seq) {
- $this->$key = $DB->nextId($this->__table);
- } else {
- $f = $DB->getOption('seqname_format');
- $DB->setOption('seqname_format','%s');
- $this->$key = $DB->nextId($seq);
- $DB->setOption('seqname_format',$f);
- }
- }
-
-
-
- foreach($items as $k => $v) {
-
- // if we are using autoincrement - skip the column...
- if ($key && ($k == $key) && $useNative) {
- continue;
- }
-
-
- if (!isset($this->$k)) {
- continue;
- }
- // dont insert data into mysql timestamps
- // use query() if you really want to do this!!!!
- if ($v & DB_DATAOBJECT_MYSQLTIMESTAMP) {
- continue;
- }
-
- if ($leftq) {
- $leftq .= ', ';
- $rightq .= ', ';
- }
-
- $leftq .= ($quoteIdentifiers ? ($DB->quoteIdentifier($k) . ' ') : "$k ");
-
- if (is_a($this->$k,'db_dataobject_cast')) {
- $value = $this->$k->toString($v,$dbtype);
- if (PEAR::isError($value)) {
- $this->raiseError($value->getMessage() ,DB_DATAOBJECT_ERROR_INVALIDARG);
- return false;
- }
- $rightq .= $value;
- continue;
- }
-
-
- if ((strtolower($this->$k) === 'null') && !($v & DB_DATAOBJECT_NOTNULL)) {
- $rightq .= " NULL ";
- continue;
- }
- // DATE is empty... on a col. that can be null..
- // note: this may be usefull for time as well..
- if (!$this->$k &&
- (($v & DB_DATAOBJECT_DATE) || ($v & DB_DATAOBJECT_TIME)) &&
- !($v & DB_DATAOBJECT_NOTNULL)) {
-
- $rightq .= " NULL ";
- continue;
- }
-
- if ($v & DB_DATAOBJECT_STR) {
- $rightq .= $DB->quote($this->$k) . " ";
- continue;
- }
- if (is_numeric($this->$k)) {
- $rightq .=" {$this->$k} ";
- continue;
- }
- // at present we only cast to integers
- // - V2 may store additional data about float/int
- $rightq .= ' ' . intval($this->$k) . ' ';
-
- }
-
-
- if ($leftq || $useNative) {
- $table = ($quoteIdentifiers ? $DB->quoteIdentifier($this->__table) : $this->__table);
-
- $r = $this->_query("INSERT INTO {$table} ($leftq) VALUES ($rightq) ");
-
-
-
- if (PEAR::isError($r)) {
- $this->raiseError($r);
- return false;
- }
-
- if ($r < 1) {
- return 0;
- }
-
-
- // now do we have an integer key!
-
- if ($key && $useNative) {
- switch ($dbtype) {
- case 'mysql':
- $this->$key = mysql_insert_id(
- $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->connection
- );
- break;
- case 'mssql':
- // note this is not really thread safe - you should wrapp it with
- // transactions = eg.
- // $db->query('BEGIN');
- // $db->insert();
- // $db->query('COMMIT');
-
- $mssql_key = $DB->getOne("SELECT @@IDENTITY");
- if (PEAR::isError($mssql_key)) {
- $this->raiseError($r);
- return false;
- }
- $this->$key = $mssql_key;
- break;
-
- case 'pgsql':
- if (!$seq) {
- $seq = $DB->getSequenceName($this->__table );
- }
- $pgsql_key = $DB->getOne("SELECT last_value FROM ".$seq);
- if (PEAR::isError($pgsql_key)) {
- $this->raiseError($r);
- return false;
- }
- $this->$key = $pgsql_key;
- break;
- }
-
- }
-
- if (isset($_DB_DATAOBJECT['CACHE'][strtolower(get_class($this))])) {
- $this->_clear_cache();
- }
- if ($key) {
- return $this->$key;
- }
- return true;
- }
- $this->raiseError("insert: No Data specifed for query", DB_DATAOBJECT_ERROR_NODATA);
- return false;
- }
-
- /**
- * Updates current objects variables into the database
- * uses the keys() to decide how to update
- * Returns the true on success
- *
- * for example
- *
- * $object = new mytable();
- * $object->get("ID",234);
- * $object->email="testing@test.com";
- * if(!$object->update())
- * echo "UPDATE FAILED";
- *
- * to only update changed items :
- * $dataobject->get(132);
- * $original = $dataobject; // clone/copy it..
- * $dataobject->setFrom($_POST);
- * if ($dataobject->validate()) {
- * $dataobject->update($original);
- * } // otherwise an error...
- *
- *
- * @param object dataobject (optional) - used to only update changed items.
- * @access public
- * @return int rows affected or false on failure
- */
- function update($dataObject = false)
- {
- global $_DB_DATAOBJECT;
- // connect will load the config!
- $this->_connect();
-
-
- $original_query = isset($this->_query) ? $this->_query : null;
-
- $items = isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table]) ?
- $_DB_DATAOBJECT['INI'][$this->_database][$this->__table] : $this->table();
-
-
- $keys = $this->keys();
-
-
- if (!$items) {
- $this->raiseError("update:No table definition for {$this->__table}", DB_DATAOBJECT_ERROR_INVALIDCONFIG);
- return false;
- }
- $datasaved = 1;
- $settings = '';
- $this->_connect();
-
- $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
- $dbtype = $DB->dsn["phptype"];
- $quoteIdentifiers = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
-
- foreach($items as $k => $v) {
- if (!isset($this->$k)) {
- continue;
- }
- // ignore stuff thats
-
- // dont write things that havent changed..
- if (($dataObject !== false) && isset($dataObject->$k) && ($dataObject->$k == $this->$k)) {
- continue;
- }
-
- // beta testing.. - dont write keys to left.!!!
- if (in_array($k,$keys)) {
- continue;
- }
-
- // dont insert data into mysql timestamps
- // use query() if you really want to do this!!!!
- if ($v & DB_DATAOBJECT_MYSQLTIMESTAMP) {
- continue;
- }
-
-
- if ($settings) {
- $settings .= ', ';
- }
-
- $kSql = ($quoteIdentifiers ? $DB->quoteIdentifier($k) : $k);
-
- if (is_a($this->$k,'db_dataobject_cast')) {
- $value = $this->$k->toString($v,$dbtype);
- if (PEAR::isError($value)) {
- $this->raiseError($value->getMessage() ,DB_DATAOBJECT_ERROR_INVALIDARG);
- return false;
- }
- $settings .= "$kSql = $value ";
- continue;
- }
-
- // special values ... at least null is handled...
- if ((strtolower($this->$k) === 'null') && !($v & DB_DATAOBJECT_NOTNULL)) {
- $settings .= "$kSql = NULL ";
- continue;
- }
- // DATE is empty... on a col. that can be null..
- // note: this may be usefull for time as well..
- if (!$this->$k &&
- (($v & DB_DATAOBJECT_DATE) || ($v & DB_DATAOBJECT_TIME)) &&
- !($v & DB_DATAOBJECT_NOTNULL)) {
-
- $settings .= "$kSql = NULL ";
- continue;
- }
-
-
- if ($v & DB_DATAOBJECT_STR) {
- $settings .= "$kSql = ". $DB->quote($this->$k) . ' ';
- continue;
- }
- if (is_numeric($this->$k)) {
- $settings .= "$kSql = {$this->$k} ";
- continue;
- }
- // at present we only cast to integers
- // - V2 may store additional data about float/int
- $settings .= "$kSql = " . intval($this->$k) . ' ';
- }
-
-
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug("got keys as ".serialize($keys),3);
- }
-
- $this->_build_condition($items,$keys);
-
- // echo " $settings, $this->condition ";
- if ($settings && isset($this->_query) && $this->_query['condition']) {
-
- $table = ($quoteIdentifiers ? $DB->quoteIdentifier($this->__table) : $this->__table);
-
- $r = $this->_query("UPDATE {$table} SET {$settings} {$this->_query['condition']} ");
-
- // restore original query conditions.
- $this->_query = $original_query;
-
- if (PEAR::isError($r)) {
- $this->raiseError($r);
- return false;
- }
- if ($r < 1) {
- return 0;
- }
-
- $this->_clear_cache();
- return $r;
- }
- // restore original query conditions.
- $this->_query = $original_query;
-
- // if you manually specified a dataobject, and there where no changes - then it's ok..
- if ($dataObject !== false) {
- return false;
- }
-
- $this->raiseError(
- "update: No Data specifed for query $settings , {$this->_query['condition']}",
- DB_DATAOBJECT_ERROR_NODATA);
- return false;
- }
-
- /**
- * Deletes items from table which match current objects variables
- *
- * Returns the true on success
- *
- * for example
- *
- * Designed to be extended
- *
- * $object = new mytable();
- * $object->ID=123;
- * echo $object->delete(); // builds a conditon
- *
- * $object = new mytable();
- * $object->whereAdd('age > 12');
- * $object->limit(1);
- * $object->orderBy('age DESC');
- * $object->delete(true); // dont use object vars, use the conditions, limit and order.
- *
- * @param bool $useWhere (optional) If DB_DATAOBJECT_WHEREADD_ONLY is passed in then
- * we will build the condition only using the whereAdd's. Default is to
- * build the condition only using the object parameters.
- *
- * @access public
- * @return mixed True on success, false on failure, 0 on no data affected
- */
- function delete($useWhere = false)
- {
- global $_DB_DATAOBJECT;
- // connect will load the config!
- $this->_connect();
- $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
- $quoteIdentifiers = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
-
- $extra_cond = ' ' . (isset($this->_query['order_by']) ? $this->_query['order_by'] : '') .
- ' ' . (isset($this->_query['limit']) ? $this->_query['limit'] : '');
-
- if (!$useWhere) {
-
- $keys = $this->keys();
- $this->_query = array(); // as it's probably unset!
- $this->_query['condition'] = ''; // default behaviour not to use where condition
- $this->_build_condition($this->table(),$keys);
- // if primary keys are not set then use data from rest of object.
- if (!$this->_query['condition']) {
- $this->_build_condition($this->table(),array(),$keys);
- }
- $extra_cond = '';
- }
-
-
- // don't delete without a condition
- if (isset($this->_query) && $this->_query['condition']) {
-
- $table = ($quoteIdentifiers ? $DB->quoteIdentifier($this->__table) : $this->__table);
-
- $r = $this->_query("DELETE FROM {$table} {$this->_query['condition']}{$extra_cond}");
-
-
- if (PEAR::isError($r)) {
- $this->raiseError($r);
- return false;
- }
- if ($r < 1) {
- return 0;
- }
- $this->_clear_cache();
- return $r;
- } else {
- $this->raiseError("delete: No condition specifed for query", DB_DATAOBJECT_ERROR_NODATA);
- return false;
- }
- }
-
- /**
- * fetches a specific row into this object variables
- *
- * Not recommended - better to use fetch()
- *
- * Returens true on success
- *
- * @param int $row row
- * @access public
- * @return boolean true on success
- */
- function fetchRow($row = null)
- {
- global $_DB_DATAOBJECT;
- if (empty($_DB_DATAOBJECT['CONFIG'])) {
- $this->_loadConfig();
- }
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug("{$this->__table} $row of {$this->N}", "fetchrow",3);
- }
- if (!$this->__table) {
- $this->raiseError("fetchrow: No table", DB_DATAOBJECT_ERROR_INVALIDCONFIG);
- return false;
- }
- if ($row === null) {
- $this->raiseError("fetchrow: No row specified", DB_DATAOBJECT_ERROR_INVALIDARGS);
- return false;
- }
- if (!$this->N) {
- $this->raiseError("fetchrow: No results avaiable", DB_DATAOBJECT_ERROR_NODATA);
- return false;
- }
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug("{$this->__table} $row of {$this->N}", "fetchrow",3);
- }
-
-
- $result = &$_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid];
- $array = $result->fetchrow(DB_FETCHMODE_ASSOC,$row);
- if (!is_array($array)) {
- $this->raiseError("fetchrow: No results available", DB_DATAOBJECT_ERROR_NODATA);
- return false;
- }
-
- foreach($array as $k => $v) {
- $kk = str_replace(".", "_", $k);
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug("$kk = ". $array[$k], "fetchrow LINE", 3);
- }
- $this->$kk = $array[$k];
- }
-
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug("{$this->__table} DONE", "fetchrow", 3);
- }
- return true;
- }
-
- /**
- * Find the number of results from a simple query
- *
- * for example
- *
- * $object = new mytable();
- * $object->name = "fred";
- * echo $object->count();
- * echo $object->count(true); // dont use object vars.
- * echo $object->count('distinct mycol');
- * echo $object->count('distinct mycol',true); // dont use object vars.
- *
- *
- * @param bool|string (optional)
- * (true|false = see below not on whereAddonly)
- * (string)
- * $countWhat (optional) normally it counts primary keys - you can use
- * this to do things like $do->count('distinct mycol');
- * @param bool $whereAddOnly (optional) If DB_DATAOBJECT_WHEREADD_ONLY is passed in then
- * we will build the condition only using the whereAdd's. Default is to
- * build the condition using the object parameters as well.
- *
- * @access public
- * @return int
- */
- function count($countWhat = false,$whereAddOnly = false)
- {
- global $_DB_DATAOBJECT;
-
- if (is_bool($countWhat)) {
- $whereAddOnly = $countWhat;
- }
-
- $t = clone($this);
-
- $quoteIdentifiers = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
-
- $items = $t->table();
- if (!isset($t->_query)) {
- $this->raiseError(
- "You cannot do run count after you have run fetch()",
- DB_DATAOBJECT_ERROR_INVALIDARGS);
- return false;
- }
- $this->_connect();
- $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
-
-
- if (!$whereAddOnly && $items) {
- $t->_build_condition($items);
- }
- $keys = $this->keys();
-
- if (!$keys[0] && !is_string($countWhat)) {
- $this->raiseError(
- "You cannot do run count without keys - use \$do->keys('id');",
- DB_DATAOBJECT_ERROR_INVALIDARGS,PEAR_ERROR_DIE);
- return false;
-
- }
- $table = ($quoteIdentifiers ? $DB->quoteIdentifier($this->__table) : $this->__table);
- if (!is_string($countWhat)) {
- $key_col = ($quoteIdentifiers ? $DB->quoteIdentifier($keys[0]) : $keys[0]);
- }
-
- $as = ($quoteIdentifiers ? $DB->quoteIdentifier('DATAOBJECT_NUM') : 'DATAOBJECT_NUM');
-
- $countWhat = is_string($countWhat) ? $countWhat : "{$table}.{$key_col}";
-
- $r = $t->_query(
- "SELECT count({$countWhat}) as $as
- FROM $table {$t->_join} {$t->_query['condition']}");
- if (PEAR::isError($r)) {
- return false;
- }
-
- $result = &$_DB_DATAOBJECT['RESULTS'][$t->_DB_resultid];
- $l = $result->fetchRow();
- return $l[0];
- }
-
- /**
- * sends raw query to database
- *
- * Since _query has to be a private 'non overwriteable method', this is a relay
- *
- * @param string $string SQL Query
- * @access public
- * @return void or DB_Error
- */
- function query($string)
- {
- return $this->_query($string);
- }
-
-
- /**
- * an escape wrapper around DB->escapeSimple()
- * can be used when adding manual queries or clauses
- * eg.
- * $object->query("select * from xyz where abc like '". $object->escape($_GET['name']) . "'");
- *
- * @param string $string value to be escaped
- * @access public
- * @return string
- */
- function escape($string)
- {
- global $_DB_DATAOBJECT;
- $this->_connect();
- $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
- return $DB->escapeSimple($string);
- }
-
- /* ==================================================== */
- /* Major Private Vars */
- /* ==================================================== */
-
- /**
- * The Database connection dsn (as described in the PEAR DB)
- * only used really if you are writing a very simple application/test..
- * try not to use this - it is better stored in configuration files..
- *
- * @access private
- * @var string
- */
- var $_database_dsn = '';
-
- /**
- * The Database connection id (md5 sum of databasedsn)
- *
- * @access private
- * @var string
- */
- var $_database_dsn_md5 = '';
-
- /**
- * The Database name
- * created in __connection
- *
- * @access private
- * @var string
- */
- var $_database = '';
-
-
-
- /**
- * The QUERY rules
- * This replaces alot of the private variables
- * used to build a query, it is unset after find() is run.
- *
- *
- *
- * @access private
- * @var array
- */
- var $_query = array(
- 'condition' => '', // the WHERE condition
- 'group_by' => '', // the GROUP BY condition
- 'order_by' => '', // the ORDER BY condition
- 'having' => '', // the HAVING condition
- 'limit' => '', // the LIMIT condition
- 'data_select' => '*', // the columns to be SELECTed
- );
-
-
-
-
- /**
- * Database result id (references global $_DB_DataObject[results]
- *
- * @access private
- * @var integer
- */
- var $_DB_resultid; // database result object
-
-
- /* ============================================================== */
- /* Table definition layer (started of very private but 'came out'*/
- /* ============================================================== */
-
- /**
- * Autoload or manually load the table definitions
- *
- *
- * usage :
- * DB_DataObject::databaseStructure( 'databasename',
- * parse_ini_file('mydb.ini',true),
- * parse_ini_file('mydb.link.ini',true));
- *
- * obviously you dont have to use ini files.. (just return array similar to ini files..)
- *
- * It should append to the table structure array
- *
- *
- * @param optional string name of database to assign / read
- * @param optional array structure of database, and keys
- * @param optional array table links
- *
- * @access public
- * @return true or PEAR:error on wrong paramenters.. or false if no file exists..
- * or the array(tablename => array(column_name=>type)) if called with 1 argument.. (databasename)
- */
- function databaseStructure()
- {
-
- global $_DB_DATAOBJECT;
-
- // Assignment code
-
- if ($args = func_get_args()) {
-
- if (count($args) == 1) {
-
- // this returns all the tables and their structure..
-
- $x = new DB_DataObject;
- $x->_database = $args[0];
- $this->_connect();
- $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
-
- $tables = $DB->getListOf('tables');
- require_once 'DB/DataObject/Generator.php';
- foreach($tables as $table) {
- $y = new DB_DataObject_Generator;
- $y->fillTableSchema($x->_database,$table);
- }
- return $_DB_DATAOBJECT['INI'][$x->_database];
- } else {
-
- $_DB_DATAOBJECT['INI'][$args[0]] = isset($_DB_DATAOBJECT['INI'][$args[0]]) ?
- $_DB_DATAOBJECT['INI'][$args[0]] + $args[1] : $args[1];
-
- if (isset($args[1])) {
- $_DB_DATAOBJECT['LINKS'][$args[0]] = isset($_DB_DATAOBJECT['LINKS'][$args[0]]) ?
- $_DB_DATAOBJECT['LINKS'][$args[0]] + $args[2] : $args[2];
- }
- return true;
- }
-
- }
-
-
-
- if (!$this->_database) {
- $this->_connect();
- }
-
- // loaded already?
- if (!empty($_DB_DATAOBJECT['INI'][$this->_database])) {
- // database loaded - but this is table is not available..
- if (empty($_DB_DATAOBJECT['INI'][$this->_database][$this->__table])) {
- require_once 'DB/DataObject/Generator.php';
- $x = new DB_DataObject_Generator;
- $x->fillTableSchema($this->_database,$this->__table);
- }
- return true;
- }
-
-
- if (empty($_DB_DATAOBJECT['CONFIG'])) {
- DB_DataObject::_loadConfig();
- }
-
- // if you supply this with arguments, then it will take those
- // as the database and links array...
-
- $schemas = isset($_DB_DATAOBJECT['CONFIG']['schema_location']) ?
- array("{$_DB_DATAOBJECT['CONFIG']['schema_location']}/{$this->_database}.ini") :
- array() ;
-
- if (isset($_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"])) {
- $schemas = is_array($_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"]) ?
- $_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"] :
- explode(PATH_SEPARATOR,$_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"]);
- }
-
-
-
- foreach ($schemas as $ini) {
- $links =
- isset($_DB_DATAOBJECT['CONFIG']["links_{$this->_database}"]) ?
- $_DB_DATAOBJECT['CONFIG']["links_{$this->_database}"] :
- str_replace('.ini','.links.ini',$ini);
-
- if (file_exists($ini)) {
- $_DB_DATAOBJECT['INI'][$this->_database] = parse_ini_file($ini, true);
- }
- if (empty($_DB_DATAOBJECT['LINKS'][$this->_database]) && file_exists($links)) {
- /* not sure why $links = ... here - TODO check if that works */
- $_DB_DATAOBJECT['LINKS'][$this->_database] = parse_ini_file($links, true);
- }
- }
- // now have we loaded the structure.. - if not try building it..
-
- if (empty($_DB_DATAOBJECT['INI'][$this->_database][$this->__table])) {
- require_once 'DB/DataObject/Generator.php';
- $x = new DB_DataObject_Generator;
- $x->fillTableSchema($this->_database,$this->__table);
- }
-
-
- return true;
- }
-
-
-
-
- /**
- * Return or assign the name of the current table
- *
- *
- * @param string optinal table name to set
- * @access public
- * @return string The name of the current table
- */
- function tableName()
- {
- $args = func_get_args();
- if (count($args)) {
- $this->__table = $args[0];
- }
- return $this->__table;
- }
-
- /**
- * Return or assign the name of the current database
- *
- * @param string optional database name to set
- * @access public
- * @return string The name of the current database
- */
- function database()
- {
- $args = func_get_args();
- if (count($args)) {
- $this->_database = $args[0];
- }
- return $this->_database;
- }
-
- /**
- * get/set an associative array of table columns
- *
- * @access public
- * @param array key=>type array
- * @return array (associative)
- */
- function table()
- {
-
- // for temporary storage of database fields..
- // note this is not declared as we dont want to bloat the print_r output
- $args = func_get_args();
- if (count($args)) {
- $this->_database_fields = $args[0];
- }
- if (isset($this->_database_fields)) {
- return $this->_database_fields;
- }
-
-
- global $_DB_DATAOBJECT;
- if (!isset($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
- $this->_connect();
- }
-
- if (isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table])) {
- return $_DB_DATAOBJECT['INI'][$this->_database][$this->__table];
- }
-
- $this->databaseStructure();
-
-
- $ret = array();
- if (isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table])) {
- $ret = $_DB_DATAOBJECT['INI'][$this->_database][$this->__table];
- }
-
- return $ret;
- }
-
- /**
- * get/set an array of table primary keys
- *
- * set usage: $do->keys('id','code');
- *
- * This is defined in the table definition if it gets it wrong,
- * or you do not want to use ini tables, you can override this.
- * @param string optional set the key
- * @param * optional set more keys
- * @access private
- * @return array
- */
- function keys()
- {
- // for temporary storage of database fields..
- // note this is not declared as we dont want to bloat the print_r output
- $args = func_get_args();
- if (count($args)) {
- $this->_database_keys = $args;
- }
- if (isset($this->_database_keys)) {
- return $this->_database_keys;
- }
-
- global $_DB_DATAOBJECT;
- if (!isset($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
- $this->_connect();
- }
- if (isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"])) {
- return array_keys($_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"]);
- }
- $this->databaseStructure();
-
- if (isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"])) {
- return array_keys($_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"]);
- }
- return array();
- }
- /**
- * get/set an sequence key
- *
- * by default it returns the first key from keys()
- * set usage: $do->sequenceKey('id',true);
- *
- * override this to return array(false,false) if table has no real sequence key.
- *
- * @param string optional the key sequence/autoinc. key
- * @param boolean optional use native increment. default false
- * @param false|string optional native sequence name
- * @access private
- * @return array (column,use_native,sequence_name)
- */
- function sequenceKey()
- {
- global $_DB_DATAOBJECT;
-
- // call setting
- if (!$this->_database) {
- $this->_connect();
- }
-
- if (!isset($_DB_DATAOBJECT['SEQUENCE'][$this->_database])) {
- $_DB_DATAOBJECT['SEQUENCE'][$this->_database] = array();
- }
-
-
- $args = func_get_args();
- if (count($args)) {
- $args[1] = isset($args[1]) ? $args[1] : false;
- $args[2] = isset($args[2]) ? $args[2] : false;
- $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->__table] = $args;
- }
- if (isset($_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->__table])) {
- return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->__table];
- }
- // end call setting (eg. $do->sequenceKeys(a,b,c); )
-
-
-
-
- $keys = $this->keys();
- if (!$keys) {
- return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->__table]
- = array(false,false,false);;
- }
-
-
- $table = isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table]) ?
- $_DB_DATAOBJECT['INI'][$this->_database][$this->__table] : $this->table();
-
- $dbtype = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['phptype'];
-
- $usekey = $keys[0];
-
-
-
- $seqname = false;
-
- if (!empty($_DB_DATAOBJECT['CONFIG']['sequence_'.$this->__table])) {
- $usekey = $_DB_DATAOBJECT['CONFIG']['sequence_'.$this->__table];
- if (strpos($usekey,':') !== false) {
- list($usekey,$seqname) = explode(':',$usekey);
- }
- }
-
-
- // if the key is not an integer - then it's not a sequence or native
- if (!($table[$usekey] & DB_DATAOBJECT_INT)) {
- return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->__table] = array(false,false,false);
- }
-
-
- if (!empty($_DB_DATAOBJECT['CONFIG']['ignore_sequence_keys'])) {
- $ignore = $_DB_DATAOBJECT['CONFIG']['ignore_sequence_keys'];
- if (is_string($ignore) && (strtoupper($ignore) == 'ALL')) {
- return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->__table] = array(false,false,$seqname);
- }
- if (is_string($ignore)) {
- $ignore = $_DB_DATAOBJECT['CONFIG']['ignore_sequence_keys'] = explode(',',$ignore);
- }
- if (in_array($this->__table,$ignore)) {
- return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->__table] = array(false,false,$seqname);
- }
- }
-
-
- $realkeys = $_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"];
-
- // if you are using an old ini file - go back to old behaviour...
- if (is_numeric($realkeys[$usekey])) {
- $realkeys[$usekey] = 'N';
- }
-
- // multiple unique primary keys without a native sequence...
- if (($realkeys[$usekey] == 'K') && (count($keys) > 1)) {
- return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->__table] = array(false,false,$seqname);
- }
- // use native sequence keys...
- // technically postgres native here...
- // we need to get the new improved tabledata sorted out first.
-
- if ( in_array($dbtype , array( 'mysql', 'mssql')) &&
- ($table[$usekey] & DB_DATAOBJECT_INT) &&
- isset($realkeys[$usekey]) && ($realkeys[$usekey] == 'N')
- ) {
- return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->__table] = array($usekey,true,$seqname);
- }
- // if not a native autoinc, and we have not assumed all primary keys are sequence
- if (($realkeys[$usekey] != 'N') &&
- !empty($_DB_DATAOBJECT['CONFIG']['dont_use_pear_sequences'])) {
- return array(false,false,false);
- }
- // I assume it's going to try and be a nextval DB sequence.. (not native)
- return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->__table] = array($usekey,false,$seqname);
- }
-
-
-
- /* =========================================================== */
- /* Major Private Methods - the core part! */
- /* =========================================================== */
-
-
-
- /**
- * clear the cache values for this class - normally done on insert/update etc.
- *
- * @access private
- * @return void
- */
- function _clear_cache()
- {
- global $_DB_DATAOBJECT;
-
- $class = get_class($this);
-
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug("Clearing Cache for ".$class,1);
- }
-
- if (!empty($_DB_DATAOBJECT['CACHE'][$class])) {
- unset($_DB_DATAOBJECT['CACHE'][$class]);
- }
- }
-
- /**
- * connects to the database
- *
- *
- * TODO: tidy this up - This has grown to support a number of connection options like
- * a) dynamic changing of ini file to change which database to connect to
- * b) multi data via the table_{$table} = dsn ini option
- * c) session based storage.
- *
- * @access private
- * @return true | PEAR::error
- */
- function _connect()
- {
- global $_DB_DATAOBJECT;
- if (empty($_DB_DATAOBJECT['CONFIG'])) {
- $this->_loadConfig();
- }
-
- // is it already connected ?
-
- if ($this->_database_dsn_md5 && !empty($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
- if (PEAR::isError($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
- return $this->raiseError(
- $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->message,
- $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->code, PEAR_ERROR_DIE
- );
-
- }
-
- if (!$this->_database) {
- $this->_database = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['database'];
- }
-
- }
-
- // it's not currently connected!
- // try and work out what to use for the dsn !
-
- $options= &$_DB_DATAOBJECT['CONFIG'];
- $dsn = isset($this->_database_dsn) ? $this->_database_dsn : null;
-
- if (!$dsn) {
- if (!$this->_database) {
- $this->_database = isset($options["table_{$this->__table}"]) ?$options["table_{$this->__table}"] : null;
- }
- if ($this->_database && !empty($options["database_{$this->_database}"])) {
- $dsn = $options["database_{$this->_database}"];
- } else if (!empty($options['database'])) {
- $dsn = $options['database'];
- }
- }
-
- // if still no database...
- if (!$dsn) {
- return $this->raiseError(
- "No database name / dsn found anywhere",
- DB_DATAOBJECT_ERROR_INVALIDCONFIG, PEAR_ERROR_DIE
- );
-
- }
-
-
-
- $this->_database_dsn_md5 = md5($dsn);
-
- if (!empty($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug("USING CACHED CONNECTION", "CONNECT",3);
- }
- if (!$this->_database) {
- $this->_database = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn["database"];
- }
- return true;
- }
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug("NEW CONNECTION", "CONNECT",3);
- /* actualy make a connection */
- $this->debug("{$dsn} {$this->_database_dsn_md5}", "CONNECT",3);
- }
- $db_options = PEAR::getStaticProperty('DB','options');
- require_once 'DB.php';
- if ($db_options) {
-
- $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5] = DB::connect($dsn,$db_options);
- } else {
- $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5] = DB::connect($dsn);
- }
-
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug(serialize($_DB_DATAOBJECT['CONNECTIONS']), "CONNECT",5);
- }
- if (PEAR::isError($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
- return $this->raiseError(
- $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->message,
- $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->code, PEAR_ERROR_DIE
- );
-
- }
-
- if (!$this->_database) {
- $this->_database = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn["database"];
- }
-
- // Oracle need to optimize for portibility - not sure exactly what this does though :)
- $c = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
-
-
-
-
-
-
-
- return true;
- }
-
- /**
- * sends query to database - this is the private one that must work
- * - internal functions use this rather than $this->query()
- *
- * @param string $string
- * @access private
- * @return mixed none or PEAR_Error
- */
- function _query($string)
- {
- global $_DB_DATAOBJECT;
- $this->_connect();
-
-
- $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
-
- $options = &$_DB_DATAOBJECT['CONFIG'];
-
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug($string,$log="QUERY");
-
- }
-
- if (strtoupper($string) == 'BEGIN') {
- $DB->autoCommit(false);
- // db backend adds begin anyway from now on..
- return true;
- }
- if (strtoupper($string) == 'COMMIT') {
- $DB->commit();
- $DB->autoCommit(true);
- return true;
- }
-
- if (strtoupper($string) == 'ROLLBACK') {
- $DB->rollback();
- $DB->autoCommit(true);
- return true;
- }
-
-
- if (!empty($options['debug_ignore_updates']) &&
- (strtolower(substr(trim($string), 0, 6)) != 'select') &&
- (strtolower(substr(trim($string), 0, 4)) != 'show') &&
- (strtolower(substr(trim($string), 0, 8)) != 'describe')) {
-
- $this->debug('Disabling Update as you are in debug mode');
- return $this->raiseError("Disabling Update as you are in debug mode", null) ;
-
- }
- //if (@$_DB_DATAOBJECT['CONFIG']['debug'] > 1) {
- // this will only work when PEAR:DB supports it.
- //$this->debug($DB->getAll('explain ' .$string,DB_FETCHMODE_ASSOC), $log="sql",2);
- //}
-
- // some sim
- $t= explode(' ',microtime());
- $_DB_DATAOBJECT['QUERYENDTIME'] = $time = $t[0]+$t[1];
-
- $result = $DB->query($string);
-
-
-
-
- if (is_a($result,'DB_Error')) {
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug($result->toString(), "Query Error",1 );
- }
- return $result;
- }
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $t= explode(' ',microtime());
- $_DB_DATAOBJECT['QUERYENDTIME'] = $t[0]+$t[1];
- $this->debug('QUERY DONE IN '.($t[0]+$t[1]-$time)." seconds", 'query',1);
- }
- switch (strtolower(substr(trim($string),0,6))) {
- case 'insert':
- case 'update':
- case 'delete':
- return $DB->affectedRows();;
- }
- if (is_object($result)) {
- // lets hope that copying the result object is OK!
-
- $_DB_resultid = $GLOBALS['_DB_DATAOBJECT']['RESULTSEQ']++;
- $_DB_DATAOBJECT['RESULTS'][$_DB_resultid] = $result;
- $this->_DB_resultid = $_DB_resultid;
- }
- $this->N = 0;
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug(serialize($result), 'RESULT',5);
- }
- if (method_exists($result, 'numrows')) {
- $DB->expectError(DB_ERROR_UNSUPPORTED);
- $this->N = $result->numrows();
- if (is_a($this->N,'DB_Error')) {
- $this->N = 1;
- }
- $DB->popExpect();
- }
- }
-
- /**
- * Builds the WHERE based on the values of of this object
- *
- * @param mixed $keys
- * @param array $filter (used by update to only uses keys in this filter list).
- * @param array $negative_filter (used by delete to prevent deleting using the keys mentioned..)
- * @access private
- * @return string
- */
- function _build_condition($keys, $filter = array(),$negative_filter=array())
- {
- global $_DB_DATAOBJECT;
- $this->_connect();
- $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
-
- $quoteIdentifiers = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
- // if we dont have query vars.. - reset them.
- if (!isset($this->_query)) {
- $x = new DB_DataObject;
- $this->_query= $x->_query;
- }
-
- foreach($keys as $k => $v) {
- // index keys is an indexed array
- /* these filter checks are a bit suspicious..
- - need to check that update really wants to work this way */
-
- if ($filter) {
- if (!in_array($k, $filter)) {
- continue;
- }
- }
- if ($negative_filter) {
- if (in_array($k, $negative_filter)) {
- continue;
- }
- }
- if (!isset($this->$k)) {
- continue;
- }
-
- $kSql = $quoteIdentifiers
- ? ( $DB->quoteIdentifier($this->__table) . '.' . $DB->quoteIdentifier($k) )
- : "{$this->__table}.{$k}";
-
-
-
- if (is_a($this->$k,'db_dataobject_cast')) {
- $dbtype = $DB->dsn["phptype"];
- $value = $this->$k->toString($v,$dbtype);
- if (PEAR::isError($value)) {
- $this->raiseError($value->getMessage() ,DB_DATAOBJECT_ERROR_INVALIDARG);
- return false;
- }
- if ($value == 'NULL') {
- $value = 'IS NULL';
- }
- $this->whereAdd(" $kSql = $value");
- continue;
- }
-
- if ((strtolower($this->$k) === 'null') && !($v & DB_DATAOBJECT_NOTNULL)) {
- $this->whereAdd(" $kSql IS NULL");
- continue;
- }
-
-
- if ($v & DB_DATAOBJECT_STR) {
- $this->whereAdd(" $kSql = " . $DB->quote($this->$k) );
- continue;
- }
- if (is_numeric($this->$k)) {
- $this->whereAdd(" $kSql = {$this->$k}");
- continue;
- }
- /* this is probably an error condition! */
- $this->whereAdd(" $kSql = 0");
- }
- }
-
- /**
- * autoload Class relating to a table
- * (depreciated - use ::factory)
- *
- * @param string $table table
- * @access private
- * @return string classname on Success
- */
- function staticAutoloadTable($table)
- {
- global $_DB_DATAOBJECT;
- if (empty($_DB_DATAOBJECT['CONFIG'])) {
- DB_DataObject::_loadConfig();
- }
- $p = isset($_DB_DATAOBJECT['CONFIG']['class_prefix']) ?
- $_DB_DATAOBJECT['CONFIG']['class_prefix'] : '';
- $class = $p . preg_replace('/[^A-Z0-9]/i','_',ucfirst($table));
- $class = (class_exists($class)) ? $class : DB_DataObject::_autoloadClass($class);
- return $class;
- }
-
-
- /**
- * classic factory method for loading a table class
- * usage: $do = DB_DataObject::factory('person')
- * WARNING - this may emit a include error if the file does not exist..
- * use @ to silence it (if you are sure it is acceptable)
- * eg. $do = @DB_DataObject::factory('person')
- *
- * table name will eventually be databasename/table
- * - and allow modular dataobjects to be written..
- * (this also helps proxy creation)
- *
- *
- * @param string $table tablename (use blank to create a new instance of the same class.)
- * @access private
- * @return DataObject|PEAR_Error
- */
-
-
-
- function factory($table = '') {
- global $_DB_DATAOBJECT;
- if (empty($_DB_DATAOBJECT['CONFIG'])) {
- DB_DataObject::_loadConfig();
- }
-
- if ($table === '') {
- if (is_a($this,'DB_DataObject') && strlen($this->__table)) {
- $table = $this->__table;
- } else {
- return DB_DataObject::raiseError(
- "factory did not recieve a table name",
- DB_DATAOBJECT_ERROR_INVALIDARGS);
- }
- }
-
-
- $p = isset($_DB_DATAOBJECT['CONFIG']['class_prefix']) ?
- $_DB_DATAOBJECT['CONFIG']['class_prefix'] : '';
- $class = $p . preg_replace('/[^A-Z0-9]/i','_',ucfirst($table));
-
- $class = (class_exists($class)) ? $class : DB_DataObject::_autoloadClass($class);
-
- // proxy = full|light
- if (!$class && isset($_DB_DATAOBJECT['CONFIG']['proxy'])) {
- $proxyMethod = 'getProxy'.$_DB_DATAOBJECT['CONFIG']['proxy'];
-
- require_once 'DB/DataObject/Generator.php';
- $d = new DB_DataObject;
-
- $d->__table = $table;
- $d->_connect();
-
- $x = new DB_DataObject_Generator;
- return $x->$proxyMethod( $d->_database, $table);
- }
-
- if (!$class) {
- return DB_DataObject::raiseError(
- "factory could not find class $class from $table",
- DB_DATAOBJECT_ERROR_INVALIDCONFIG);
- }
-
- return new $class;
- }
- /**
- * autoload Class
- *
- * @param string $class Class
- * @access private
- * @return string classname on Success
- */
- function _autoloadClass($class)
- {
- global $_DB_DATAOBJECT;
-
- if (empty($_DB_DATAOBJECT['CONFIG'])) {
- DB_DataObject::_loadConfig();
- }
- $table = substr($class,strlen($_DB_DATAOBJECT['CONFIG']['class_prefix']));
-
- // only include the file if it exists - and barf badly if it has parse errors :)
- if (!empty($_DB_DATAOBJECT['CONFIG']['proxy']) && empty($_DB_DATAOBJECT['CONFIG']['class_location'])) {
- return false;
- }
-
- $file = $_DB_DATAOBJECT['CONFIG']['class_location'].'/'.preg_replace('/[^A-Z0-9]/i','_',ucfirst($table)).".php";
-
- if (!file_exists($file)) {
- $found = false;
- foreach(explode(PATH_SEPARATOR, ini_get('include_path')) as $p) {
- if (file_exists("$p/$file")) {
- $file = "$p/$file";
- $found = true;
- break;
- }
- }
- if (!$found) {
- DB_DataObject::raiseError(
- "autoload:Could not find class {$class} using class_location value",
- DB_DATAOBJECT_ERROR_INVALIDCONFIG);
- return false;
- }
- }
-
- include_once $file;
-
-
-
-
- if (!class_exists($class)) {
- DB_DataObject::raiseError(
- "autoload:Could not autoload {$class}",
- DB_DATAOBJECT_ERROR_INVALIDCONFIG);
- return false;
- }
- return $class;
- }
-
-
-
- /**
- * Have the links been loaded?
- * if they have it contains a array of those variables.
- *
- * @access private
- * @var boolean | array
- */
- var $_link_loaded = false;
-
- /**
- * Get the links associate array as defined by the links.ini file.
- *
- *
- * Experimental... -
- * Should look a bit like
- * [local_col_name] => "related_tablename:related_col_name"
- *
- *
- * @return array|null
- * array = if there are links defined for this table.
- * empty array - if there is a links.ini file, but no links on this table
- * null - if no links.ini exists for this database (hence try auto_links).
- * @access public
- * @see DB_DataObject::getLinks(), DB_DataObject::getLink()
- */
-
- function links()
- {
- global $_DB_DATAOBJECT;
- if (empty($_DB_DATAOBJECT['CONFIG'])) {
- $this->_loadConfig();
- }
-
-
- if (isset($_DB_DATAOBJECT['LINKS'][$this->_database][$this->__table])) {
- return $_DB_DATAOBJECT['LINKS'][$this->_database][$this->__table];
- }
- $this->databaseStructure();
- // if there is no link data at all on the file!
- // we return null.
- if (!isset($_DB_DATAOBJECT['LINKS'][$this->_database])) {
- return null;
- }
-
- if (isset($_DB_DATAOBJECT['LINKS'][$this->_database][$this->__table])) {
- return $_DB_DATAOBJECT['LINKS'][$this->_database][$this->__table];
- }
-
- return array();
- }
- /**
- * load related objects
- *
- * There are two ways to use this, one is to set up a <dbname>.links.ini file
- * into a static property named <dbname>.links and specifies the table joins,
- * the other highly dependent on naming columns 'correctly' :)
- * using colname = xxxxx_yyyyyy
- * xxxxxx = related table; (yyyyy = user defined..)
- * looks up table xxxxx, for value id=$this->xxxxx
- * stores it in $this->_xxxxx_yyyyy
- * you can change what object vars the links are stored in by
- * changeing the format parameter
- *
- *
- * @param string format (default _%s) where %s is the table name.
- * @author Tim White <tim@cyface.com>
- * @access public
- * @return boolean , true on success
- */
- function getLinks($format = '_%s')
- {
-
- // get table will load the options.
- if ($this->_link_loaded) {
- return true;
- }
- $this->_link_loaded = false;
- $cols = $this->table();
- $links = $this->links();
-
- $loaded = array();
-
- if ($links) {
- foreach($links as $key => $match) {
- list($table,$link) = explode(':', $match);
- $k = sprintf($format, str_replace('.', '_', $key));
- // makes sure that '.' is the end of the key;
- if ($p = strpos($key,'.')) {
- $key = substr($key, 0, $p);
- }
-
- $this->$k = $this->getLink($key, $table, $link);
- if (is_object($this->$k)) {
- $loaded[] = $k;
- }
- }
- $this->_link_loaded = $loaded;
- return true;
- }
- // this is the autonaming stuff..
- // it sends the column name down to getLink and lets that sort it out..
- // if there is a links file then it is not used!
- // IT IS DEPRECIATED!!!! - USE
- if (!is_null($links)) {
- return false;
- }
-
-
- foreach (array_keys($cols) as $key) {
- if (!($p = strpos($key, '_'))) {
- continue;
- }
- // does the table exist.
- $k =sprintf($format, $key);
- $this->$k = $this->getLink($key);
- if (is_object($this->$k)) {
- $loaded[] = $k;
- }
- }
- $this->_link_loaded = $loaded;
- return true;
- }
-
- /**
- * return name from related object
- *
- * There are two ways to use this, one is to set up a <dbname>.links.ini file
- * into a static property named <dbname>.links and specifies the table joins,
- * the other is highly dependant on naming columns 'correctly' :)
- *
- * NOTE: the naming convention is depreciated!!! - use links.ini
- *
- * using colname = xxxxx_yyyyyy
- * xxxxxx = related table; (yyyyy = user defined..)
- * looks up table xxxxx, for value id=$this->xxxxx
- * stores it in $this->_xxxxx_yyyyy
- *
- * you can also use $this->getLink('thisColumnName','otherTable','otherTableColumnName')
- *
- *
- * @param string $row either row or row.xxxxx
- * @param string $table name of table to look up value in
- * @param string $link name of column in other table to match
- * @author Tim White <tim@cyface.com>
- * @access public
- * @return mixed object on success
- */
- function &getLink($row, $table = null, $link = false)
- {
-
-
- // GUESS THE LINKED TABLE.. (if found - recursevly call self)
-
- if ($table === null) {
- $links = $this->links();
-
- if (is_array($links)) {
-
- if ($links[$row]) {
- list($table,$link) = explode(':', $links[$row]);
- if ($p = strpos($row,".")) {
- $row = substr($row,0,$p);
- }
- return $r = &$this->getLink($row,$table,$link);
- }
-
- $this->raiseError(
- "getLink: $row is not defined as a link (normally this is ok)",
- DB_DATAOBJECT_ERROR_NODATA);
-
- return false; // technically a possible error condition?
-
- }
- // use the old _ method - this shouldnt happen if called via getLinks()
- if (!($p = strpos($row, '_'))) {
- return null;
- }
- $table = substr($row, 0, $p);
- return $r = &$this->getLink($row, $table);
-
- }
-
-
-
- if (!isset($this->$row)) {
- $this->raiseError("getLink: row not set $row", DB_DATAOBJECT_ERROR_NODATA);
- return false;
- }
-
- // check to see if we know anything about this table..
-
- $obj = $this->factory($table);
-
- if (!is_a($obj,'DB_DataObject')) {
- $this->raiseError(
- "getLink:Could not find class for row $row, table $table",
- DB_DATAOBJECT_ERROR_INVALIDCONFIG);
- return false;
- }
- if ($link) {
- if ($obj->get($link, $this->$row)) {
- return $obj;
- }
- return false;
- }
-
- if ($obj->get($this->$row)) {
- return $obj;
- }
- return false;
- }
-
- /**
- * IS THIS SUPPORTED/USED ANYMORE????
- *return a list of options for a linked table
- *
- * This is highly dependant on naming columns 'correctly' :)
- * using colname = xxxxx_yyyyyy
- * xxxxxx = related table; (yyyyy = user defined..)
- * looks up table xxxxx, for value id=$this->xxxxx
- * stores it in $this->_xxxxx_yyyyy
- *
- * @access public
- * @return array of results (empty array on failure)
- */
- function &getLinkArray($row, $table = null)
- {
-
- $ret = array();
- if (!$table) {
- $links = $this->links();
-
- if (is_array($links)) {
- if (!isset($links[$row])) {
- // failed..
- return $ret;
- }
- list($table,$link) = explode(':',$links[$row]);
- } else {
- if (!($p = strpos($row,'_'))) {
- return $ret;
- }
- $table = substr($row,0,$p);
- }
- }
-
- $c = $this->factory($table);
-
- if (!is_a($obj,'DB_DataObject')) {
- $this->raiseError(
- "getLinkArray:Could not find class for row $row, table $table",
- DB_DATAOBJECT_ERROR_INVALIDCONFIG
- );
- return $ret;
- }
-
- // if the user defined method list exists - use it...
- if (method_exists($c, 'listFind')) {
- $c->listFind($this->id);
- } else {
- $c->find();
- }
- while ($c->fetch()) {
- $ret[] = $c;
- }
- return $ret;
- }
-
- /**
- * The JOIN condition
- *
- * @access private
- * @var string
- */
- var $_join = '';
-
- /**
- * joinAdd - adds another dataobject to this, building a joined query.
- *
- * example (requires links.ini to be set up correctly)
- * // get all the images for product 24
- * $i = new DataObject_Image();
- * $pi = new DataObjects_Product_image();
- * $pi->product_id = 24; // set the product id to 24
- * $i->joinAdd($pi); // add the product_image connectoin
- * $i->find();
- * while ($i->fetch()) {
- * // do stuff
- * }
- * // an example with 2 joins
- * // get all the images linked with products or productgroups
- * $i = new DataObject_Image();
- * $pi = new DataObject_Product_image();
- * $pgi = new DataObject_Productgroup_image();
- * $i->joinAdd($pi);
- * $i->joinAdd($pgi);
- * $i->find();
- * while ($i->fetch()) {
- * // do stuff
- * }
- *
- *
- * @param optional $obj object |array the joining object (no value resets the join)
- * If you use an array here it should be in the format:
- * array('local_column','remotetable:remote_column');
- * if remotetable does not have a definition, you should
- * use @ to hide the include error message..
- *
- *
- * @param optional $joinType string 'LEFT'|'INNER'|'RIGHT'|'' Inner is default, '' indicates
- * just select ... from a,b,c with no join and
- * links are added as where items.
- *
- * @param optional $joinAs string if you want to select the table as anther name
- * useful when you want to select multiple columsn
- * from a secondary table.
-
- * @param optional $joinCol string The column on This objects table to match (needed
- * if this table links to the child object in
- * multiple places eg.
- * user->friend (is a link to another user)
- * user->mother (is a link to another user..)
- *
- * @return none
- * @access public
- * @author Stijn de Reede <sjr@gmx.co.uk>
- */
- function joinAdd($obj = false, $joinType='INNER', $joinAs=false, $joinCol=false)
- {
- global $_DB_DATAOBJECT;
- if ($obj === false) {
- $this->_join = '';
- return;
- }
-
- // support for array as first argument
- // this assumes that you dont have a links.ini for the specified table.
- // and it doesnt exist as am extended dataobject!! - experimental.
-
- $ofield = false; // object field
- $tfield = false; // this field
- $toTable = false;
- if (is_array($obj)) {
- $tfield = $obj[0];
- list($toTable,$ofield) = explode(':',$obj[1]);
- $obj = DB_DataObject::factory($toTable);
- if (!$obj) {
- $obj = new DB_DataObject;
- $obj->__table = $toTable;
- }
- // set the table items to nothing.. - eg. do not try and match
- // things in the child table...???
- $items = array();
- }
-
- if (!is_object($obj)) {
- $this->raiseError("joinAdd: called without an object", DB_DATAOBJECT_ERROR_NODATA,PEAR_ERROR_DIE);
- }
- /* make sure $this->_database is set. */
- $this->_connect();
- $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
-
-
-
-
- /* look up the links for obj table */
-
- if (!$ofield && ($olinks = $obj->links())) {
- foreach ($olinks as $k => $v) {
- /* link contains {this column} = {linked table}:{linked column} */
- $ar = explode(':', $v);
- if ($ar[0] == $this->__table) {
-
- // you have explictly specified the column
- // and the col is listed here..
- // not sure if 1:1 table could cause probs here..
-
- if ($joinCol !== false) {
- $this->raiseError(
- "joinAdd: You cannot target a join column in the " .
- "'link from' table ({$obj->__table}). " .
- "Either remove the fourth argument to joinAdd() ".
- "({$joinCol}), or alter your links.ini file.",
- DB_DATAOBJECT_ERROR_NODATA);
- return false;
- }
-
- $ofield = $k;
- $tfield = $ar[1];
- break;
- }
- }
- }
-
- /* otherwise see if there are any links from this table to the obj. */
-
- if (($ofield === false) && ($links = $this->links())) {
- foreach ($links as $k => $v) {
- /* link contains {this column} = {linked table}:{linked column} */
- $ar = explode(':', $v);
- if ($ar[0] == $obj->__table) {
- if ($joinCol !== false) {
- if ($k == $joinCol) {
- $tfield = $k;
- $ofield = $ar[1];
- break;
- } else {
- continue;
- }
- } else {
- $tfield = $k;
- $ofield = $ar[1];
- break;
- }
- }
- }
- }
-
- /* did I find a conneciton between them? */
-
- if ($ofield === false) {
- $this->raiseError(
- "joinAdd: {$obj->__table} has no link with {$this->__table}",
- DB_DATAOBJECT_ERROR_NODATA);
- return false;
- }
- $joinType = strtoupper($joinType);
- if ($joinAs === false) {
- $joinAs = $obj->__table;
- }
-
- $quoteIdentifiers = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
-
- $objTable = $quoteIdentifiers ? $DB->quoteIdentifier($obj->__table) : $obj->__table ;
-
-
- // nested (join of joined objects..)
- $appendJoin = '';
- if ($obj->_join) {
- // postgres allows nested queries, with ()'s
- // not sure what the results are with other databases..
- // may be unpredictable..
- if (in_array($DB->dsn["phptype"],array('pgsql'))) {
- $objTable = "($objTable {$obj->_join})";
- } else {
- $appendJoin = $obj->_join;
- }
- }
-
-
- $table = $this->__table;
-
- if ($quoteIdentifiers) {
- $joinAs = $DB->quoteIdentifier($joinAs);
- $table = $DB->quoteIdentifier($table);
- $ofield = $DB->quoteIdentifier($ofield);
- $tfield = $DB->quoteIdentifier($tfield);
- }
-
- $fullJoinAs = '';
- if ($DB->quoteIdentifier($obj->__table) != $joinAs) {
- $fullJoinAs = "AS {$joinAs}";
- }
-
- switch ($joinType) {
- case 'INNER':
- case 'LEFT':
- case 'RIGHT': // others??? .. cross, left outer, right outer, natural..?
- $this->_join .= "\n {$joinType} JOIN {$objTable} {$fullJoinAs}".
- " ON {$joinAs}.{$ofield}={$table}.{$tfield} {$appendJoin} ";
- break;
- case '': // this is just a standard multitable select..
- $this->_join .= "\n , {$objTable} {$fullJoinAs} {$appendJoin}";
- $this->whereAdd("{$joinAs}.{$ofield}={$table}.{$tfield}");
- }
-
- // if obj only a dataobject - eg. no extended class has been defined..
- // it obvioulsy cant work out what child elements might exist...
- // untill we get on the fly querying of tables..
- if ( strtolower(get_class($obj)) == 'db_dataobject') {
- return true;
- }
-
- /* now add where conditions for anything that is set in the object */
-
-
-
- $items = $obj->table();
- // will return an array if no items..
-
- // only fail if we where expecting it to work (eg. not joined on a array)
-
-
-
- if (!$items) {
- $this->raiseError(
- "joinAdd: No table definition for {$obj->__table}",
- DB_DATAOBJECT_ERROR_INVALIDCONFIG);
- return false;
- }
-
- foreach($items as $k => $v) {
- if (!isset($obj->$k)) {
- continue;
- }
-
- $kSql = ($quoteIdentifiers ? $DB->quoteIdentifier($k) : $k);
-
-
- if ($v & DB_DATAOBJECT_STR) {
- $this->whereAdd("{$joinAs}.{$kSql} = " . $DB->quote($obj->$k));
- continue;
- }
- if (is_numeric($obj->$k)) {
- $this->whereAdd("{$joinAs}.{$kSql} = {$obj->$k}");
- continue;
- }
- /* this is probably an error condition! */
- $this->whereAdd("{$joinAs}.{$kSql} = 0");
- }
-
- // and finally merge the whereAdd from the child..
- if (!$obj->_query['condition']) {
- return true;
- }
- $cond = preg_replace('/^\sWHERE/i','',$obj->_query['condition']);
-
- $this->whereAdd("($cond)");
- return true;
-
- }
-
- /**
- * Copies items that are in the table definitions from an
- * array or object into the current object
- * will not override key values.
- *
- *
- * @param array | object $from
- * @param string $format eg. map xxxx_name to $object->name using 'xxxx_%s' (defaults to %s - eg. name -> $object->name
- * @access public
- * @return true on success or array of key=>setValue error message
- */
- function setFrom(&$from, $format = '%s')
- {
- global $_DB_DATAOBJECT;
- $keys = $this->keys();
- $items = $this->table();
- if (!$items) {
- $this->raiseError(
- "setFrom:Could not find table definition for {$this->__table}",
- DB_DATAOBJECT_ERROR_INVALIDCONFIG);
- return;
- }
- $overload_return = array();
- foreach (array_keys($items) as $k) {
- if (in_array($k,$keys)) {
- continue; // dont overwrite keys
- }
- if (!$k) {
- continue; // ignore empty keys!!! what
- }
- if (is_object($from) && isset($from->{sprintf($format,$k)})) {
- $kk = (strtolower($k) == 'from') ? '_from' : $k;
- if (method_exists($this,'set'.$kk)) {
- $ret = $this->{'set'.$kk}($from->{sprintf($format,$k)});
- if (is_string($ret)) {
- $overload_return[$k] = $ret;
- }
- continue;
- }
- $this->$k = $from->{sprintf($format,$k)};
- continue;
- }
-
- if (is_object($from)) {
- continue;
- }
-
- if (!isset($from[sprintf($format,$k)])) {
- continue;
- }
- if (is_object($from[sprintf($format,$k)])) {
- continue;
- }
- if (is_array($from[sprintf($format,$k)])) {
- continue;
- }
- $kk = (strtolower($k) == 'from') ? '_from' : $k;
- if (method_exists($this,'set'. $kk)) {
- $ret = $this->{'set'.$kk}($from[sprintf($format,$k)]);
- if (is_string($ret)) {
- $overload_return[$k] = $ret;
- }
- continue;
- }
- $ret = $this->fromValue($k,$from[sprintf($format,$k)]);
- if ($ret !== true) {
- $overload_return[$k] = 'Not A Valid Value';
- }
- //$this->$k = $from[sprintf($format,$k)];
- }
- if ($overload_return) {
- return $overload_return;
- }
- return true;
- }
-
- /**
- * Returns an associative array from the current data
- * (kind of oblivates the idea behind DataObjects, but
- * is usefull if you use it with things like QuickForms.
- *
- * you can use the format to return things like user[key]
- * by sending it $object->toArray('user[%s]')
- *
- * will also return links converted to arrays.
- *
- * @param string sprintf format for array
- * @access public
- * @return array of key => value for row
- */
-
- function toArray($format = '%s')
- {
- global $_DB_DATAOBJECT;
- $ret = array();
- $ar = isset($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid]) ?
- array_merge($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid],$this->table()) :
- $this->table();
-
- foreach($ar as $k=>$v) {
-
- if (!isset($this->$k)) {
- $ret[sprintf($format,$k)] = '';
- continue;
- }
- // call the overloaded getXXXX() method.
- if (method_exists($this,'get'.$k)) {
- $ret[sprintf($format,$k)] = $this->{'get'.$k}();
- continue;
- }
- // should this call toValue() ???
- $ret[sprintf($format,$k)] = $this->$k;
- }
- if (!$this->_link_loaded) {
- return $ret;
- }
- foreach($this->_link_loaded as $k) {
- $ret[sprintf($format,$k)] = $this->$k->toArray();
-
- }
-
- return $ret;
- }
-
- /**
- * validate - override this to set up your validation rules
- *
- * validate the current objects values either just testing strings/numbers or
- * using the user defined validate{Row name}() methods.
- * will attempt to call $this->validate{column_name}() - expects true = ok false = ERROR
- * you can the use the validate Class from your own methods.
- *
- * @access public
- * @return array of validation results or true
- */
- function validate()
- {
- require_once 'Validate.php';
- $table = $this->table();
- $ret = array();
-
- foreach($table as $key => $val) {
-
-
- // call user defined validation always...
- $method = "Validate" . ucfirst($key);
- if (method_exists($this, $method)) {
- $ret[$key] = $this->$method();
- continue;
- }
-
- // if not null - and it's not set.......
-
- if (!isset($this->$key) && ($val & DB_DATAOBJECT_NOTNULL)) {
- $ret[$key] = false;
- continue;
- }
-
- if (is_string($this->$key) && (strtolower($this->$key) == 'null') && ($val & DB_DATAOBJECT_NOTNULL)) {
- $ret[$key] = false;
- continue;
- }
- // ignore things that are not set. ?
-
- if (!isset($this->$key)) {
- continue;
- }
-
- // if the string is empty.. assume it is ok..
- if (!is_object($this->$key) && !is_array($this->$key) && !strlen((string) $this->$key)) {
- continue;
- }
-
- switch (true) {
- // todo: date time.....
-
-
- case ($val & DB_DATAOBJECT_STR):
- $ret[$key] = Validate::string($this->$key, VALIDATE_PUNCTUATION . VALIDATE_NAME);
- continue;
- case ($val & DB_DATAOBJECT_INT):
- $ret[$key] = Validate::number($this->$key, array('decimal'=>'.'));
- continue;
- }
- }
-
- foreach ($ret as $key => $val) {
- if ($val === false) {
- return $ret;
- }
- }
- return true; // everything is OK.
- }
-
- /**
- * Gets the DB object related to an object - so you can use funky peardb stuf with it :)
- *
- * @access public
- * @return object The DB connection
- */
- function &getDatabaseConnection()
- {
- global $_DB_DATAOBJECT;
-
- if (($e = $this->_connect()) !== true) {
- return $e;
- }
- if (!isset($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
- return false;
- }
- return $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
- }
-
-
- /**
- * Gets the DB result object related to the objects active query
- * - so you can use funky pear stuff with it - like pager for example.. :)
- *
- * @access public
- * @return object The DB result object
- */
-
- function &getDatabaseResult()
- {
- global $_DB_DATAOBJECT;
- $this->_connect();
- if (!isset($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid])) {
- return false;
- }
- return $_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid];
- }
-
- /**
- * Overload Extension support
- * - enables setCOLNAME/getCOLNAME
- * if you define a set/get method for the item it will be called.
- * otherwise it will just return/set the value.
- * NOTE this currently means that a few Names are NO-NO's
- * eg. links,link,linksarray, from, Databaseconnection,databaseresult
- *
- * note
- * - set is automatically called by setFrom.
- * - get is automatically called by toArray()
- *
- * setters return true on success. = strings on failure
- * getters return the value!
- *
- * this fires off trigger_error - if any problems.. pear_error,
- * has problems with 4.3.2RC2 here
- *
- * @access public
- * @return true?
- * @see overload
- */
-
-
- function _call($method,$params,&$return) {
-
- //$this->debug("ATTEMPTING OVERLOAD? $method");
- // ignore constructors : - mm
- if (strtolower($method) == strtolower(get_class($this))) {
- return true;
- }
- $type = strtolower(substr($method,0,3));
- $class = get_class($this);
- if (($type != 'set') && ($type != 'get')) {
- return false;
- }
-
-
-
- // deal with naming conflick of setFrom = this is messy ATM!
-
- if (strtolower($method) == 'set_from') {
- $return = $this->toValue('from',isset($params[0]) ? $params[0] : null);
- return true;
- }
-
- $element = substr($method,3);
- if ($element{0} == '_') {
- return false;
- }
-
-
- // dont you just love php's case insensitivity!!!!
-
- $array = array_keys(get_class_vars($class));
-
- if (!in_array($element,$array)) {
- // munge case
- foreach($array as $k) {
- $case[strtolower($k)] = $k;
- }
- if ((substr(phpversion(),0,1) == 5) && isset($case[strtolower($element)])) {
- trigger_error("PHP5 set/get calls should match the case of the variable",E_USER_WARNING);
- $element = strtolower($element);
- }
-
- // does it really exist?
- if (!isset($case[$element])) {
- return false;
- }
- // use the mundged case
- $element = $case[$element]; // real case !
- }
-
-
- if ($type == 'get') {
- $return = $this->toValue($element,isset($params[0]) ? $params[0] : null);
- return true;
- }
-
-
- $return = $this->fromValue($element, $params[0]);
-
- return true;
-
-
- }
-
-
- /**
- * standard set* implementation.
- *
- * takes data and uses it to set dates/strings etc.
- * normally called from __call..
- *
- * Current supports
- * date = using (standard time format, or unixtimestamp).... so you could create a method :
- * function setLastread($string) { $this->fromValue('lastread',strtotime($string)); }
- *
- * time = using strtotime
- * datetime = using same as date - accepts iso standard or unixtimestamp.
- * string = typecast only..
- *
- * TODO: add formater:: eg. d/m/Y for date! ???
- *
- * @param string column of database
- * @param mixed value to assign
- *
- * @return true| false (False on error)
- * @access public
- * @see DB_DataObject::_call
- */
-
-
- function fromValue($col,$value)
- {
- $cols = $this->table();
- // dont know anything about this col..
- if (!isset($cols[$col])) {
- $this->$col = $value;
- return true;
- }
- //echo "FROM VALUE $col, {$cols[$col]}, $value\n";
- switch (true) {
- // set to null and column is can be null...
- case ((strtolower($value) == 'null') && (!($cols[$col] & DB_DATAOBJECT_NOTNULL))):
- case (is_object($value) && is_a($value,'DB_DataObject_Cast')):
- $this->$col = $value;
- return true;
-
- // fail on setting null on a not null field..
- case ((strtolower($value) == 'null') && ($cols[$col] & DB_DATAOBJECT_NOTNULL)):
- return false;
-
- case (($cols[$col] & DB_DATAOBJECT_DATE) && ($cols[$col] & DB_DATAOBJECT_TIME)):
- // empty values get set to '' (which is inserted/updated as NULl
- if (!$value) {
- $this->$col = '';
- }
-
- if (is_numeric($value)) {
- $this->$col = date('Y-m-d H:i:s', $value);
- return true;
- }
-
- // eak... - no way to validate date time otherwise...
- $this->$col = (string) $value;
- return true;
-
- case ($cols[$col] & DB_DATAOBJECT_DATE):
- // empty values get set to '' (which is inserted/updated as NULl
-
- if (!$value) {
- $this->$col = '';
- }
-
- if (is_numeric($value)) {
- echo "it's numberic?";
- $this->$col = date('Y-m-d',$value);
- return true;
- }
-
- // try date!!!!
- require_once 'Date.php';
- $x = new Date($value);
- $this->$col = $x->format("%Y-%m-%d");
- return true;
-
- case ($cols[$col] & DB_DATAOBJECT_TIME):
- // empty values get set to '' (which is inserted/updated as NULl
- if (!$value) {
- $this->$col = '';
- }
-
- $guess = strtotime($value);
- if ($guess != -1) {
- $this->$col = date('H:i:s', $guess);
- return $return = true;
- }
- // otherwise an error in type...
- return false;
-
- case ($cols[$col] & DB_DATAOBJECT_STR):
-
- $this->$col = (string) $value;
- return true;
-
- // todo : floats numerics and ints...
- default:
- $this->$col = $value;
- return true;
- }
-
-
-
- }
- /**
- * standard get* implementation.
- *
- * with formaters..
- * supported formaters:
- * date/time : %d/%m/%Y (eg. php strftime) or pear::Date
- * numbers : %02d (eg. sprintf)
- * NOTE you will get unexpected results with times like 0000-00-00 !!!
- *
- *
- *
- * @param string column of database
- * @param format foramt
- *
- * @return true Description
- * @access public
- * @see DB_DataObject::_call(),strftime(),Date::format()
- */
- function toValue($col,$format = null)
- {
- if (is_null($format)) {
- return $this->$col;
- }
- $cols = $this->table();
- switch (true) {
- case (($cols[$col] & DB_DATAOBJECT_DATE) && ($cols[$col] & DB_DATAOBJECT_TIME)):
- if (!$this->$col) {
- return '';
- }
- $guess = strtotime($this->$col);
- if ($guess != -1) {
- return strftime($format, $guess);
- }
- // eak... - no way to validate date time otherwise...
- return $this->$col;
- case ($cols[$col] & DB_DATAOBJECT_DATE):
- if (!$this->$col) {
- return '';
- }
- $guess = strtotime($this->$col);
- if ($guess != -1) {
- return strftime($format,$guess);
- }
- // try date!!!!
- require_once 'Date.php';
- $x = new Date($this->$col);
- return $x->format($format);
-
- case ($cols[$col] & DB_DATAOBJECT_TIME):
- if (!$this->$col) {
- return '';
- }
- $guess = strtotime($this->$col);
- if ($guess > -1) {
- return strftime($format, $guess);
- }
- // otherwise an error in type...
- return $this->$col;
-
- case ($cols[$col] & DB_DATAOBJECT_MYSQLTIMESTAMP):
- if (!$this->$col) {
- return '';
- }
- require_once 'Date.php';
-
- $x = new Date($this->$col);
-
- return $x->format($format);
-
-
- default:
- return sprintf($format,$this->col);
- }
-
-
- }
-
-
- /* ----------------------- Debugger ------------------ */
-
- /**
- * Debugger. - use this in your extended classes to output debugging information.
- *
- * Uses DB_DataObject::DebugLevel(x) to turn it on
- *
- * @param string $message - message to output
- * @param string $logtype - bold at start
- * @param string $level - output level
- * @access public
- * @return none
- */
- function debug($message, $logtype = 0, $level = 1)
- {
- global $_DB_DATAOBJECT;
-
- if (empty($_DB_DATAOBJECT['CONFIG']['debug']) ||
- (is_int($_DB_DATAOBJECT['CONFIG']['debug']) && $_DB_DATAOBJECT['CONFIG']['debug'] < $level)) {
- return;
- }
- // this is a bit flaky due to php's wonderfull class passing around crap..
- // but it's about as good as it gets..
- $class = (isset($this) && is_a($this,'DB_DataObject')) ? get_class($this) : 'DB_DataObject';
-
- if (!is_string($message)) {
- $message = print_r($message,true);
- }
- if (!is_int( $_DB_DATAOBJECT['CONFIG']['debug']) && is_callable( $_DB_DATAOBJECT['CONFIG']['debug'])) {
- return call_user_func($_DB_DATAOBJECT['CONFIG']['debug'], $class, $message, $logtype, $level);
- }
-
- if (!ini_get('html_errors')) {
- echo "$class : $logtype : $message\n";
- flush();
- return;
- }
- if (!is_string($message)) {
- $message = print_r($message,true);
- }
- echo "<code><B>$class: $logtype:</B> $message</code><BR>\n";
- flush();
- }
-
- /**
- * sets and returns debug level
- * eg. DB_DataObject::debugLevel(4);
- *
- * @param int $v level
- * @access public
- * @return none
- */
- function debugLevel($v = null)
- {
- global $_DB_DATAOBJECT;
- if (empty($_DB_DATAOBJECT['CONFIG'])) {
- DB_DataObject::_loadConfig();
- }
- if ($v !== null) {
- $r = isset($_DB_DATAOBJECT['CONFIG']['debug']) ? $_DB_DATAOBJECT['CONFIG']['debug'] : 0;
- $_DB_DATAOBJECT['CONFIG']['debug'] = $v;
- return $r;
- }
- return isset($_DB_DATAOBJECT['CONFIG']['debug']) ? $_DB_DATAOBJECT['CONFIG']['debug'] : 0;
- }
-
- /**
- * Last Error that has occured
- * - use $this->_lastError or
- * $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
- *
- * @access public
- * @var object PEAR_Error (or false)
- */
- var $_lastError = false;
-
- /**
- * Default error handling is to create a pear error, but never return it.
- * if you need to handle errors you should look at setting the PEAR_Error callback
- * this is due to the fact it would wreck havoc on the internal methods!
- *
- * @param int $message message
- * @param int $type type
- * @param int $behaviour behaviour (die or continue!);
- * @access public
- * @return error object
- */
- function raiseError($message, $type = null, $behaviour = null)
- {
- global $_DB_DATAOBJECT;
-
- if ($behaviour == PEAR_ERROR_DIE && !empty($_DB_DATAOBJECT['CONFIG']['dont_die'])) {
- $behaviour = null;
- }
-
- if (PEAR::isError($message)) {
- $error = $message;
- } else {
- require_once 'DB/DataObject/Error.php';
- $error = PEAR::raiseError($message, $type, $behaviour,
- $opts=null, $userinfo=null, 'DB_DataObject_Error'
- );
- }
- // this will never work totally with PHP's object model.
- // as this is passed on static calls (like staticGet in our case)
-
- if (@is_object($this) && is_subclass_of($this,'db_dataobject')) {
- $this->_lastError = $error;
- }
-
- $_DB_DATAOBJECT['LASTERROR'] = $error;
-
- // no checks for production here?.......
- DB_DataObject::debug($message,"ERROR",1);
- return $error;
- }
-
- /**
- * Define the global $_DB_DATAOBJECT['CONFIG'] as an alias to PEAR::getStaticProperty('DB_DataObject','options');
- *
- * After Profiling DB_DataObject, I discoved that the debug calls where taking
- * considerable time (well 0.1 ms), so this should stop those calls happening. as
- * all calls to debug are wrapped with direct variable queries rather than actually calling the funciton
- * THIS STILL NEEDS FURTHER INVESTIGATION
- *
- * @access public
- * @return object an error object
- */
- function _loadConfig()
- {
- global $_DB_DATAOBJECT;
-
- $_DB_DATAOBJECT['CONFIG'] = &PEAR::getStaticProperty('DB_DataObject','options');
-
-
- }
- /**
- * Free global arrays associated with this object.
- *
- * Note: as we now store resultfields in a global, it is never freed, if you do alot of calls to find(),
- * memory will grow gradually.
- *
- *
- * @access public
- * @return none
- */
- function free()
- {
- global $_DB_DATAOBJECT;
-
- if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid])) {
- unset($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid]);
- }
- if (isset($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid])) {
- unset($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid]);
- }
- // this is a huge bug in DB!
- $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->num_rows = array();
-
- }
-
-
- /* ---- LEGACY BC METHODS - NOT DOCUMENTED - See Documentation on New Methods. ---*/
-
- function _get_table() { return $this->table(); }
- function _get_keys() { return $this->keys(); }
-
-
-
-
-}
-// technially 4.3.2RC1 was broken!!
-// looks like 4.3.3 may have problems too....
-if (!defined('DB_DATAOBJECT_NO_OVERLOAD')) {
-
- if ((phpversion() != '4.3.2-RC1') && (version_compare( phpversion(), "4.3.1") > 0)) {
- if (version_compare( phpversion(), "5") < 0) {
- overload('DB_DataObject');
- }
- $GLOBALS['_DB_DATAOBJECT']['OVERLOADED'] = true;
- }
-}
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Alan Knowles <alan@akbkhome.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Cast.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
-//
-// Prototype Castable Object.. for DataObject queries
-//
-
-/**
-*
-* @abstract Storage for Data that may be cast into a variety of formats.
-*
-* Common usages:
-* // blobs
-* $data = DB_DataObject_Cast::blob($somefile);
-* $data = DB_DataObject_Cast::string($somefile);
-* $dataObject->someblobfield = $data
-*
-* // dates?
-* $d1 = new DB_DataObject_Cast::date('12/12/2000');
-* $d2 = new DB_DataObject_Cast::date(2000,12,30);
-* $d3 = new DB_DataObject_Cast::date($d1->year, $d1->month+30, $d1->day+30);
-*
-* // time, datetime.. ?????????
-*
-* // raw sql????
-* $data = DB_DataObject_Cast::sql('cast("123123",datetime)');
-* $data = DB_DataObject_Cast::sql('NULL');
-*
-* // int's/string etc. are proably pretty pointless..!!!!
-*
-*
-* inside DB_DataObject,
-* if (is_a($v,'db_dataobject_class')) {
-* $value .= $v->toString(DB_DATAOBJECT_INT,'mysql');
-* }
-*
-*
-*
-*
-* @version $Id: Cast.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
-*/
-class DB_DataObject_Cast {
-
- /**
- * Type of data Stored in the object..
- *
- * @var string (date|blob|.....?)
- * @access public
- */
- var $type;
-
- /**
- * Data For date representation
- *
- * @var int day/month/year
- * @access public
- */
- var $day;
- var $month;
- var $year;
-
-
- /**
- * Generic Data..
- *
- * @var string
- * @access public
- */
-
- var $value;
-
-
-
- /**
- * Blob consructor
- *
- * create a Cast object from some raw data.. (binary)
- *
- *
- * @param string (with binary data!)
- *
- * @return object DB_DataObject_Cast
- * @access public
- */
-
- function blob($value) {
- $r = new DB_DataObject_Cast;
- $r->type = 'blob';
- $r->value = $value;
- return $r;
- }
-
-
- /**
- * String consructor (actually use if for ints and everything else!!!
- *
- * create a Cast object from some string (not binary)
- *
- *
- * @param string (with binary data!)
- *
- * @return object DB_DataObject_Cast
- * @access public
- */
-
- function string($value) {
- $r = new DB_DataObject_Cast;
- $r->type = 'string';
- $r->value = $value;
- return $r;
- }
-
- /**
- * SQL constructor (for raw SQL insert)
- *
- * create a Cast object from some sql
- *
- * @param string (with binary data!)
- *
- * @return object DB_DataObject_Cast
- * @access public
- */
-
- function sql($value) {
- $r = new DB_DataObject_Cast;
- $r->type = 'sql';
- $r->value = $value;
- return $r;
- }
-
-
- /**
- * Date Constructor
- *
- * create a Cast object from some string (not binary)
- *
- *
- * @param vargs... accepts
- * dd/mm
- * dd/mm/yyyy
- * yyyy-mm
- * yyyy-mm-dd
- * array(yyyy,dd)
- * array(yyyy,dd,mm)
- *
- *
- *
- * @return object DB_DataObject_Cast
- * @access public
- */
-
- function date() {
- $args = func_get_args();
- switch(count($args)) {
- case 0: // no args = today!
- $bits = explode('-',date('Y-m-d'));
- break;
- case 1: // one arg = a string
-
- if (strpos($args[0],'/') !== false) {
- $bits = array_reverse(explode('/',$args[0]));
- } else {
- $bits = explode('-',$args[0]);
- }
- default: // 2 or more..
- $bits = $args;
- }
- if (count($bits) == 1) { // if YYYY set day = 1st..
- $bits[] = 1;
- }
-
- if (count($bits) == 2) { // if YYYY-DD set day = 1st..
- $bits[] = 1;
- }
-
- // if year < 1970 we cant use system tools to check it...
- // so we make a few best gueses....
- // basically do date calculations for the year 2000!!!
- // fix me if anyone has more time...
- if (($bits[0] < 1975) || ($bits[0] > 2030)) {
- $oldyear = $bits[0];
- $bits = explode('-',date('Y-m-d',mktime(1,1,1,$bits[1],$bits[2],2000)));
- $bits[0] = ($bits[0] - 2000) + $oldyear;
- } else {
- // now mktime
- $bits = explode('-',date('Y-m-d',mktime(1,1,1,$bits[1],$bits[2],$bits[0])));
- }
- $r = new DB_DataObject_Cast;
- $r->type = 'date';
- list($r->year,$r->month,$r->day) = $bits;
- return $r;
- }
-
- /**
- * get the string to use in the SQL statement for this...
- *
- *
- * @param int $to Type (DB_DATAOBJECT_*
- * @param string $db (eg. mysql|mssql.....)
- *
- *
- * @return string
- * @access public
- */
-
- function toString($to=false,$db='mysql') {
- // if $this->type is not set, we are in serious trouble!!!!
- // values for to:
- $method = 'toStringFrom'.$this->type;
- return $this->$method($to,$db);
- }
-
- /**
- * get the string to use in the SQL statement from a blob of binary data
- * ** Suppots only blob->postgres::bytea
- *
- * @param int $to Type (DB_DATAOBJECT_*
- * @param string $db (eg. mysql|mssql.....)
- *
- *
- * @return string
- * @access public
- */
- function toStringFromBlob($to,$db) {
- // first weed out invalid casts..
- // in blobs can only be cast to blobs.!
-
- // perhaps we should support TEXT fields???
-
- if (!($to & DB_DATAOBJECT_BLOB)) {
- return PEAR::raiseError('Invalid Cast from a DB_DataObject_Cast::blob to something other than a blob!');
- }
-
- switch ($db) {
- case 'pgsql':
- return "'".pg_escape_bytea($this->value)."'::bytea";
-
- default:
- return PEAR::raiseError("DB_DataObject_Cast cant handle blobs for Database:$db Yet");
- }
-
- }
-
- /**
- * get the string to use in the SQL statement for a blob from a string!
- * ** Suppots only string->postgres::bytea
- *
- *
- * @param int $to Type (DB_DATAOBJECT_*
- * @param string $db (eg. mysql|mssql.....)
- *
- *
- * @return string
- * @access public
- */
- function toStringFromString($to,$db) {
- // first weed out invalid casts..
- // in blobs can only be cast to blobs.!
-
- // perhaps we should support TEXT fields???
- //
-
- if (!($to & DB_DATAOBJECT_BLOB)) {
- return PEAR::raiseError('Invalid Cast from a DB_DataObject_Cast::string to something other than a blob!'.
- ' (why not just use native features)');
- }
-
- switch ($db) {
- case 'pgsql':
- return "'".pg_escape_string($this->value)."'::bytea";
-
- default:
- return PEAR::raiseError("DB_DataObject_Cast cant handle blobs for Database:$db Yet");
- }
-
- }
-
-
- /**
- * get the string to use in the SQL statement for a date
- *
- *
- *
- * @param int $to Type (DB_DATAOBJECT_*
- * @param string $db (eg. mysql|mssql.....)
- *
- *
- * @return string
- * @access public
- */
- function toStringFromDate($to,$db) {
- // first weed out invalid casts..
- // in blobs can only be cast to blobs.!
- // perhaps we should support TEXT fields???
- //
-
- if (($to !== false) && !($to & DB_DATAOBJECT_DATE)) {
- return PEAR::raiseError('Invalid Cast from a DB_DataObject_Cast::string to something other than a date!'.
- ' (why not just use native features)');
- }
- return "'{$this->year}-{$this->month}-{$this->day}'";
- }
-
-
-
- /**
- * get the string to use in the SQL statement for a raw sql statement.
- *
- * @param int $to Type (DB_DATAOBJECT_*
- * @param string $db (eg. mysql|mssql.....)
- *
- *
- * @return string
- * @access public
- */
- function toStringFromSql($to,$db) {
- return $this->value;
- }
-
-
-
-
-}
-
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Alan Knowles <alan@akbkhome.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Error.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
-//
-// DataObjects error handler, loaded on demand...
-//
-
-/**
- * DB_DataObject_Error is a quick wrapper around pear error, so you can distinguish the
- * error code source.
- * messages.
- *
- * @package DB_DataObject
- * @author Alan Knowles <alan@akbkhome.com>
- */
-class DB_DataObject_Error extends PEAR_Error
-{
-
- /**
- * DB_DataObject_Error constructor.
- *
- * @param mixed $code DB error code, or string with error message.
- * @param integer $mode what "error mode" to operate in
- * @param integer $level what error level to use for $mode & PEAR_ERROR_TRIGGER
- * @param mixed $debuginfo additional debug info, such as the last query
- *
- * @access public
- *
- * @see PEAR_Error
- */
- function DB_DataObject_Error($message = '', $code = DB_ERROR, $mode = PEAR_ERROR_RETURN,
- $level = E_USER_NOTICE)
- {
- $this->PEAR_Error('DB_DataObject Error: ' . $message, $code, $mode, $level);
-
- }
-
-
- // todo : - support code -> message handling, and translated error messages...
-
-
-
-}
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Markus Wolff <mw21st@php.net> |
-// +----------------------------------------------------------------------+
-
-/**
- * This class adds some nice utility methods to the DataObject class
- * to speed up prototyping new applications - like auto-generating fully
- * functional forms using HTML_QuickForm.
- *
- * All the settings for FormBuilder must be in a section [DB_DataObject_FormBuilder]
- * within the DataObject.ini file (or however you've named it).
- * If you stuck to the DB_DataObject example in the doc, you'll read in your
- * config like this:
- * <code>
- * $config = parse_ini_file('DataObject.ini', true);
- * foreach ($config as $class => $values) {
- * $options = &PEAR::getStaticProperty($class, 'options');
- * $options = $values;
- * }
- * </code>
- * Unfortunately, DataObject will overwrite FormBuilder's settings when first instantiated,
- * so you'll have to add another line after that:
- * <code>
- * $_DB_DATAOBJECT_FORMBUILDER['CONFIG'] = $config['DB_DataObject_FormBuilder'];
- * </code>
- * Now you're ready to go!
- *
- * You can also set any option through your DB_DataObject derived classes by
- * appending 'fb_' to the option name. Ex: 'fb_fieldLabels'. This is the
- * preferred way of setting DataObject-specific options.
- *
- * You may also set all options manually by setting them in the DO ir FB objects.
- *
- * You may also set the options in an FB derived class, but this isn't as well
- * supported.
- *
- * In addition, there are special methods you can define in your DataObject classes for even more control.
- * <ul>
- * <li>preGenerateForm(&$formBuilder):
- * This method will be called before the form is generated. Use this to change
- * property values or options in your DataObject. This is the normal plave to
- * set up fb_preDefElements. Note: the $formBuilder object passed in has not
- * yet copied the options from the DataObject into it. If you plan to use the
- * functions in FB in this method, call populateOptions() on it first.
- * </li>
- * <li>postGenerateForm(&$form):
- * This method will be called after the form is generated. The form is passed in by reference so you can
- * alter it. Use this method to add, remove, or alter elements in the form or the form itself.
- * </li>
- * <li>preProcessForm(&$values):
- * This method is called just before FormBuilder processes the submitted form data. The values are sent
- * by reference in the first parameter as an associative array. The key is the element name and the value
- * the submitted value. You can alter the values as you see fit (md5 on passwords, for example).
- * </li>
- * <li>postProcessForm(&$values):
- * This method is called just after FormBuilder processed the submitted form data. The values are again
- * sent by reference. This method could be used to inform the user of changes, alter the DataObject, etc.
- * </li>
- * <li>getForm():
- * If this function exists, it will be used instead of FormBuilder's internal form generation routines
- * Use this only if you want to create the entire form on your own.
- * </li>
- * </ul>
- *
- * Note for PHP5-users: These properties have to be public! In general, you can
- * override all settings from the .ini file by setting similarly-named properties
- * in your DataObject classes.
- *
- * <b>Most basic usage:</b>
- * <code>
- * $do =& new MyDataObject();
- * // Insert "$do->get($some_id);" here to edit an existing object instead of making a new one
- * $fg =& DB_DataObject_FormBuilder::create($do);
- * $form =& $fg->getForm();
- * if ($form->validate()) {
- * $form->process(array(&$fg,'processForm'), false);
- * $form->freeze();
- * }
- * $form->display();
- * </code>
- *
- * For more information on how to use the DB_DataObject or HTML_QuickForm packages
- * themselves, please see the excellent documentation on http://pear.php.net/.
- *
- * @package DB_DataObject_FormBuilder
- * @author Markus Wolff <mw21st@php.net>
- * @version $Id: FormBuilder.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
- */
-
-// Import requirements
-require_once ('DB/DataObject.php');
-
-// Constants used for forceQueryType()
-define ('DB_DATAOBJECT_FORMBUILDER_QUERY_AUTODETECT', 0);
-define ('DB_DATAOBJECT_FORMBUILDER_QUERY_FORCEINSERT', 1);
-define ('DB_DATAOBJECT_FORMBUILDER_QUERY_FORCEUPDATE', 2);
-define ('DB_DATAOBJECT_FORMBUILDER_QUERY_FORCENOACTION', 3);
-
-// Constants used for cross/triple links
-define ('DB_DATAOBJECT_FORMBUILDER_CROSSLINK', 1048576);
-define ('DB_DATAOBJECT_FORMBUILDER_TRIPLELINK', 2097152);
-define ('DB_DATAOBJECT_FORMBUILDER_ENUM', 4194304);
-define ('DB_DATAOBJECT_FORMBUILDER_REVERSELINK',8388608);
-
-// Error code constants
-define ('DB_DATAOBJECT_FORMBUILDER_ERROR_UNKNOWNDRIVER', 4711);
-define ('DB_DATAOBJECT_FORMBUILDER_ERROR_NODATAOBJECT', 4712);
-
-class DB_DataObject_FormBuilder
-{
- //PROTECTED vars
- /**
- * If you want to use the generator on an existing form object, pass it
- * to the factory method within the options array, element name: 'form'
- * (who would have guessed?)
- *
- * @access protected
- * @see DB_DataObject_Formbuilder()
- */
- var $_form = false;
-
- /**
- * Contains the last validation errors, if validation checking is enabled.
- *
- * @access protected
- */
- var $_validationErrors = false;
-
- /**
- * Used to determine which action to perform with the submitted data in processForm()
- *
- * @access protected
- */
- var $_queryType = DB_DATAOBJECT_FORMBUILDER_QUERY_AUTODETECT;
-
- /**
- * If false, FormBuilder will use the form object from $_form as a basis for the new
- * form: It will just add elements to the existing form object, not generate a new one.
- * If true, FormBuilder will generate a new form object, create all elements as needed for
- * the given DataObject, then strip the elements from the exiting form object in $_form
- * and add it to the newly generated form object.
- *
- * @access protected
- */
- var $_appendForm = false;
-
-
-
- //PUBLIC vars
- /**
- * Add a header to the form - if set to true, the form will
- * have a header element as the first element in the form.
- *
- * @access public
- * @see formHeaderText
- */
- var $addFormHeader = true;
-
- /**
- * Text for the form header. If not set, the name of the database
- * table this form represents will be used.
- *
- * @access public
- * @see addFormHeader
- */
- var $formHeaderText = null;
-
- /**
- * Text that is displayed as an error message if a validation rule
- * is violated by the user's input. Use %s to insert the field name.
- *
- * @access public
- * @see requiredRuleMessage
- */
- var $ruleViolationMessage = '%s: The value you have entered is not valid.';
-
- /**
- * Text that is displayed as an error message if a required field is
- * left empty. Use %s to insert the field name.
- *
- * @access public
- * @see ruleViolationMessage
- */
- var $requiredRuleMessage = 'The field %s is required.';
-
- /**
- * If set to TRUE, the current DataObject's validate method is being called
- * before the form data is processed. If errors occur, no insert/update operation
- * will be made on the database. Use getValidationErrors() to retrieve the reasons
- * for a failure.
- * Defaults to FALSE.
- *
- * @access public
- */
- var $validateOnProcess = false;
-
- /**
- * The language used in date fields. See documentation of HTML_Quickform's
- * date element for more information.
- *
- * @see HTML_QuickForm_date
- */
- var $dateFieldLanguage = 'en';
-
- /**
- * Callback method to convert a date from the format it is stored
- * in the database to the format used by the QuickForm element that
- * handles date values. Must have a format usable with call_user_func().
- */
- var $dateFromDatabaseCallback = array('DB_DataObject_FormBuilder','_date2array');
-
- /**
- * Callback method to convert a date from the format used by the QuickForm
- * element that handles date values to the format the database can store it in.
- * Must have a format usable with call_user_func().
- */
- var $dateToDatabaseCallback = array('DB_DataObject_FormBuilder','_array2date');
-
- /**
- * A format string that represents the display settings for QuickForm date elements.
- * Example: "d-m-Y". See QuickForm documentation for details on format strings.
- * Legal letters to use in the format string that work with FormBuilder are:
- * d,m,Y,H,i,s
- */
- var $dateElementFormat = 'd-m-Y';
-
- /**
- * A format string that represents the display settings for QuickForm time elements.
- * Example: "H:i:s". See QuickForm documentation for details on format strings.
- * Legal letters to use in the format string that work with FormBuilder are:
- * d,m,Y,H,i,s
- */
- var $timeElementFormat = 'H:i:s';
-
- /**
- * A format string that represents the display settings for QuickForm datetime elements.
- * Example: "d-m-Y H:i:s". See QuickForm documentation for details on format strings.
- * Legal letters to use in the format string that work with FormBuilder are:
- * d,m,Y,H,i,s
- */
- var $dateTimeElementFormat = 'd-m-Y H:i:s';
-
- /**
- * This is for the future support of string date formats other than ISO, but
- * currently, that's the only supported one. Set to 1 for ISO, other values
- * may be available later on.
- */
- var $dbDateFormat = 1;
-
- /**
- * These fields will be used when displaying a link record. The fields
- * listed will be seperated by ", ". If you specify a link field as a
- * display field and linkDisplayLevel is not 0, the link will be followed
- * and the display fields of the record linked to displayed within parenthesis.
- *
- * For example, say we have these tables:
- *
- * [person]
- *
- * name = 130
- * gender_id = 129
- *
- * [gender]
- * id = 129
- * name = 130
- *
- *
- * this link:
- *
- * [person]
- * gender_id = gender:id
- *
- *
- * and this data:
- * Person:
- * name: "Justin Patrin"
- * gender_id: 1
- * Gender:
- * id: 1
- * name: "male"
- *
- * If person's display fields are:
- * <?php
- * class DataObject_Person extends DB_DataObject {
- * //...
- * var $fb_linkDisplayFields = array('name', 'gender_id');
- * }
- * ?>
- *
- * and gender's display fields are:
- * <?php
- * class DataObject_Gender extends DB_DataObject {
- * //...
- * var $fb_linkDisplayFields = array('name');
- * }
- * ?>
- *
- * and we set linkDisplayLevel to 0, the person record will be displayed as:
- * "Justin Patrin, 1"
- *
- * If we set linkDisplayLevel to 1, the person record will be displayed as:
- * "Justin Patrin, (male)"
- */
- var $linkDisplayFields = array();
-
- /**
- * The fields to be used for sorting the options of an auto-generated link
- * element. You can specify ASC and DESC in these options as well:
- * <?php
- * class DataObject_SomeTable extends DB_DataObject {
- * //...
- * var $fb_linkOrderFields = array('field1', 'field2 DESC');
- * }
- * ?>
- *
- * You may also want to escape the field names if they are reserved words in
- * the database you're using:
- * <?php
- * class DataObject_SomeTable extends DB_DataObject {
- * //...
- * function preGenerateForm() {
- * $db = $this->getDatabaseConnection();
- * $this->fb_linkOrderFields = array($db->quoteIdentifier('config'),
- * $db->quoteIdentifier('select').' DESC');
- * }
- * }
- * ?>
- */
- var $linkOrderFields = array();
-
- /**
- * The caption of the submit button, if created.
- */
- var $submitText = 'Submit';
-
- /**
- * If set to false, no submit button will be created for your forms. Useful when
- * used together with QuickForm_Controller when you already have submit buttons
- * for next/previous page. By default, a button is being generated.
- */
- var $createSubmit = true;
-
- /**
- * Array of field labels. The key of the element is the field name. Use this if
- * you want to keep the auto-generated elements, but still define your
- * own labels for them.
- */
- var $fieldLabels = array();
-
- /**
- * Array of fields to render elements for. If a field is not given, it will not
- * be rendered. If empty, all fields will be rendered (except, normally, the
- * primary key).
- */
- var $fieldsToRender = array();
-
- /**
- * Array of fields which the user can edit. If a field is rendered but not
- * specified in this array, it will be frozen. Ignored if not given.
- */
- var $userEditableFields = array();
-
- /**
- * Array of groups to put certain elements in. The key is an element name, the
- * value is the group to put the element in.
- */
- var $preDefGroups = array();
-
- /**
- * Indexed array of element names. If defined, this will determine the order
- * in which the form elements are being created. This is useful if you're
- * using QuickForm's default renderer or dynamic templates and the order of
- * the fields in the database doesn't match your needs.
- */
- var $preDefOrder = array();
-
- /**
- * Array of user-defined QuickForm elements that will be used for the field
- * matching the array key. If no match is found, the element for that field
- * will be auto-generated. Make your element objects either in the
- * preGenerateForm() method or in the getForm() method. Use
- * HTML_QuickForm::createElement() to do this.
- *
- * If you wish to put in a group of elements in place of a single element,
- * you can put an array in preDefElements instead of a single element. The
- * name of the group will be the name of the replaced element.
- */
- var $preDefElements = array();
-
- /**
- * An array of the link or date fields which should have an empty option added to the
- * select box. This is only a valid option for fields which link to another
- * table or date fields.
- */
- var $selectAddEmpty = array();
-
- /**
- * An string to put in the "empty option" added to select fields
- */
- var $selectAddEmptyLabel = '';
-
- /**
- * By default, hidden fields are generated for the primary key of a
- * DataObject. This behaviour can be deactivated by setting this option to
- * false.
- */
- var $hidePrimaryKey = true;
-
- /**
- * A simple array of field names indicating which of the fields in a particular
- * table/class are actually to be treated as textareas. This is an unfortunate
- * workaround that is neccessary because the DataObject generator script does
- * not make a difference between any other datatypes than string and integer.
- * When it does, this can be dropped.
- */
- var $textFields = array();
-
- /**
- * A simple array of field names indicating which of the fields in a particular
- * table/class are actually to be treated date fields. This is an unfortunate
- * workaround that is neccessary because the DataObject generator script does
- * not make a difference between any other datatypes than string and integer.
- * When it does, this can be dropped.
- */
- var $dateFields = array();
-
- /**
- * A simple array of field names indicating which of the fields in a particular
- * table/class are actually to be treated time fields. This is an unfortunate
- * workaround that is neccessary because the DataObject generator script does
- * not make a difference between any other datatypes than string and integer.
- * When it does, this can be dropped.
- */
- var $timeFields = array();
-
- /**
- * Array to configure the type of the link elements. By default, a select box
- * will be used. The key is the name of the link element. The value is 'radio'
- * or 'select'. If you choose 'radio', radio buttons will be made instead of
- * a select box.
- */
- var $linkElementTypes = array();
-
- /**
- * A simple array of fields names which should be treated as ENUMs. A select
- * box will be created with the enum options. If you add this field to the
- * linkElementTypes array and give it a 'radio' type, you will get radio buttons
- * instead.
- *
- * The default handler for enums is only tested in mysql. If you are using a
- * different DB backend, use enumOptionsCallback or enumOptions.
- */
- var $enumFields = array();
-
- /**
- * A valid callback which will return the options in a simple array of strings
- * for an enum field given the table and field names.
- */
- var $enumOptionsCallback = array();
-
- /**
- * An array which holds enum options for specific fields. Each key should be a
- * field in the current table and each value holds a an array of strings which
- * are the possible values for the enum. This will only be used if the field is
- * listed in enumFields.
- */
- var $enumOptions = array();
-
- /**
- * An array which holds the field names of those fields which are booleans.
- * They will be displayed as checkboxes.
- */
- var $booleanFields = array();
-
- /**
- * The text to put between crosslink elements.
- */
- var $crossLinkSeparator = '<br/>';
-
- /**
- * If this is set to 1 or above, links will be followed in the display fields
- * and the display fields of the record linked to will be used for display.
- * If this is set to 2, links will be followed in the linked record as well.
- * This can be set to any number of links you wish but could easily slow down
- * your application if set to more than 1 or 2 (but only if you have links in
- * your display fields that go that far ;-)). For a more in-depth example, see
- * the docs for linkDisplayFields.
- */
- var $linkDisplayLevel = 0;
-
- /**
- * The crossLinks array holds data pertaining to many-many links. If you
- * have a table which links two tables together, you can use this to
- * automatically create a set of checkboxes or a multi-select on your form.
- * The simplest way of using this is:
- * <code>
- * <?php
- * class DataObject_SomeTable extends DB_DataObject {
- * //...
- * var $fb_crossLinks = array(array('table' => 'crossLinkTable'));
- * }
- * ?>
- * </code>
- * Where crossLinkTable is the name of the linking table. You can have as
- * many cross-link entries as you want. Try it with just the table ewntry
- * first. If it doesn't work, you can specify the fields to use as well.
- * <code>
- * 'fromField' => 'linkFieldToCurrentTable' //This is the field which links to the current (from) table
- * 'toField' => 'linkFieldToLinkedTable' //This is the field which links to the "other" (to) table
- * </code>
- * To get a multi-select add a 'type' key which it set to 'select'.
- * <code>
- * <?php
- * class DataObject_SomeTable extends DB_DataObject {
- * //...
- * var $fb_crossLinks = array(array('table' => 'crossLinkTable', 'type' => 'select'));
- * }
- * ?>
- * </code>
- * An example: I have a user table and a group table, each with a primary
- * key called id. There is a table called user_group which has fields user_id
- * and group_id which are set up as links to user and group. Here's the
- * configuration array that could go in both the user DO and the group DO:
- * <code>
- * <?php
- * $fb_crossLinks = array(array('table' => 'user_group'));
- * ?>
- * </code>
- * Here is the full configuration for the user DO:
- * <code>
- * <?php
- * $fb_crossLinks = array(array('table' => 'user_group',
- * 'fromField' => 'user_id',
- * 'toField' => 'group_id'));
- * ?>
- * </code>
- * And the full configuration for the group DO:
- * <code>
- * <?php
- * $fb_crossLinks = array(array('table' => 'user_group',
- * 'fromField' => 'group_id',
- * 'toField' => 'user_id'));
- * ?>
- * </code>
- *
- * You can also specify the seperator between the elements with crossLinkSeperator.
- */
- var $crossLinks = array();
-
- /**
- * You can also specify extra fields to edit in the a crossLink table with
- * this option. For example, if the user_group table mentioned above had
- * another field called 'role' which was a text field, you could specify it
- * like this in the user_group DataObject class:
- * <code>
- * <?php
- * class DataObject_User_group extends DB_DataObject {
- * //normal stuff here
- *
- * var $fb_crossLinkExtraFields = array('role');
- * }
- * ?>
- * </code>
- *
- * This would cause a text box to show up next to each checkbox in the
- * user_group section of the form for the field 'role'.
- *
- * You can specify as many fields as you want in the 'extraFields' array.
- *
- * Note: If you specify a linked field in 'extraFields' you'll get a select
- * box just like when you do a normal link field in a FormBuilder form. :-)
- */
- var $crossLinkExtraFields = array();
-
- /**
- * Holds triple link data.
- * The tripleLinks array can be used to display checkboxes for "triple-links". A triple link is set
- * up with a table which links to three different tables. These will show up as a table of checkboxes
- * The initial setting (table) is the same as for crossLinks. The field configuration keys (if you
- * need them) are:
- * <code>
- * 'fromField'
- * 'toField1'
- * 'toField2'
- * </code>
- */
- var $tripleLinks = array();
-
- /**
- * Holds reverseLink configuration.
- * A reverseLink is a table which links back to the current table. For
- * example, let say we have a "gender" table which has Male and Female in it
- * and a "person" table which has the fields "name", which holds the person's
- * name and "genre_id" which links to the genre. If you set up a form for the
- * gender table, the person table can be a reverseLink. The setup in the
- * gender table would look like this:
- * <code>
- * <?php
- * class DataObject_Gender extends DB_DataObject {
- * //normal stuff here
- *
- * var $fb_reverseLinks = array(array('table' => 'person'));
- * }
- * ?>
- * </code>
- * Now a list of people will be shown in the gender form with a checkbox next
- * to it which is checked if the record currently links to the one you're
- * editing. In addition, some special text will be added to the end of the
- * label for the person record if it's linked to another gender.
- *
- * Say we have a person record with the name "Justin Patrin" which is linked
- * to the gender "Male". If you view the form for the gender "Male", the
- * checkbox next to "Justin Patrin" will be checked. If you choose the
- * "Female" gender the checkbox will be unchecked and it will say:
- * Justin Patrin - currently linked to - Male
- *
- * If the link field is set as NOT NULL then FormBuilder will not process
- * and unchecked checkbox unless you specify a default value to set the link
- * to. If null is allowed, the link will be set to NULL. To specify a default
- * value:
- * <code>
- * <?php
- * class DataObject_Gender extends DB_DataObject {
- * //normal stuff here
- *
- * var $fb_reverseLinks = array(array('table' => 'person',
- * 'defaultLinkValue' => 5));
- * }
- * ?>
- * </code>
- * Now if a checkbox is unchecked the link field will be set to 5...whatever
- * that means. Be careful here as you need to make sure you enter the correct
- * value here (probably the value of the primary key of the record you want
- * to link to by default).
- *
- * You may also set the text which is displayed between the record and the
- * currently linked to record.
- * <code>
- * <?php
- * class DataObject_Gender extends DB_DataObject {
- * //normal stuff here
- *
- * var $fb_reverseLinks = array(array('table' => 'person',
- * 'linkText' => ' is currently listed as a '));
- * }
- * ?>
- * </code>
- * If you select "Female" the Justin Patrin entry would now say:
- * Justin Patrin__ is currently listed as a Male__
- */
- var $reverseLinks = array();
-
- /**
- * If set to true, validation rules will also be client side.
- */
- var $clientRules = false;
-
- /**
- * A string to prepend to element names. Together with elementNamePostfix, this option allows you to
- * alter the form element names that FormBuilder uses to create and process elements. The main use for
- * this is to combine multiple forms into one. For example, if you wanted to use multiple FB forms for
- * the same table within one actual HTML form you could do something like this:
- * <?php
- * $do = DB_DataObject::factory('table');
- * $fb = DB_DataObject_FormBuilder::create($do);
- * $fb->elementNamePrefix = 'formOne';
- * $form = $fb->getForm();
- *
- * $do2 = DB_DataObject::factory('table');
- * $fb2 = DB_DataObject_FormBuilder::create($do2);
- * $fb->elementNamePrefix = 'formTwo';
- * $fb->useForm($form);
- * $form = $fb->getForm();
- *
- * //normal processing here
- * ?>
- *
- * If you assume that "table: has one field, "name", then the resultant form will have two elements:
- * "formOnename" and "formTwoname".
- *
- * Please note: You *cannot* use '[' or ']' anywhere in the prefix or postfix. Doing so
- * will cause FormBuilder to not be able to process the form.
- */
- var $elementNamePrefix = '';
-
- /**
- * A postfix to put after element names in the form
- * @see DB_DataObject_FormBuilder::elementNamePrefix
- */
- var $elementNamePostfix = '';
-
- /**
- * Whether or not to use call-time-pass-by-reference when calling DataObject callbacks
- */
- var $useCallTimePassByReference = false;
-
- /**
- * DB_DataObject_FormBuilder::create()
- *
- * Factory method. As this is meant as an abstract class, it is the only supported
- * method to make a new object instance. Pass the DataObject-derived class you want to
- * build a form from as the first parameter. Use the second to pass additional options.
- *
- * Options can be:
- * - 'ruleViolationMessage' : See description of similarly-named class property
- * - 'requiredRuleMessage' : See description of similarly-named class property
- * - 'addFormHeader' : See description of similarly-named class property
- * - 'formHeaderText' : See description of similarly-named class property
- *
- * The third parameter is the name of a driver class. A driver class will take care of
- * the actual form generation. This way it's possible to have FormBuilder build different
- * forms for different types of output media from the same set of DataObjects.
- *
- * Currently available driver classes:
- * - QuickForm (stable)
- * - XUL (experimental!)
- *
- * @param object $do The DB_DataObject-derived object for which a form shall be built
- * @param array $options An optional associative array of options.
- * @param string $driver Optional: Name of the driver class for constructing the form object. Default: QuickForm.
- * @access public
- * @returns object DB_DataObject_FormBuilder or PEAR_Error object
- */
- function &create(&$do, $options = false, $driver = 'QuickForm')
- {
- if (!is_a($do, 'db_dataobject')) {
- $err =& PEAR::raiseError('DB_DataObject_FormBuilder::create(): Object does not extend DB_DataObject.',
- DB_DATAOBJECT_FORMBUILDER_ERROR_NODATAOBJECT);
- return $err;
- }
-
- @include_once('DB/DataObject/FormBuilder/'.$driver.'.php');
- $className = 'db_dataobject_formbuilder_'.strtolower($driver);
- if (class_exists($className)) {
- $obj = &new $className($do, $options);
- return $obj;
- }
- $err =& PEAR::raiseError('DB_DataObject_FormBuilder::create(): Driver class "'.$className.'" not found.',
- DB_DATAOBJECT_FORMBUILDER_ERROR_UNKNOWNDRIVER);
- return $err;
- }
-
-
- /**
- * DB_DataObject_FormBuilder::DB_DataObject_FormBuilder()
- *
- * The class constructor.
- *
- * @param object $do The DB_DataObject-derived object for which a form shall be built
- * @param array $options An optional associative array of options.
- * @access public
- */
- function DB_DataObject_FormBuilder(&$do, $options = false)
- {
- // Set default callbacks first!
- $this->dateToDatabaseCallback = array(&$this, '_array2date');
- $this->dateFromDatabaseCallback = array(&$this, '_date2array');
- $this->enumOptionsCallback = array(&$this, '_getEnumOptions');
-
- // Read in config
- $vars = get_object_vars($this);
- if (isset($GLOBALS['_DB_DATAOBJECT_FORMBUILDER']['CONFIG'])) {
- //read all config options into member vars
- foreach ($GLOBALS['_DB_DATAOBJECT_FORMBUILDER']['CONFIG'] as $key => $value) {
- if (in_array($key, $vars) && $key[0] != '_') {
- $this->$key = $value;
- }
- }
- }
- if (is_array($options)) {
- reset($options);
- while (list($key, $value) = each($options)) {
- if (in_array($key, $vars) && $key[0] != '_') {
- $this->$key = $value;
- }
- }
- }
-
- $defVars = get_class_vars(get_class($this));
- foreach ($defVars as $member => $value) {
- if (is_array($value) && isset($this->$member) && is_string($this->$member)) {
- $this->$member = $this->_explodeArrString($this->$member);
- }
- }
- $this->_do = &$do;
- }
-
- /**
- * Gets the primary key field name for a DataObject
- * Looks for $do->_primary_key, $do->sequenceKey(), then $do->keys()
- *
- * @param DB_DataObject the DataObject to get the primary key of
- * @return string the name of the primary key or false if none is found
- */
- function _getPrimaryKey(&$do) {
- if (isset($do->_primary_key)) {
- return $do->_primary_key;
- } elseif (($seq = $do->sequenceKey()) && isset($seq[0])) {
- return $seq[0];
- } else {
- if (($keys = $do->keys()) && isset($keys[0])) {
- return $keys[0];
- }
- }
- return false;
- }
-
- /**
- * DB_DataObject_FormBuilder::_getEnumOptions()
- * Gets the possible values for an enum field from the DB. This is only tested in
- * mysql and will likely break on all other DB backends.
- *
- * @param string Table to query on
- * @param string Field to get enum options for
- * @return array array of strings, each being a possible value for th eenum field
- */
- function _getEnumOptions($table, $field) {
- $db = $this->_do->getDatabaseConnection();
- if (isset($GLOBALS['_DB_DATAOBJECT']['CONFIG']['quote_identifiers']) && $GLOBALS['_DB_DATAOBJECT']['CONFIG']['quote_identifiers']) {
- $table = $db->quoteIdentifier($table);
- }
- $option = $db->getRow('SHOW COLUMNS FROM '.$table.' LIKE '.$db->quoteSmart($field), DB_FETCHMODE_ASSOC);
- if (PEAR::isError($option)) {
- return PEAR::raiseError('There was an error querying for the enum options for field "'.$field.'". You likely need to use enumOptionsCallback.');
- }
- $option = substr($option['Type'], strpos($option['Type'], '(') + 1);
- $option = substr($option, 0, strrpos($option, ')') - strlen($option));
- $split = explode(',', $option);
- $options = array();
- $option = '';
- for ($i = 0; $i < sizeof($split); ++$i) {
- $option .= $split[$i];
- if (substr_count($option, "'") % 2 == 0) {
- $option = trim(trim($option), "'");
- $options[$option] = $option;
- $option = '';
- }
- }
- return $options;
- }
-
- /**
- * DB_DataObject_FormBuilder::_generateForm()
- *
- * Builds a simple HTML form for the current DataObject. Internal function, called by
- * the public getForm() method. You can override this in child classes if needed, but
- * it's also possible to leave this as it is and just override the getForm() method
- * to simply fine-tune the auto-generated form object (i.e. add/remove elements, alter
- * options, add/remove rules etc.).
- * If a key with the same name as the current field is found in the fb_preDefElements
- * property, the QuickForm element object contained in that array will be used instead
- * of auto-generating a new one. This allows for complete step-by-step customizing of
- * your forms.
- *
- * Note for date fields: HTML_QuickForm allows passing of an options array to the
- * HTML_QuickForm_date element. You can define your own options array for date elements
- * in your DataObject-derived classes by defining a method "dateOptions($fieldName)".
- * FormBuilder will call that method whenever it encounters a date field and expects to
- * get back a valid options array.
- *
- * @param string $action The form action. Optional. If set to false (default), PHP_SELF is used.
- * @param string $target The window target of the form. Optional. Defaults to '_self'.
- * @param string $formName The name of the form, will be used in "id" and "name" attributes. If set to false (default), the class name is used
- * @param string $method The submit method. Defaults to 'post'.
- * @return object
- * @access protected
- * @author Markus Wolff <mw21st@php.net>
- * @author Fabien Franzen <atelierfabien@home.nl>
- */
- function &_generateForm($action = false, $target = '_self', $formName = false, $method = 'post')
- {
- if ($formName === false) {
- $formName = strtolower(get_class($this->_do));
- }
- if ($action === false) {
- $action = $_SERVER['PHP_SELF'];
- }
-
- // Retrieve the form object to use (may depend on the current renderer)
- $form =& $this->_createFormObject($formName, $method, $action, $target);
-
- // Initialize array with default values
- //$formValues = $this->_do->toArray();
-
- // Add a header to the form - set addFormHeader property to false to prevent this
- $this->_addFormHeader($form);
-
- // Go through all table fields and create appropriate form elements
- $keys = $this->_do->keys();
-
- // Reorder elements if requested
- $elements = $this->_reorderElements();
- if ($elements == false) { //no sorting necessary
- $elements = $this->_getFieldsToRender();
- }
- //get elements to freeze
- $user_editable_fields = $this->_getUserEditableFields();
- if (is_array($user_editable_fields)) {
- $elements_to_freeze = array_diff(array_keys($elements), $user_editable_fields);
- } else {
- $elements_to_freeze = array();
- }
-
- $links = $this->_do->links();
- $pk = $this->_getPrimaryKey($this->_do);
- $rules = array();
- foreach ($elements as $key => $type) {
- // Check if current field is primary key. And primary key hiding is on. If so, make hidden field
- if (in_array($key, $keys) && $this->hidePrimaryKey == true) {
- $formValues[$key] = $this->_do->$key;
- $element =& $this->_createHiddenField($key);
- } else {
- unset($element);
- // Try to determine field types depending on object properties
- $notNull = $type & DB_DATAOBJECT_NOTNULL;
- if (in_array($key, $this->dateFields)) {
- $type = DB_DATAOBJECT_DATE;
- } elseif (in_array($key, $this->timeFields)) {
- $type = DB_DATAOBJECT_TIME;
- } elseif (in_array($key, $this->textFields)) {
- $type = DB_DATAOBJECT_TXT;
- } elseif (in_array($key, $this->enumFields)) {
- $type = DB_DATAOBJECT_FORMBUILDER_ENUM;
- } elseif (in_array($key, $this->booleanFields)) {
- $type = DB_DATAOBJECT_BOOL;
- }
- if (isset($this->preDefElements[$key])
- && (is_object($this->preDefElements[$key]) || is_array($this->preDefElements[$key]))) {
- // Use predefined form field, IMPORTANT: This may depend on the used renderer!!
- $element =& $this->preDefElements[$key];
- } elseif (is_array($links) && isset($links[$key])) {
- // If this field links to another table, display selectbox or radiobuttons
- $opt = $this->getSelectOptions($key, false, !$notNull);
- if (isset($this->linkElementTypes[$key]) && $this->linkElementTypes[$key] == 'radio') {
- $element =& $this->_createRadioButtons($key, $opt);
- } else {
- $element =& $this->_createSelectBox($key, $opt);
- }
- unset($opt);
- }
-
- // No predefined object available, auto-generate new one
- $elValidator = false;
- $elValidRule = false;
-
- // Auto-detect field types depending on field's database type
- switch (true) {
- case ($type & DB_DATAOBJECT_BOOL):
- $formValues[$key] = $this->_do->$key;
- if (!isset($element)) {
- $element =& $this->_createCheckbox($key, null, null, $this->getFieldLabel($key));
- }
- break;
- case ($type & DB_DATAOBJECT_INT):
- $formValues[$key] = $this->_do->$key;
- if (!isset($element)) {
- $element =& $this->_createIntegerField($key);
- $elValidator = 'numeric';
- }
- break;
- case (($type & DB_DATAOBJECT_DATE) && ($type & DB_DATAOBJECT_TIME)):
- $this->debug('DATE & TIME CONVERSION using callback for element '.$key.' ('.$this->_do->$key.')!', 'FormBuilder');
- $formValues[$key] = call_user_func($this->dateFromDatabaseCallback, $this->_do->$key);
- if (!isset($element)) {
- $element =& $this->_createDateTimeElement($key);
- }
- break;
- case ($type & DB_DATAOBJECT_DATE):
- $this->debug('DATE CONVERSION using callback for element '.$key.' ('.$this->_do->$key.')!', 'FormBuilder');
- $formValues[$key] = call_user_func($this->dateFromDatabaseCallback, $this->_do->$key);
- if (!isset($element)) {
- $element =& $this->_createDateElement($key);
- }
- break;
- case ($type & DB_DATAOBJECT_TIME):
- $this->debug('TIME CONVERSION using callback for element '.$key.' ('.$this->_do->$key.')!', 'FormBuilder');
- $formValues[$key] = call_user_func($this->dateFromDatabaseCallback, $this->_do->$key);
- if (!isset($element)) {
- $element =& $this->_createTimeElement($key);
- }
- break;
- case ($type & DB_DATAOBJECT_TXT):
- $formValues[$key] = $this->_do->$key;
- if (!isset($element)) {
- $element =& $this->_createTextArea($key);
- }
- break;
- case ($type & DB_DATAOBJECT_STR):
- $formValues[$key] = $this->_do->$key;
- if (!isset($element)) {
- // If field content contains linebreaks, make textarea - otherwise, standard textbox
- if (isset($this->_do->$key) && strlen($this->_do->$key) && strstr($this->_do->$key, "\n")) {
- $element =& $this->_createTextArea($key);
- } else {
- $element =& $this->_createTextField($key);
- }
- }
- break;
- case ($type & DB_DATAOBJECT_FORMBUILDER_CROSSLINK):
- unset($element);
- // generate crossLink stuff
- if ($pk === false) {
- return PEAR::raiseError('A primary key must exist in the base table when using crossLinks.');
- }
- $crossLink = $this->crossLinks[$key];
- $groupName = '__crossLink_' . $crossLink['table'];
- $crossLinksDo = DB_DataObject::factory($crossLink['table']);
- if (PEAR::isError($crossLinksDo)) {
- die($crossLinksDo->getMessage());
- }
-
- $crossLinksLinks = $crossLinksDo->links();
-
- list($linkedtable, $linkedfield) = explode(':', $crossLinksLinks[$crossLink['toField']]);
- $all_options = $this->_getSelectOptions($linkedtable);
- $selected_options = array();
- if (isset($this->_do->$pk) && strlen($this->_do->$pk)) {
- $crossLinksDo->{$crossLink['fromField']} = $this->_do->$pk;
- if (method_exists($this->_do, 'preparelinkeddataobject')) {
- if ($this->useCallTimePassByReference) {
- eval('$this->_do->prepareLinkedDataObject(&$crossLinksDo, $key);');
- } else {
- $this->_do->prepareLinkedDataObject($crossLinksDo, $key);
- }
- }
- if ($crossLinksDo->find() > 0) {
- while ($crossLinksDo->fetch()) {
- $selected_options[$crossLinksDo->{$crossLink['toField']}] = clone($crossLinksDo);
- }
- }
- }
-
- if (isset($crossLink['type']) && $crossLink['type'] == 'select') {
- unset($element);
- $element =& $this->_createSelectBox($groupName, $all_options, true);
- $formValues[$groupName] = array_keys($selected_options); // set defaults later
-
- // ***X*** generate checkboxes
- } else {
- $element = array();
- $rowNames = array();
- $colNames = array('');
- foreach ($all_options as $optionKey => $value) {
- $crossLinksElement = $this->_createCheckbox($groupName.'['.$optionKey.']', $value, $optionKey);
- $elementNamePrefix = $this->elementNamePrefix.$groupName.'__'.$optionKey.'_';
- $elementNamePostfix = '_'.$this->elementNamePostfix;//']';
- if (isset($selected_options[$optionKey])) {
- if (!isset($formValues[$groupName])) {
- $formValues[$groupName] = array();
- }
- $formValues[$groupName][$optionKey] = $optionKey;
- }
- if (isset($crossLinksDo->fb_crossLinkExtraFields)) {
- $row = array(&$crossLinksElement);
- if (isset($selected_options[$optionKey])) {
- $extraFieldDo = $selected_options[$optionKey];
- } else {
- $extraFieldDo = DB_DataObject::factory($crossLink['table']);
- }
- unset($tempFb);
- $tempFb =& DB_DataObject_FormBuilder::create($extraFieldDo);
- $extraFieldDo->fb_fieldsToRender = $crossLinksDo->fb_crossLinkExtraFields;
- $extraFieldDo->fb_elementNamePrefix = $elementNamePrefix;
- $extraFieldDo->fb_elementNamePostfix = $elementNamePostfix;
- $this->_extraFieldsFb[$elementNamePrefix.$elementNamePostfix] =& $tempFb;
- $tempForm = $tempFb->getForm();
- foreach ($crossLinksDo->fb_crossLinkExtraFields as $extraField) {
- if ($tempForm->elementExists($elementNamePrefix.$extraField.$elementNamePostfix)) {
- $tempEl =& $tempForm->getElement($elementNamePrefix.$extraField.$elementNamePostfix);
- $colNames[$extraField] = $tempEl->getLabel();
- } else {
- $tempEl =& $this->_createStaticField($elementNamePrefix.$extraField.$elementNamePostfix,
- 'Error - element not found for extra field '.$extraField);
- }
- $row[] =& $tempEl;
- if (!isset($formValues[$groupName.'__extraFields'])) {
- $formValues[$groupName.'__extraFields'] = array();
- }
- if (!isset($formValues[$groupName.'__extraFields'][$optionKey])) {
- $formValues[$groupName.'__extraFields'][$optionKey] = array();
- }
- $formValues[$groupName.'__extraFields'][$optionKey][$extraField] = $tempEl->getValue();
- unset($tempEl);
- }
- $element[] = $row;
- unset($tempFb, $tempForm, $extraFieldDo, $row);
- $rowNames[] = '<label for="'.$crossLinksElement->getAttribute('id').'">'.$value.'</label>';
- $crossLinksElement->setText('');
- } else {
- $element[] = $crossLinksElement;
- }
- unset($crossLinksElement);
- }
- if (isset($crossLinksDo->fb_crossLinkExtraFields)) {
- $this->_addElementTableToForm($form, $groupName, array_values($colNames), $rowNames, $element);
- } else {
- $this->_addElementGroupToForm($form, $element, $groupName, $this->crossLinkSeparator);
- }
- unset($element);
- unset($rowNames);
- unset($colNames);
- }
- break;
- case ($type & DB_DATAOBJECT_FORMBUILDER_TRIPLELINK):
- unset($element);
- if ($pk === false) {
- return PEAR::raiseError('A primary key must exist in the base table when using tripleLinks.');
- }
- $tripleLink = $this->tripleLinks[$key];
- $elName = '__tripleLink_' . $tripleLink['table'];
- $freeze = array_search($elName, $elements_to_freeze);
- $tripleLinkDo = DB_DataObject::factory($tripleLink['table']);
- if (PEAR::isError($tripleLinkDo)) {
- die($tripleLinkDo->getMessage());
- }
-
- $tripleLinksLinks = $tripleLinkDo->links();
-
- $fromField = $tripleLink['fromField'];
- $toField1 = $tripleLink['toField1'];
- $toField2 = $tripleLink['toField2'];
-
- list($linkedtable1, $linkedfield1) = explode(':', $tripleLinksLinks[$toField1]);
- list($linkedtable2, $linkedfield2) = explode(':', $tripleLinksLinks[$toField2]);
-
- $all_options1 = $this->_getSelectOptions($linkedtable1);
- $all_options2 = $this->_getSelectOptions($linkedtable2);
- $selected_options = array();
- if (isset($this->_do->$pk) && strlen($this->_do->$pk)) {
- $tripleLinkDo->$fromField = $this->_do->$pk;
- if (method_exists($this->_do, 'preparelinkeddataobject')) {
- if ($this->useCallTimePassByReference) {
- eval('$this->_do->prepareLinkedDataObject(&$tripleLinkDo, $key);');
- } else {
- $this->_do->prepareLinkedDataObject($tripleLinkDo, $key);
- }
- }
- if ($tripleLinkDo->find() > 0) {
- while ($tripleLinkDo->fetch()) {
- $selected_options[$tripleLinkDo->$toField1][] = $tripleLinkDo->$toField2;
- }
- }
- }
-
- $columnNames = array();
- foreach ($all_options2 as $key2 => $value2) {
- $columnNames[] = $value2;
- }
- $rows = array();
- $rowNames = array();
- $formValues[$key] = array();
- foreach ($all_options1 as $key1 => $value1) {
- $rowNames[] = $value1;
- $row = array();
- foreach ($all_options2 as $key2 => $value2) {
- unset($tripleLinksElement);
- $tripleLinksElement = $this->_createCheckbox($elName.'['.$key1.']['.$key2.']',
- '',
- $key2
- //false,
- //$freeze
- );
- if (isset($selected_options[$key1])) {
- if (in_array($key2, $selected_options[$key1])) {
- if (!isset($formValues['__tripleLink_'.$tripleLink['table']][$key1])) {
- $formValues['__tripleLink_'.$tripleLink['table']][$key1] = array();
- }
- $formValues['__tripleLink_'.$tripleLink['table']][$key1][$key2] = $key2;
- }
- }
- $row[] =& $tripleLinksElement;
- }
- $rows[] =& $row;
- unset($row);
- }
- $this->_addElementTableToForm($form, $elName, $columnNames, $rowNames, $rows);
- unset($columnNames, $rowNames, $rows);
- break;
- case ($type & DB_DATAOBJECT_FORMBUILDER_ENUM):
- $formValues[$key] = $this->_do->$key;
- if (!isset($element)) {
- if (isset($this->enumOptions[$key])) {
- $options = $this->enumOptions[$key];
- } else {
- $options = call_user_func($this->enumOptionsCallback, $this->_do->__table, $key);
- }
- if (in_array($key, $this->selectAddEmpty) || !$notNull) {
- $options = array_merge(array('' => $this->selectAddEmptyLabel), $options);
- }
- if (!$options) {
- return PEAR::raiseError('There are no options defined for the enum field "'.$key.'". You may need to set the options in the enumOptions option or use your own enumOptionsCallback.');
- }
- $element = array();
- if (isset($this->linkElementTypes[$key]) && $this->linkElementTypes[$key] == 'radio') {
- foreach ($options as $option) {
- $element =& $this->_createRadioButtons($key, $options);
- }
- } else {
- $element =& $this->_createSelectBox($key, $options);
- }
- unset($options);
- }
- break;
- case ($type & DB_DATAOBJECT_FORMBUILDER_REVERSELINK):
- unset($element);
- $element = array();
- $elName = '__reverseLink_'.$this->reverseLinks[$key]['table'].'_'.$this->reverseLinks[$key]['field'];
- $do = DB_DataObject::factory($this->reverseLinks[$key]['table']);
- if (method_exists($this->_do, 'preparelinkeddataobject')) {
- if ($this->useCallTimePassByReference) {
- eval('$this->_do->prepareLinkedDataObject(&$do, $key);');
- } else {
- $this->_do->prepareLinkedDataObject($do, $key);
- }
- }
- $rLinks = $do->links();
- $rPk = $this->_getPrimaryKey($do);
- //$rFields = $do->table();
- list($lTable, $lField) = explode(':', $rLinks[$this->reverseLinks[$key]['field']]);
- $formValues[$elName] = array();
- if ($do->find()) {
- while ($do->fetch()) {
- $label = $this->getDataObjectString($do);
- if ($do->{$this->reverseLinks[$key]['field']} == $this->_do->$lField) {
- $formValues[$elName][$do->$rPk] = $do->$rPk;
- } elseif ($rLinked =& $do->getLink($this->reverseLinks[$key]['field'])) {
- $label .= '<b>'.$this->reverseLinks[$key]['linkText'].$this->getDataObjectString($rLinked).'</b>';
- }
- $element[] =& $this->_createCheckbox($elName.'['.$do->$rPk.']', $label, $do->$rPk);
- }
- }
- $this->_addElementGroupToForm($form, $element, $elName, $this->crossLinkSeparator);
- unset($element);
- break;
- default:
- $formValues[$key] = $this->_do->$key;
- if (!isset($element)) {
- $element =& $this->_createTextField($key);
- }
- } // End switch
- //} // End else
- if ($elValidator !== false) {
- if (!isset($rules[$key])) {
- $rules[$key] = array();
- }
- $rules[$key][] = array('validator' => $elValidator,
- 'rule' => $elValidRule,
- 'message' => $this->ruleViolationMessage);
- } // End if
-
- } // End else
-
- //GROUP OR ELEMENT ADDITION
- if (isset($this->preDefGroups[$key])) {
- $group = $this->preDefGroups[$key];
- $groups[$group][] = $element;
- } elseif (isset($element)) {
- if (is_array($element)) {
- $this->_addElementGroupToForm($form, $element, $key);
- } else {
- $this->_addElementToForm($form, $element);
- }
- } // End if
-
-
- //ADD REQURED RULE FOR NOT_NULL FIELDS
- if ((!in_array($key, $keys) || $this->hidePrimaryKey == false)
- && ($notNull)
- && !in_array($key, $elements_to_freeze)
- && !($type & DB_DATAOBJECT_BOOL)) {
- $this->_setFormElementRequired($form, $key);
- }
-
- // VALIDATION RULES
- if (isset($rules[$key])) {
- $this->_addFieldRulesToForm($form, $rules[$key], $key);
- }
- } // End foreach
-
- // Freeze fields that are not to be edited by the user
- $this->_freezeFormElements($form, $elements_to_freeze);
-
- //GROUP SUBMIT
- $flag = true;
- if (isset($this->preDefGroups['__submit__'])) {
- $group = $this->preDefGroups['__submit__'];
- if (count($groups[$group]) > 1) {
- $groups[$group][] =& $this->_createSubmitButton('__submit__', $this->submitText);
- $flag = false;
- } else {
- $flag = true;
- }
- }
-
- //GROUPING
- if (isset($groups) && is_array($groups)) { //apply grouping
- reset($groups);
- while (list($grp, $elements) = each($groups)) {
- if (count($elements) == 1) {
- $this->_addElementToForm($form, $elements[0]);
- } elseif (count($elements) > 1) {
- $this->_addElementGroupToForm($form, $elements, $grp, ' ');
- }
- }
- }
-
- //ELEMENT SUBMIT
- if ($flag == true && $this->createSubmit == true) {
- $this->_addSubmitButtonToForm($form, '__submit__', $this->submitText);
- }
-
- //APPEND EXISTING FORM ELEMENTS
- if (is_a($this->_form, 'html_quickform') && $this->_appendForm == true) {
- // There somehow needs to be a new method in QuickForm that allows to fetch
- // a list of all element names currently registered in a form. Otherwise, there
- // will be need for some really nasty workarounds once QuickForm adopts PHP5's
- // new encapsulation features.
- reset($this->_form->_elements);
- while (list($elNum, $element) = each($this->_form->_elements)) {
- $this->_addElementToForm($form, $element);
- }
- }
-
- // Assign default values to the form
- $fixedFormValues = array();
- foreach ($formValues as $key => $value) {
- $fixedFormValues[$this->getFieldName($key)] = $value;
- }
- $this->_setFormDefaults($form, $fixedFormValues);
- return $form;
- }
-
-
- /**
- * Gets the name of the field to use in the form.
- *
- * @param string field's name
- * @return string field name to use with form
- */
- function getFieldName($fieldName) {
- if (($pos = strpos($fieldName, '[')) !== false) {
- $fieldName = substr($fieldName, 0, $pos).$this->elementNamePostfix.substr($fieldName, $pos);
- } else {
- $fieldName .= $this->elementNamePostfix;
- }
- return $this->elementNamePrefix.$fieldName;
- }
-
-
- /**
- * DB_DataObject_FormBuilder::_explodeArrString()
- *
- * Internal method, will convert string representations of arrays as used in .ini files
- * to real arrays. String format example:
- * key1:value1,key2:value2,key3:value3,...
- *
- * @param string $str The string to convert to an array
- * @access protected
- * @return array
- */
- function _explodeArrString($str) {
- $ret = array();
- $arr = explode(',', $str);
- foreach ($arr as $mapping) {
- if (strstr($mapping, ':')) {
- $map = explode(':', $mapping);
- $ret[$map[0]] = $map[1];
- } else {
- $ret[] = $mapping;
- }
- }
- return $ret;
- }
-
-
- /**
- * DB_DataObject_FormBuilder::_reorderElements()
- *
- * Changes the order in which elements are being processed, so that
- * you can use QuickForm's default renderer or dynamic templates without
- * being dependent on the field order in the database.
- *
- * Make a class property named "fb_preDefOrder" in your DataObject-derived classes
- * which contains an array with the correct element order to use this feature.
- *
- * @return mixed Array in correct order or FALSE if reordering was not possible
- * @access protected
- * @author Fabien Franzen <atelierfabien@home.nl>
- */
- function _reorderElements() {
- if ($this->preDefOrder) {
- $this->debug('<br/>...reordering elements...<br/>');
- $elements = $this->_getFieldsToRender();
- $table = $this->_do->table();
- $crossLinks = $this->_getSpecialElementNames();
-
- foreach ($this->preDefOrder as $elem) {
- if (isset($elements[$elem])) {
- $ordered[$elem] = $elements[$elem]; //key=>type
- } elseif (!isset($table[$elem]) && !isset($crossLinks[$elem])) {
- $this->debug('<br/>...reorder not supported: invalid element(key) found "'.$elem.'"...<br/>');
- return false;
- }
- }
-
- $ordered = array_merge($ordered, array_diff_assoc($elements, $ordered));
-
- return $ordered;
- } else {
- $this->debug('<br/>...reorder not supported, fb_preDefOrder is not set or is not an array...<br/>');
- return false;
- }
- }
-
- /**
- * Returns an array of crosslink and triplelink elements for use the same as
- * DB_DataObject::table().
- *
- * @return array the key is the name of the cross/triplelink element, the value
- * is the type
- */
- function _getSpecialElementNames() {
- $ret = array();
- foreach ($this->tripleLinks as $tripleLink) {
- $ret['__tripleLink_'.$tripleLink['table']] = DB_DATAOBJECT_FORMBUILDER_TRIPLELINK;
- }
- foreach ($this->crossLinks as $crossLink) {
- $ret['__crossLink_'.$crossLink['table']] = DB_DATAOBJECT_FORMBUILDER_CROSSLINK;
- }
- foreach ($this->reverseLinks as $reverseLink) {
- $ret['__reverseLink_'.$reverseLink['table'].'_'.$reverseLink['field']] = DB_DATAOBJECT_FORMBUILDER_REVERSELINK;
- }
- return $ret;
- }
-
-
- /**
- * DB_DataObject_FormBuilder::useForm()
- *
- * Sometimes, it might come in handy not just to create a new QuickForm object,
- * but to work with an existing one. Using FormBuilder together with
- * HTML_QuickForm_Controller or HTML_QuickForm_Page is such an example ;-)
- * If you do not call this method before the form is generated, a new QuickForm
- * object will be created (default behaviour).
- *
- * @param $form object A HTML_QuickForm object (or extended from that)
- * @param $append boolean If TRUE, the form will be appended to the one generated by FormBuilder. If false, FormBuilder will just add its own elements to this form.
- * @return boolean Returns false if the passed object was not a HTML_QuickForm object or a QuickForm object was already created
- * @access public
- */
- function useForm(&$form, $append = false)
- {
- if (is_a($form, 'html_quickform') && !is_object($this->_form)) {
- $this->_form =& $form;
- $this->_appendForm = $append;
- return true;
- }
- return false;
- }
-
-
-
-
- /**
- * DB_DataObject_FormBuilder::getFieldLabel()
- *
- * Returns the label for the given field name. If no label is specified,
- * the fieldname will be returned with ucfirst() applied.
- *
- * @param $fieldName string The field name
- * @return string
- * @access public
- */
- function getFieldLabel($fieldName)
- {
- if (isset($this->fieldLabels[$fieldName])) {
- return $this->fieldLabels[$fieldName];
- }
- return ucfirst($fieldName);
- }
-
- /**
- * DB_DataObject_FormBuilder::getDataObjectString()
- *
- * Returns a string which identitfies this dataobject.
- * If multiple display fields are given, will display them all seperated by ", ".
- * If a display field is a foreign key (link) the display value for the record it
- * points to will be used as long as the linkDisplayLevel has not been reached.
- * Its display value will be surrounded by parenthesis as it may have multiple
- * display fields of its own.
- *
- * May be called statically.
- *
- * Will use display field configurations from these locations, in this order:
- * 1) $displayFields parameter
- * 2) the fb_linkDisplayFields member variable of the dataobject
- * 3) the linkDisplayFields member variable of this class (if not called statically)
- * 4) all fields returned by the DO's table() function
- *
- * @param DB_DataObject the dataobject to get the display value for, must be populated
- * @param mixed field to use to display, may be an array with field names or a single field.
- * Will only be used for this DO, not linked DOs. If you wish to set the display fields
- * all DOs the same, set the option in the FormBuilder class instance.
- * @param int the maximum link display level. If null, $this->linkDisplayLebel will be used
- * if it exists, otherwise 3 will be used. {@see DB_DataObject_FormBuilder::linkDisplayLevel}
- * @param int the current recursion level. For internal use only.
- * @return string select display value for this field
- * @access public
- */
- function getDataObjectString(&$do, $displayFields = false, $linkDisplayLevel = null, $level = 1) {
- if ($linkDisplayLevel === null) {
- $linkDisplayLevel = (isset($this) && isset($this->linkDisplayLevel)) ? $this->linkDisplayLevel : 3;
- }
- $links = $do->links();
- if ($displayFields === false) {
- if (isset($do->fb_linkDisplayFields)) {
- $displayFields = $do->fb_linkDisplayFields;
- } elseif (isset($this) && isset($this->linkDisplayFields) && $this->linkDisplayFields) {
- $displayFields = $this->linkDisplayFields;
- }
- if (!$displayFields) {
- $displayFields = array_keys($do->table());
- }
- }
- $ret = '';
- $first = true;
- foreach ($displayFields as $field) {
- if ($first) {
- $first = false;
- } else {
- $ret .= ', ';
- }
- if (isset($do->$field)) {
- if ($linkDisplayLevel > $level && isset($links[$field])
- && ($subDo = $do->getLink($field))) {
- if (isset($this) && is_a($this, 'DB_DataObject_FormBuilder')) {
- $ret .= '('.$this->getDataObjectString($subDo, false, $linkDisplayLevel, $level + 1).')';
- } else {
- $ret .= '('.DB_DataObject_FormBuilder::getDataObjectString($subDo, false, $linkDisplayLevel, $level + 1).')';
- }
- } else {
- $ret .= $do->$field;
- }
- }
- }
- return $ret;
- }
-
- /**
- * DB_DataObject_FormBuilder::getSelectOptions()
- *
- * Returns an array of options for use with the HTML_QuickForm "select" element.
- * It will try to fetch all related objects (if any) for the given field name and
- * build the array.
- * For the display name of the option, it will try to use
- * the settings in the database.formBuilder.ini file. If those are not found,
- * the linked object's property "fb_linkDisplayFields". If that one is not present,
- * it will try to use the global configuration setting "linkDisplayFields".
- * Can also be called with a second parameter containing the name of the display
- * field - this will override all other settings.
- * Same goes for "linkOrderFields", which determines the field name used for
- * sorting the option elements. If neither a config setting nor a class property
- * of that name is set, the display field name will be used.
- *
- * @param string $field The field to fetch the links from. You should make sure the field actually *has* links before calling this function (see: DB_DataObject::links())
- * @param string $displayFields (Optional) The name of the field used for the display text of the options
- * @param bool $selectAddEmpty (Optional) If true, an empty option will be added to the list of options
- * If false, the selectAddEmpty member var will be checked
- * @return array strings representing all of the records in the table $field links to.
- * @access public
- */
- function getSelectOptions($field, $displayFields = false, $selectAddEmpty = false)
- {
- if (empty($this->_do->_database)) {
- // TEMPORARY WORKAROUND !!! Guarantees that DataObject config has
- // been loaded and all link information is available.
- $this->_do->keys();
- }
- $links = $this->_do->links();
- $link = explode(':', $links[$field]);
-
- $res = $this->_getSelectOptions($link[0],
- $displayFields,
- $selectAddEmpty || in_array($field, $this->selectAddEmpty),
- $field);
-
- if ($res !== false) {
- return $res;
- }
-
- $this->debug('Error: '.get_class($opts).' does not inherit from DB_DataObject');
- return array();
- }
-
- /**
- * Internal function to get the select potions for a table.
- *
- * @param string $table The table to get the select display strings for.
- * @param array $displayFields array of diaply fields to use. Will default to the FB or DO options.
- * @param bool $selectAddEmpty If set to true, there will be an empty option in the returned array.
- * @param string $field the field in the current table which we're getting options for
- *
- * @return array strings representing all of the records in $table.
- * @access protected
- */
- function _getSelectOptions($table, $displayFields = false, $selectAddEmpty = false, $field = false) {
- $opts = DB_DataObject::factory($table);
- if (is_a($opts, 'db_dataobject')) {
- $pk = $this->_getPrimaryKey($opts);
- if ($displayFields === false) {
- if (isset($opts->fb_linkDisplayFields)) {
- $displayFields = $opts->fb_linkDisplayFields;
- } elseif ($this->linkDisplayFields){
- $displayFields = $this->linkDisplayFields;
- } else {
- $displayFields = array($pk);
- }
- }
-
- if (isset($opts->fb_linkOrderFields)) {
- $orderFields = $opts->fb_linkOrderFields;
- } elseif ($this->linkOrderFields){
- $orderFields = $this->linkOrderFields;
- } else {
- $orderFields = $displayFields;
- }
- $orderStr = '';
- $first = true;
- foreach ($orderFields as $col) {
- if ($first) {
- $first = false;
- } else {
- $orderStr .= ', ';
- }
- $orderStr .= $col;
- }
- if ($orderStr) {
- $opts->orderBy($orderStr);
- }
- $list = array();
-
- // FIXME!
- if ($selectAddEmpty) {
- $list[''] = $this->selectAddEmptyLabel;
- }
- if (method_exists($this->_do, 'preparelinkeddataobject')) {
- if ($this->useCallTimePassByReference) {
- eval('$this->_do->prepareLinkedDataObject(&$opts, $field);');
- } else {
- $this->_do->prepareLinkedDataObject($opts, $field);
- }
- }
- // FINALLY, let's see if there are any results
- if ($opts->find() > 0) {
- while ($opts->fetch()) {
- $list[$opts->$pk] = $this->getDataObjectString($opts, $displayFields);
- }
- }
-
- return $list;
- }
- $this->debug('Error: '.get_class($opts).' does not inherit from DB_DataObject');
- return array();
- }
-
- /**
- * DB_DataObject_FormBuilder::populateOptions()
- *
- * Populates public member vars with fb_ equivalents in the DataObject.
- */
- function populateOptions() {
- $badVars = array('linkDisplayFields', 'linkOrderFields');
- foreach (get_object_vars($this) as $var => $value) {
- if ($var[0] != '_' && !in_array($var, $badVars) && isset($this->_do->{'fb_'.$var})) {
- $this->$var = $this->_do->{'fb_'.$var};
- }
- }
- }
-
- /**
- * DB_DataObject_FormBuilder::getForm()
- *
- * Returns a HTML form that was automagically created by _generateForm().
- * You need to use the get() method before calling this one in order to
- * prefill the form with the retrieved data.
- *
- * If you have a method named "preGenerateForm()" in your DataObject-derived class,
- * it will be called before _generateForm(). This way, you can create your own elements
- * there and add them to the "fb_preDefElements" property, so they will not be auto-generated.
- *
- * If you have your own "getForm()" method in your class, it will be called <b>instead</b> of
- * _generateForm(). This enables you to have some classes that make their own forms completely
- * from scratch, without any auto-generation. Use this for highly complex forms. Your getForm()
- * method needs to return the complete HTML_QuickForm object by reference.
- *
- * If you have a method named "postGenerateForm()" in your DataObject-derived class, it will
- * be called after _generateForm(). This allows you to remove some elements that have been
- * auto-generated from table fields but that you don't want in the form.
- *
- * Many ways lead to rome.
- *
- * @param string $action The form action. Optional. If set to false (default), $_SERVER['PHP_SELF'] is used.
- * @param string $target The window target of the form. Optional. Defaults to '_self'.
- * @param string $formName The name of the form, will be used in "id" and "name" attributes.
- * If set to false (default), the class name is used, prefixed with "frm"
- * @param string $method The submit method. Defaults to 'post'.
- * @return object
- * @access public
- */
- function &getForm($action = false, $target = '_self', $formName = false, $method = 'post')
- {
- if (method_exists($this->_do, 'pregenerateform')) {
- if ($this->useCallTimePassByReference) {
- eval('$this->_do->preGenerateForm(&$this);');
- } else {
- $this->_do->preGenerateForm($this);
- }
- }
- $this->populateOptions();
- foreach ($this->crossLinks as $key => $crossLink) {
- $groupName = '__crossLink_' . $crossLink['table'];
- $do = DB_DataObject::factory($crossLink['table']);
- if (PEAR::isError($do)) {
- return PEAR::raiseError('Cannot load dataobject for table '.$crossLink['table'].' - '.$do->getMessage());
- }
-
- $links = $do->links();
-
- if (isset($crossLink['fromField'])) {
- $fromField = $crossLink['fromField'];
- } else {
- unset($fromField);
- }
- if (isset($crossLink['toField'])) {
- $toField = $crossLink['toField'];
- } else {
- unset($toField);
- }
- if (!isset($toField) || !isset($fromField)) {
- foreach ($links as $field => $link) {
- list($linkTable, $linkField) = explode(':', $link);
- if (!isset($fromField) && $linkTable == $this->_do->__table) {
- $fromField = $field;
- } elseif (!isset($toField) && (!isset($fromField) || $linkField != $fromField)) {
- $toField = $field;
- }
- }
- }
- unset($this->crossLinks[$key]);
- $this->crossLinks[$groupName] = array_merge($crossLink,
- array('fromField' => $fromField,
- 'toField' => $toField));
- }
- foreach ($this->tripleLinks as $key => $tripleLink) {
- $elName = '__tripleLink_' . $tripleLink['table'];
- //$freeze = array_search($elName, $elements_to_freeze);
- $do = DB_DataObject::factory($tripleLink['table']);
- if (PEAR::isError($do)) {
- die($do->getMessage());
- }
-
- $links = $do->links();
-
- if (isset($tripleLink['fromField'])) {
- $fromField = $tripleLink['fromField'];
- } else {
- unset($fromField);
- }
- if (isset($tripleLink['toField1'])) {
- $toField1 = $tripleLink['toField1'];
- } else {
- unset($toField1);
- }
- if (isset($tripleLink['toField2'])) {
- $toField2 = $tripleLink['toField2'];
- } else {
- unset($toField2);
- }
- if (!isset($toField2) || !isset($toField1) || !isset($fromField)) {
- foreach ($links as $field => $link) {
- list($linkTable, $linkField) = explode(':', $link);
- if (!isset($fromField) && $linkTable == $this->_do->__table) {
- $fromField = $field;
- } elseif (!isset($toField1) && (!isset($fromField) || $linkField != $fromField)) {
- $toField1 = $field;
- } elseif (!isset($toField2) && (!isset($fromField) || $linkField != $fromField) && $linkField != $toField1) {
- $toField2 = $field;
- }
- }
- }
- unset($this->tripleLinks[$key]);
- $this->tripleLinks[$elName] = array_merge($tripleLink,
- array('fromField' => $fromField,
- 'toField1' => $toField1,
- 'toField2' => $toField2));
- }
- foreach ($this->reverseLinks as $key => $reverseLink) {
- $elName = '__reverseLink_'.$reverseLink['table'].'_'.$reverseLink['field'];
- if (!isset($reverseLink['field'])) {
- $do = DB_DataObject::factory($reverseLink['table']);
- $links = $do->links();
- foreach ($do->links() as $field => $link) {
- list($linkTable, $linkField) = explode(':', $link);
- if ($linkTable == $this->_do->__table) {
- $reverseLink['field'] = $field;
- break;
- }
- }
- }
- if (!isset($reverseLink['linkText'])) {
- $reverseLink['linkText'] = ' - currently linked to - ';
- }
- unset($this->reverseLinks[$key]);
- $this->reverseLinks[$elName] = $reverseLink;
- }
-
- if (method_exists($this->_do, 'getform')) {
- $obj = $this->_do->getForm($action, $target, $formName, $method);
- } else {
- $obj = &$this->_generateForm($action, $target, $formName, $method);
- }
- if (method_exists($this->_do, 'postgenerateform')) {
- if ($this->useCallTimePassByReference) {
- eval('$this->_do->postGenerateForm(&$obj, &$this);');
- } else {
- $this->_do->postGenerateForm($obj, $this);
- }
- }
- return($obj);
- }
-
-
- /**
- * DB_DataObject_FormBuilder::_date2array()
- *
- * Takes a string representing a date or a unix timestamp and turns it into an
- * array suitable for use with the QuickForm data element.
- * When using a string, make sure the format can be handled by the PEAR::Date constructor!
- *
- * Beware: For the date conversion to work, you must at least use the letters "d", "m" and "Y" in
- * your format string (see "dateElementFormat" option). If you want to enter a time as well,
- * you will have to use "H", "i" and "s" as well. Other letters will not work! Exception: You can
- * also use "M" instead of "m" if you want plain text month names.
- *
- * @param mixed $date A unix timestamp or the string representation of a date, compatible to strtotime()
- * @return array
- * @access protected
- */
- function _date2array($date)
- {
- $da = array();
- if (is_string($date)) {
- if (preg_match('/^\d+:\d+(:\d+|)(\s+[ap]m|)$/i', $date)) {
- $date = date('Y-m-d ').$date;
- $getDate = false;
- } else {
- $getDate = true;
- }
- include_once('Date.php');
- $dObj = new Date($date);
- if ($getDate) {
- $da['d'] = $dObj->getDay();
- $da['l'] = $da['D'] = $dObj->getDayOfWeek();
- $da['m'] = $da['M'] = $da['F'] = $dObj->getMonth();
- $da['Y'] = $da['y'] = $dObj->getYear();
- }
- $da['H'] = $dObj->getHour();
- $da['h'] = $da['H'] % 12;
- if ($da['h'] == 0) {
- $da['h'] = 12;
- }
- $da['i'] = $dObj->getMinute();
- $da['s'] = $dObj->getSecond();
- if ($da['H'] >= 12) {
- $da['a'] = 'pm';
- $da['A'] = 'PM';
- } else {
- $da['a'] = 'am';
- $da['A'] = 'AM';
- }
- unset($dObj);
- } else {
- if (is_int($date)) {
- $time = $date;
- } else {
- $time = time();
- }
- $da['d'] = date('d', $time);
- $da['l'] = $da['D'] = date('w', $time);
- $da['m'] = $da['M'] = $da['F'] = date('m', $time);
- $da['Y'] = $da['y'] = date('Y', $time);
- $da['H'] = date('H', $time);
- $da['h'] = date('h', $time);
- $da['i'] = date('i', $time);
- $da['s'] = date('s', $time);
- $da['a'] = date('a', $time);
- $da['A'] = date('A', $time);
- }
- $this->debug('<i>_date2array():</i> from '.$date.' ...');
- return $da;
- }
-
-
- /**
- * DB_DataObject_FormBuilder::_array2date()
- *
- * Takes a date array as used by the QuickForm date element and turns it back into
- * a string representation suitable for use with a database date field (format 'YYYY-MM-DD').
- * If second parameter is true, it will return a unix timestamp instead. //FRANK: Not at this point it wont
- *
- * Beware: For the date conversion to work, you must at least use the letters "d", "m" and "Y" in
- * your format string (see "dateElementFormat" option). If you want to enter a time as well,
- * you will have to use "H", "i" and "s" as well. Other letters will not work! Exception: You can
- * also use "M" instead of "m" if you want plain text month names.
- *
- * @param array $date An array representation of a date, as user in HTML_QuickForm's date element
- * @param boolean $timestamp Optional. If true, return a timestamp instead of a string. Defaults to false.
- * @return mixed
- * @access protected
- */
- function _array2date($dateInput, $timestamp = false)
- {
- if (isset($dateInput['M'])) {
- $month = $dateInput['M'];
- } elseif (isset($dateInput['m'])) {
- $month = $dateInput['m'];
- } elseif (isset($dateInput['F'])) {
- $month = $dateInput['F'];
- }
- if (isset($dateInput['Y'])) {
- $year = $dateInput['Y'];
- } elseif (isset($dateInput['y'])) {
- $year = $dateInput['y'];
- }
- if (isset($dateInput['H'])) {
- $hour = $dateInput['H'];
- } elseif (isset($dateInput['h'])) {
- $hour = $dateInput['h'];
- }
- if (isset($dateInput['a'])) {
- $ampm = $dateInput['a'];
- } elseif (isset($dateInput['A'])) {
- $ampm = isset($dateInput['A']);
- }
- $strDate = '';
- if (isset($year) || isset($month) || isset($dateInput['d'])) {
- if (!isset($year)) {
- $year = '0000';
- }
- if(!isset($month)) {
- $month = '00';
- }
- if (!isset($dateInput['d'])) {
- $dateInput['d'] = '00';
- }
- $strDate .= $year.'-'.$month.'-'.$dateInput['d'];
- }
- if (isset($hour) || isset($dateInput['i']) || isset($dateInput['s'])) {
- if (!isset($hour)) {
- $hour = '00';
- }
- if (!isset($dateInput['i'])) {
- $dateInput['i'] = '00';
- }
- if (!empty($strDate)) {
- $strDate .= ' ';
- }
- $strDate .= $hour.':'.$dateInput['i'];
- if (isset($dateInput['s'])) {
- $strDate .= ':'.$dateInput['s'];
- }
- if (isset($ampm)) {
- $strDate .= ' '.$ampm;
- }
- }
- $this->debug('<i>_array2date():</i> to '.$strDate.' ...');
- return $strDate;
- }
-
- /**
- * DB_DataObject_FormBuilder::validateData()
- *
- * Makes a call to the current DataObject's validate() method and returns the result.
- *
- * @return mixed
- * @access public
- * @see DB_DataObject::validate()
- */
- function validateData()
- {
- $this->_validationErrors = $this->_do->validate();
- return $this->_validationErrors;
- }
-
- /**
- * DB_DataObject_FormBuilder::getValidationErrors()
- *
- * Returns errors from data validation. If errors have occured, this will be
- * an array with the fields that have errors, otherwise a boolean.
- *
- * @return mixed
- * @access public
- * @see DB_DataObject::validate()
- */
- function getValidationErrors()
- {
- return $this->_validationErrors;
- }
-
-
- /**
- * DB_DataObject_FormBuilder::processForm()
- *
- * This will take the submitted form data and put it back into the object's properties.
- * If the primary key is not set or NULL, it will be assumed that you wish to insert a new
- * element into the database, so DataObject's insert() method is invoked.
- * Otherwise, an update() will be performed.
- * <i><b>Careful:</b> If you're using natural keys or cross-referencing tables where you don't have
- * one dedicated primary key, this will always assume that you want to do an update! As there
- * won't be a matching entry in the table, no action will be performed at all - the reason
- * for this behaviour can be very hard to detect. Thus, if you have such a situation in one
- * of your tables, simply override this method so that instead of the key check it will try
- * to do a SELECT on the table using the current settings. If a match is found, do an update.
- * If not, do an insert.</i>
- * This method is perfect for use with QuickForm's process method. Example:
- * <code>
- * if ($form->validate()) {
- * $form->freeze();
- * $form->process(array(&$formGenerator,'processForm'), false);
- * }
- * </code>
- *
- * If you wish to enforce a special type of query, use the forceQueryType() method.
- *
- * Always remember to pass your objects by reference - otherwise, if the operation was
- * an insert, the primary key won't get updated with the new database ID because processForm()
- * was using a local copy of the object!
- *
- * If a method named "preProcessForm()" exists in your derived class, it will be called before
- * processForm() starts doing its magic. The data that has been submitted by the form
- * will be passed to that method as a parameter.
- * Same goes for a method named "postProcessForm()", with the only difference - you might
- * have guessed this by now - that it's called after the insert/update operations have
- * been done. Use this for filtering data, notifying users of changes etc.pp. ...
- *
- * @param array $values The values of the submitted form
- * @param string $queryType If the standard query behaviour ain't good enough for you, you can force a certain type of query
- * @return boolean TRUE if database operations were performed, FALSE if not
- * @access public
- */
- function processForm($values)
- {
- if ($this->elementNamePrefix !== '' || $this->elementNamePostfix !== '') {
- $origValues = $values;
- $values = $this->_getMyValues($values);
- }
- $this->debug('<br>...processing form data...<br>');
- if (method_exists($this->_do, 'preprocessform')) {
- if ($this->useCallTimePassByReference) {
- eval('$this->_do->preProcessForm(&$values);');
- } else {
- $this->_do->preProcessForm($values);
- }
- }
-
- $editableFields = $this->_getUserEditableFields();
- $tableFields = $this->_do->table();
- $links = $this->_do->links();
-
- foreach ($values as $field => $value) {
- $this->debug('Field '.$field.' ');
- // Double-check if the field may be edited by the user... if not, don't
- // set the submitted value, it could have been faked!
- if (in_array($field, $editableFields)) {
- if (isset($tableFields[$field])) {
- if (($tableFields[$field] & DB_DATAOBJECT_DATE) || in_array($field, $this->dateFields)) {
- $this->debug('DATE CONVERSION for using callback from '.$value.' ...');
- $value = call_user_func($this->dateToDatabaseCallback, $value);
- } elseif (($tableFields[$field] & DB_DATAOBJECT_TIME) || in_array($field, $this->timeFields)) {
- $this->debug('TIME CONVERSION for using callback from '.$value.' ...');
- $value = call_user_func($this->dateToDatabaseCallback, $value);
- } elseif (is_array($value)) {
- if (isset($value['tmp_name'])) {
- $this->debug(' (converting file array) ');
- $value = $value['name'];
- //JUSTIN
- //This is not really a valid assumption IMHO. This should only be done if the type is
- // date or the field is in dateFields
- /*} else {
- $this->debug("DATE CONVERSION using callback from $value ...");
- $value = call_user_func($this->dateToDatabaseCallback, $value);*/
- }
- }
- if (is_array($links) && isset($links[$field])) {
- if ($value === '') {
- $this->debug('Casting to NULL');
- require_once('DB/DataObject/Cast.php');
- $value = DB_DataObject_Cast::sql('NULL');
- }
- }
- $this->debug('is substituted with "'.$value.'".<br/>');
-
- // See if a setter method exists in the DataObject - if so, use that one
- if (method_exists($this->_do, 'set' . $field)) {
- $this->_do->{'set'.$field}($value);
- } else {
- // Otherwise, just set the property 'normally'...
- $this->_do->$field = $value;
- }
- } else {
- $this->debug('is not a valid field.<br/>');
- }
- } else {
- $this->debug('is defined not to be editable by the user!<br/>');
- }
- }
- foreach ($this->booleanFields as $boolField) {
- if (!isset($values[$boolField])) {
- $this->_do->$boolField = 0;
- }
- }
- foreach ($tableFields as $field => $type) {
- if ($type & DB_DATAOBJECT_BOOL && !isset($values[$field])) {
- $this->_do->$field = 0;
- }
- }
-
- $dbOperations = true;
- if ($this->validateOnProcess === true) {
- $this->debug('Validating data... ');
- if (is_array($this->validateData())) {
- $dbOperations = false;
- }
- }
-
- $pk = $this->_getPrimaryKey($this->_do);
-
- // Data is valid, let's store it!
- if ($dbOperations) {
- $action = $this->_queryType;
- if ($this->_queryType == DB_DATAOBJECT_FORMBUILDER_QUERY_AUTODETECT) {
- // Could the primary key be detected?
- if ($pk === false) {
- // Nope, so let's exit and return false. Sorry, you can't store data using
- // processForm with this DataObject unless you do some tweaking :-(
- $this->debug('Primary key not detected - storing data not possible.');
- return false;
- }
-
- $action = DB_DATAOBJECT_FORMBUILDER_QUERY_FORCEUPDATE;
- if (!isset($this->_do->$pk) || !strlen($this->_do->$pk)) {
- $action = DB_DATAOBJECT_FORMBUILDER_QUERY_FORCEINSERT;
- }
- }
-
- switch ($action) {
- case DB_DATAOBJECT_FORMBUILDER_QUERY_FORCEINSERT:
- $id = $this->_do->insert();
- $this->debug('ID ('.$pk.') of the new object: '.$id.'<br/>');
- break;
- case DB_DATAOBJECT_FORMBUILDER_QUERY_FORCEUPDATE:
- $this->_do->update();
- $this->debug('Object updated.<br/>');
- break;
- }
-
- //triple/crossLinks only work when a primark key is set
- if ($pk && isset($this->_do->$pk) && strlen($this->_do->$pk)) {
- // process tripleLinks
- foreach ($this->tripleLinks as $tripleLink) {
- $do = DB_DataObject::factory($tripleLink['table']);
-
- $links = $do->links();
-
- $fromField = $tripleLink['fromField'];
- $toField1 = $tripleLink['toField1'];
- $toField2 = $tripleLink['toField2'];
-
- if (isset($values['__tripleLink_'.$tripleLink['table']])) {
- $rows = $values['__tripleLink_'.$tripleLink['table']];
- } else {
- $rows = array();
- }
- $do->$fromField = $this->_do->$pk;
- $do->selectAdd();
- $do->selectAdd($toField1);
- $do->selectAdd($toField2);
- if (method_exists($this->_do, 'preparelinkeddataobject')) {
- if ($this->useCallTimePassByReference) {
- eval('$this->_do->prepareLinkedDataObject(&$do, \'__tripleLink_\'.$tripleLink[\'table\']);');
- } else {
- $this->_do->prepareLinkedDataObject($do, '__tripleLink_'.$tripleLink['table']);
- }
- }
- $do->find();
-
- $oldFieldValues = array();
- while ($do->fetch()) {
- if (isset($rows[$do->$toField1]) && in_array($do->$toField2, $rows[$do->$toField1])) {
- $oldFieldValues[$do->$toField1][$do->$toField2] = true;
- } else {
- $do->delete();
- }
- }
-
- if (count($rows) > 0) {
- foreach ($rows as $rowid => $row) {
- if (count($row) > 0) {
- foreach ($row as $fieldvalue) {
- if (!isset($oldFieldValues[$rowid]) || !isset($oldFieldValues[$rowid][$fieldvalue])) {
- $do = DB_DataObject::factory($tripleLink['table']);
- $do->$fromField = $this->_do->$pk;
- $do->$toField1 = $rowid;
- $do->$toField2 = $fieldvalue;
- $do->insert();
- }
- }
- }
- }
- }
- }
-
- //process crossLinks
- foreach ($this->crossLinks as $crossLink) {
- $do = DB_DataObject::factory($crossLink['table']);
- $links = $do->links();
-
- $fromField = $crossLink['fromField'];
- $toField = $crossLink['toField'];
-
- if (isset($values['__crossLink_'.$crossLink['table']])) {
- $fieldvalues = $values['__crossLink_'.$crossLink['table']];
- } else {
- $fieldvalues = array();
- }
- /*if (isset($values['__crossLink_'.$crossLink['table'].'__extraFields'])) {
- $extraFieldValues = $values['__crossLink_'.$crossLink['table'].'__extraFields'];
- } else {
- $extraFieldValues = array();
- }*/
- $do->$fromField = $this->_do->$pk;
- $do->selectAdd();
- $do->selectAdd($toField);
- $do->selectAdd($fromField);
- if ($doKeys = $do->sequenceKey()) {
- $do->selectAdd($doKeys[0]);
- }
- if (method_exists($this->_do, 'preparelinkeddataobject')) {
- if ($this->useCallTimePassByReference) {
- eval('$this->_do->prepareLinkedDataObject(&$do, \'__crossLink_\'.$crossLink[\'table\']);');
- } else {
- $this->_do->prepareLinkedDataObject($do, '__crossLink_'.$crossLink['table']);
- }
- }
- $do->find();
-
- $oldFieldValues = array();
- while ($do->fetch()) {
- if (isset($fieldvalues[$do->$toField])) {
- $oldFieldValues[$do->$toField] = clone($do);
- } else {
- $do->delete();
- }
- }
- if (count($fieldvalues) > 0) {
- foreach ($fieldvalues as $fieldvalue) {
- $crossLinkPrefix = $this->elementNamePrefix.'__crossLink_'.$crossLink['table'].'__'.$fieldvalue.'_';
- $crossLinkPostfix = '_'.$this->elementNamePostfix;
- if (isset($oldFieldValues[$fieldvalue])) {
- if (isset($do->fb_crossLinkExtraFields)) {
- $this->_extraFieldsFb[$crossLinkPrefix.$crossLinkPostfix]->processForm(isset($origValues) ? $origValues : $values);
- /*$do = $oldFieldValues[$fieldvalue];
- $update = false;
- foreach ($do->fb_crossLinkExtraFields as $extraField) {
- if ($do->$extraField !== $extraFieldValues[$fieldvalue][$extraField]) {
- $update = true;
- $do->$extraField = $extraFieldValues[$fieldvalue][$extraField];
- }
- }
- if ($update) {
- $do->update();
- }*/
- }
- } else {
- if (isset($do->fb_crossLinkExtraFields)) {
- $insertValues = isset($origValues) ? $origValues : $values;
- $insertValues[$crossLinkPrefix.$fromField.$crossLinkPostfix] = $this->_do->$pk;
- $insertValues[$crossLinkPrefix.$toField.$crossLinkPostfix] = $fieldvalue;
- $this->_extraFieldsFb[$crossLinkPrefix.$crossLinkPostfix]->fieldsToRender[] = $fromField;
- $this->_extraFieldsFb[$crossLinkPrefix.$crossLinkPostfix]->fieldsToRender[] = $toField;
- $this->_extraFieldsFb[$crossLinkPrefix.$crossLinkPostfix]->processForm($insertValues);
- /*foreach ($do->fb_crossLinkExtraFields as $extraField) {
- $do->$extraField = $extraFieldValues[$do->$toField][$extraField];
- }*/
- } else {
- $do = DB_DataObject::factory($crossLink['table']);
- $do->$fromField = $this->_do->$pk;
- $do->$toField = $fieldvalue;
- $do->insert();
- }
- }
- }
- }
- }
-
- foreach ($this->reverseLinks as $reverseLink) {
- $elName = '__reverseLink_'.$reverseLink['table'].'_'.$reverseLink['field'];
- $do = DB_DataObject::factory($reverseLink['table']);
- if (method_exists($this->_do, 'preparelinkeddataobject')) {
- if ($this->useCallTimePassByReference) {
- eval('$this->_do->prepareLinkedDataObject(&$do, $key);');
- } else {
- $this->_do->prepareLinkedDataObject($do, $key);
- }
- }
- $rLinks = $do->links();
- $rPk = $this->_getPrimaryKey($do);
- $rFields = $do->table();
- list($lTable, $lField) = explode(':', $rLinks[$reverseLink['field']]);
- if ($do->find()) {
- while ($do->fetch()) {
- unset($newVal);
- if (isset($values[$elName][$do->$rPk])) {
- if ($do->{$reverseLink['field']} != $this->_do->$lField) {
- $do->{$reverseLink['field']} = $this->_do->$lField;
- $do->update();
- }
- } elseif ($do->{$reverseLink['field']} == $this->_do->$lField) {
- if (isset($reverseLink['defaultLinkValue'])) {
- $do->{$reverseLink['field']} = $reverseLink['defaultLinkValue'];
- $do->update();
- } else {
- if ($rFields[$reverseLink['field']] & DB_DATAOBJECT_NOTNULL) {
- //ERROR!!
- $this->debug('Checkbox in reverseLinks unset when link field may not be null');
- } else {
- require_once('DB/DataObject/Cast.php');
- $do->{$reverseLink['field']} = DB_DataObject_Cast::sql('NULL');
- $do->update();
- }
- }
- }
- }
- }
- }
- }
- }
-
- if (method_exists($this->_do, 'postprocessform')) {
- if ($this->useCallTimePassByReference) {
- eval('$this->_do->postProcessForm(&$values);');
- } else {
- $this->_do->postProcessForm($values);
- }
- }
-
- return $dbOperations;
- }
-
-
- /**
- * Takes a multi-dimentional array and flattens it. If a value in the array is an array,
- * its keys are added as [key] to the original key.
- * Ex:
- * array('a' => 'a',
- * 'b' => array('a' => 'a',
- * 'b' => array('a' => 'a',
- * 'b' => 'b')),
- * 'c' => 'c')
- * becomes
- * array('a' => 'a',
- * 'b[a]' => 'a',
- * 'b[b][a]' => 'a',
- * 'b[b][b]' => 'b',
- * 'c' => 'c')
- *
- * @param array the array to convert
- * @return array the flattened array
- */
- /*function _multiArrayToSingleArray($arr) {
- do {
- $arrayFound = false;
- foreach ($arr as $key => $val) {
- if (is_array($val)) {
- unset($arr[$key]);
- foreach ($val as $key2 => $val2) {
- $arr[$key.'['.$key2.']'] = $val2;
- }
- $arrayFound = true;
- }
- }
- } while ($arrayFound);
- return $arr;
- }*/
-
-
- /**
- * Takes a full request array and extracts the values for this formBuilder instance.
- * Removes the element name prefix and postfix
- * Will only return values whose key is prefixed with the prefix and postfixed by the postfix
- *
- * @param array array from $_REQUEST
- * @return array array indexed by real field name
- */
- function _getMyValues(&$arr) {
- //$arr = $this->_multiArrayToSingleArray($arr);
- $retArr = array();
- $prefixLen = strlen($this->elementNamePrefix);
- $postfixLen = strlen($this->elementNamePostfix);
- foreach ($arr as $key => $val) {
- if ($prefixLen) {
- if (substr($key, 0, $prefixLen) == $this->elementNamePrefix) {
- $key = substr($key, $prefixLen);
- } else {
- $key = false;
- }
- }
- if ($key !== false && $postfixLen) {
- if (substr($key, -$postfixLen) == $this->elementNamePostfix) {
- $key = substr($key, 0, -$postfixLen);
- } else {
- $key = false;
- }
- }
- if ($key !== false) {
- $retArr[$key] = $val;
- }
- }
- return $retArr;
- }
-
-
- /**
- * DB_DataObject_FormBuilder::forceQueryType()
- *
- * You can force the behaviour of the processForm() method by passing one of
- * the following constants to this method:
- *
- * - DB_DATAOBJECT_FORMBUILDER_QUERY_FORCEINSERT:
- * The submitted data will always be INSERTed into the database
- * - DB_DATAOBJECT_FORMBUILDER_QUERY_FORCEUPDATE:
- * The submitted data will always be used to perform an UPDATE on the database
- * - DB_DATAOBJECT_FORMBUILDER_QUERY_FORCENOACTION:
- * The submitted data will overwrite the properties of the DataObject, but no
- * action will be performed on the database.
- * - DB_DATAOBJECT_FORMBUILDER_QUERY_AUTODETECT:
- * The processForm() method will try to detect for itself if an INSERT or UPDATE
- * query has to be performed. This will not work if no primary key field can
- * be detected for the current DataObject. In this case, no action will be performed.
- * This is the default behaviour.
- *
- * @param integer $queryType The type of the query to be performed. Please use the preset constants for setting this.
- * @return boolean
- * @access public
- */
- function forceQueryType($queryType = DB_DATAOBJECT_FORMBUILDER_QUERY_AUTODETECT)
- {
- switch ($queryType) {
- case DB_DATAOBJECT_FORMBUILDER_QUERY_FORCEINSERT:
- case DB_DATAOBJECT_FORMBUILDER_QUERY_FORCEUPDATE:
- case DB_DATAOBJECT_FORMBUILDER_QUERY_FORCENOACTION:
- case DB_DATAOBJECT_FORMBUILDER_QUERY_AUTODETECT:
- $this->_queryType = $queryType;
- return true;
- break;
- default:
- return false;
- }
- }
-
-
- /**
- * DB_DataObject_FormBuilder::debug()
- *
- * Outputs a debug message, if the debug setting in the DataObject.ini file is
- * set to 1 or higher.
- *
- * @param string $message The message to printed to the browser
- * @access public
- * @see DB_DataObject::debugLevel()
- */
- function debug($message)
- {
- if (DB_DataObject::debugLevel() > 0) {
- echo '<pre><b>FormBuilder:</b> '.$message."</pre>\n";
- }
- }
-
- /**
- * DB_DataObject_FormBuilder::_getFieldsToRender()
- *
- * If the "fb_fieldsToRender" property in a DataObject is not set, all fields
- * will be rendered as form fields.
- * When the property is set, a field will be rendered only if:
- * 1. it is a primary key
- * 2. it's explicitly requested in $do->fb_fieldsToRender
- *
- * @access private
- * @return array The fields that shall be rendered
- */
- function _getFieldsToRender()
- {
- $all_fields = array_merge($this->_do->table(), $this->_getSpecialElementNames());
- if ($this->fieldsToRender) {
- // a little workaround to get an array like [FIELD_NAME] => FIELD_TYPE (for use in _generateForm)
- // maybe there's some better way to do this:
- $result = array();
-
- $key_fields = $this->_do->keys();
- if (!is_array($key_fields)) {
- $key_fields = array();
- }
- $fields_to_render = $this->fieldsToRender;
-
- if (is_array($all_fields)) {
- foreach ($all_fields as $key=>$value) {
- if ( (in_array($key, $key_fields)) || (in_array($key, $fields_to_render)) ) {
- $result[$key] = $all_fields[$key];
- }
- }
- }
-
- if (count($result) > 0) {
- return $result;
- }
- return $all_fields;
- }
- return $all_fields;
- }
-
-
- /**
- * DB_DataObject_FormBuilder::_getUserEditableFields()
- *
- * Normally, all fields in a form are editable by the user. If you want to
- * make some fields uneditable, you have to set the "fb_userEditableFields" property
- * with an array that contains the field names that actually can be edited.
- * All other fields will be freezed (which means, they will still be a part of
- * the form, and they values will still be displayed, but only as plain text, not
- * as form elements).
- *
- * @access private
- * @return array The fields that shall be editable.
- */
- function _getUserEditableFields()
- {
- // if you don't want any of your fields to be editable by the user, set fb_userEditableFields to
- // "array()" in your DataObject-derived class
- if ($this->userEditableFields) {
- return $this->userEditableFields;
- }
- // all fields may be updated by the user since fb_userEditableFields is not set
- if ($this->fieldsToRender) {
- return $this->fieldsToRender;
- }
- return array_keys($this->_getFieldsToRender());
- }
-
-}
-
-?>
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Markus Wolff <mw21st@php.net> |
-// +----------------------------------------------------------------------+
-
-/**
- * This is a driver class for the DB_DataObject_FormBuilder package.
- * It uses HTML_QuickForm to render the forms.
- *
- * @package DB_DataObject_FormBuilder
- * @author Markus Wolff <mw21st@php.net>
- * @version $Id: QuickForm.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
- */
-
-require_once ('HTML/QuickForm.php');
-
-class DB_DataObject_FormBuilder_QuickForm extends DB_DataObject_FormBuilder
-{
- /**
- * Array to determine what QuickForm element types are being used for which
- * general field types. If you configure FormBuilder using arrays, the format is:
- * array('nameOfFieldType' => 'QuickForm_Element_name', ...);
- * If configured via .ini file, the format looks like this:
- * elementTypeMap = shorttext:text,date:date,...
- *
- * Allowed field types:
- * <ul><li>shorttext</li>
- * <li>longtext</<li>
- * <li>date</li>
- * <li>integer</li>
- * <li>float</li></ul>
- */
- var $elementTypeMap = array('shorttext' => 'text',
- 'longtext' => 'textarea',
- 'date' => 'date',
- 'time' => 'date',
- 'datetime' => 'date',
- 'integer' => 'text',
- 'float' => 'text',
- 'select' => 'select',
- 'elementTable' => 'elementTable');
-
- /**
- * Array of attributes for each element type. See the keys of elementTypeMap
- * for the allowed element types.
- *
- * The key is the element type. The value can be a valid attribute string or
- * an associative array of attributes.
- */
- var $elementTypeAttributes = array();
-
- /**
- * Array of attributes for each specific field.
- *
- * The key is the field name. The value can be a valid attribute string or
- * an associative array of attributes.
- */
- var $fieldAttributes = array();
-
- /**
- * DB_DataObject_FormBuilder_QuickForm::DB_DataObject_FormBuilder_QuickForm()
- *
- * The class constructor.
- *
- * @param object $do The DB_DataObject-derived object for which a form shall be built
- * @param array $options An optional associative array of options.
- * @access public
- */
- function DB_DataObject_FormBuilder_QuickForm(&$do, $options = false)
- {
- // Call parent class constructor.
- parent::DB_DataObject_FormBuilder($do,$options);
- }
-
- /**
- * DB_DataObject_FormBuilder_QuickForm::_getQFType()
- *
- * Returns the QuickForm element type associated with the given field type,
- * as defined in the elementTypeMap property. If an unknown field type is given,
- * the returned type name will default to 'text'.
- *
- * @access protected
- * @param string $fieldType The internal field type
- * @return string The QuickForm element type name
- */
- function _getQFType($fieldType)
- {
- if (isset($this->elementTypeMap[$fieldType])) {
- return $this->elementTypeMap[$fieldType];
- }
- return 'text';
- }
-
- /**
- * DB_DataObject_FormBuilder_QuickForm::_getAttributes()
- *
- * Returns the attributes to apply to a field based on the field name and
- * element type. The field's attributes take precedence over the element type's.
- *
- * @param string $elementType the internal type of the element
- * @param string $fieldName the name of the field
- * @return array an array of attributes to apply to the element
- */
- function _getAttributes($elementType, $fieldName) {
- if (isset($this->elementTypeAttributes[$elementType])) {
- if (is_string($this->elementTypeAttributes[$elementType])) {
- $this->elementTypeAttributes[$elementType] =
- HTML_Common::_parseAttributes($this->elementTypeAttributes[$elementType]);
- }
- $attr = $this->elementTypeAttributes[$elementType];
- } else {
- $attr = array();
- }
- if (isset($this->fieldAttributes[$fieldName])) {
- if (is_string($this->fieldAttributes[$fieldName])) {
- $this->fieldAttributes[$fieldName] =
- HTML_Common::_parseAttributes($this->fieldAttributes[$fieldName]);
- }
- $attr = array_merge($attr, $this->fieldAttributes[$fieldName]);
- }
- return $attr;
- }
-
- /**
- * DB_DataObject_FormBuilder_QuickForm::_createFormObject()
- *
- * Creates a QuickForm object to be used by _generateForm().
- *
- * @param string $formName The name of the form
- * @param string $method Method for transferring form data over HTTP (GET|POST)
- * @param string $action The script to transfer the form data to
- * @param string $target Name of the target frame/window to use to display the "action" script
- * @return object The HTML_QuickForm object.
- * @access protected
- * @see DB_DataObject_FormBuilder::_generateForm()
- */
- function &_createFormObject($formName, $method, $action, $target)
- {
- // If there is an existing QuickForm object, and the form object should not just be
- // appended, use that one. If not, make a new one.
- if (is_a($this->_form, 'html_quickform') && $this->_appendForm == false) {
- $form =& $this->_form;
- } else {
- $form =& new HTML_QuickForm($formName, $method, $action, $target);
- }
- return $form;
- }
-
- /**
- * DB_DataObject_FormBuilder_QuickForm::_addFormHeader()
- *
- * Adds a header to the given form. Will use the header defined in the "formHeaderText" property.
- * Used in _generateForm().
- *
- * @param object $form The QuickForm object to add the header to
- * @access protected
- * @see DB_DataObject_FormBuilder::_generateForm()
- */
- function _addFormHeader(&$form)
- {
- // Add a header to the form - set addFormHeader property to false to prevent this
- if ($this->addFormHeader == true) {
- if (!is_null($this->formHeaderText)) {
- $form->addElement('header', '', $this->formHeaderText);
- } else {
- $form->addElement('header', '', $this->_do->tableName());
- }
- }
- }
-
- /**
- * DB_DataObject_FormBuilder_QuickForm::_createHiddenField()
- *
- * Returns a QuickForm element for a hidden field.
- * Used in _generateForm().
- *
- * @param string $fieldName The field name to use for the QuickForm element
- * @access protected
- * @see DB_DataObject_FormBuilder::_generateForm()
- */
- function &_createHiddenField($fieldName)
- {
- $element =& HTML_QuickForm::createElement('hidden',
- $this->getFieldName($fieldName));
- $attr = $this->_getAttributes('hidden', $fieldName);
- $element->updateAttributes($attr);
- return $element;
- }
-
- /**
- * DB_DataObject_FormBuilder_QuickForm::_createRadioButtons()
- *
- * Returns a QuickForm element for a group of radio buttons.
- * Used in _generateForm().
- *
- * @param string $fieldName The field name to use for the QuickForm element group
- * @param array $options The list of options to generate the radio buttons for
- * @return array Array of HTML_QuickForm_element objects.
- * @access protected
- * @see DB_DataObject_FormBuilder::_generateForm()
- */
- function &_createRadioButtons($fieldName, $options)
- {
- $element = array();
- $attr = $this->_getAttributes('radio', $fieldName);
- foreach($options as $value => $display) {
- unset($radio);
- $radio =& HTML_QuickForm::createElement('radio',
- $this->getFieldName($fieldName),
- null,
- $display,
- $value);
- $radio->updateAttributes($attr);
- $element[] =& $radio;
- }
- return $element;
- }
-
- /**
- * DB_DataObject_FormBuilder_QuickForm::_createCheckbox()
- *
- * Returns a QuickForm element for a checkbox.
- * Used in _generateForm().
- *
- * @param string $fieldName The field name to use for the QuickForm element
- * @param string $text Text to label the checkbox
- * @param string $value The value that is submitted when the checkbox is checked
- * @param boolean $checked Is the checkbox checked? (Default: False)
- * @param boolean $freeze Is the checkbox frozen? (Default: False)
- * @return object The HTML_QuickForm_element object.
- * @access protected
- * @see DB_DataObject_FormBuilder::_generateForm()
- */
- function &_createCheckbox($fieldName, $text = null, $value = null, $label = null, $checked = false, $freeze = false)
- {
- $element =& HTML_QuickForm::createElement('checkbox',
- $this->getFieldName($fieldName),
- $label,
- $text);
- if ($value !== null) {
- $element->updateAttributes(array('value' => $value));
- }
- if ($checked) {
- $element->setChecked(true);
- }
- if ($freeze) {
- $element->freeze();
- }
- $attr = $this->_getAttributes('checkbox', $fieldName);
- $element->updateAttributes($attr);
- return $element;
- }
-
- /**
- * DB_DataObject_FormBuilder_QuickForm::_createTextField()
- *
- * Returns a QuickForm element for a single-line text field.
- * Used in _generateForm().
- *
- * @param string $fieldName The field name to use for the QuickForm element
- * @return object The HTML_QuickForm_element object.
- * @access protected
- * @see DB_DataObject_FormBuilder::_generateForm()
- */
- function &_createTextField($fieldName)
- {
- $element =& HTML_QuickForm::createElement($this->_getQFType('shorttext'),
- $this->getFieldName($fieldName),
- $this->getFieldLabel($fieldName));
- $attr = $this->_getAttributes('shorttext', $fieldName);
- $element->updateAttributes($attr);
- return $element;
- }
-
- /**
- * DB_DataObject_FormBuilder_QuickForm::_createIntegerField()
- *
- * Returns a QuickForm element for an integer field.
- * Used in _generateForm().
- *
- * @param string $fieldName The field name to use for the QuickForm element
- * @return object The HTML_QuickForm_element object.
- * @access protected
- * @see DB_DataObject_FormBuilder::_generateForm()
- */
- function &_createIntegerField($fieldName)
- {
- $element =& HTML_QuickForm::createElement($this->_getQFType('integer'),
- $this->getFieldName($fieldName),
- $this->getFieldLabel($fieldName));
- $attr = $this->_getAttributes('integer', $fieldName);
- $element->updateAttributes($attr);
- return $element;
- }
-
- /**
- * DB_DataObject_FormBuilder_QuickForm::_createTextArea()
- *
- * Returns a QuickForm element for a long text field.
- * Used in _generateForm().
- *
- * @param string $fieldName The field name to use for the QuickForm element
- * @return object The HTML_QuickForm_element object.
- * @access protected
- * @see DB_DataObject_FormBuilder::_generateForm()
- */
- function &_createTextArea($fieldName)
- {
- $element =& HTML_QuickForm::createElement($this->_getQFType('longtext'),
- $this->getFieldName($fieldName),
- $this->getFieldLabel($fieldName));
- $attr = $this->_getAttributes('longtext', $fieldName);
- $element->updateAttributes($attr);
- return $element;
- }
-
- /**
- * DB_DataObject_FormBuilder_QuickForm::_createSelectBox()
- *
- * Returns a QuickForm element for a selectbox/combobox.
- * Used in _generateForm().
- *
- * @param string $fieldName The field name to use for the QuickForm element
- * @param array $options List of options for populating the selectbox
- * @param boolean $multiple If set to true, the select box will be a multi-select
- * @return object The HTML_QuickForm_element object.
- * @access protected
- * @see DB_DataObject_FormBuilder::_generateForm()
- */
- function &_createSelectBox($fieldName, $options, $multiple = false)
- {
- if ($multiple) {
- $element =& HTML_QuickForm::createElement($this->_getQFType('select'),
- $this->getFieldName($fieldName),
- $this->getFieldLabel($fieldName),
- $options,
- array('multiple' => 'multiple'));
- } else {
- $element =& HTML_QuickForm::createElement($this->_getQFType('select'),
- $this->getFieldName($fieldName),
- $this->getFieldLabel($fieldName),
- $options);
- }
- $attr = $this->_getAttributes('select', $fieldName);
- $element->updateAttributes($attr);
- return $element;
- }
-
- /**
- * DB_DataObject_FormBuilder_QuickForm::_createStaticField()
- *
- * Returns a QuickForm element for displaying static HTML.
- * Used in _generateForm().
- *
- * @param string $fieldName The field name to use for the QuickForm element
- * @param string $text The text or HTML code to display in place of this element
- * @return object The HTML_QuickForm_element object.
- * @access protected
- * @see DB_DataObject_FormBuilder::_generateForm()
- */
- function &_createStaticField($fieldName, $text = null)
- {
- $element =& HTML_QuickForm::createElement('static',
- $this->getFieldName($fieldName),
- $this->getFieldLabel($fieldName),
- $text);
- $attr = $this->_getAttributes('static', $fieldName);
- $element->updateAttributes($attr);
- return $element;
- }
-
- /**
- * DB_DataObject_FormBuilder_QuickForm::_addElementGroupToForm()
- *
- * Adds a group of elements to a form object
- * Used in _generateForm().
- *
- * @param object $form The QuickForm object to add the group to
- * @param array $element Array of QuickForm element objects
- * @param string $fieldName The field name to use for the QuickForm element group
- * @param string $separator Some text or HTML snippet used to separate the group entries
- * @access protected
- * @see DB_DataObject_FormBuilder::_generateForm()
- */
- function _addElementGroupToForm(&$form, &$element, $fieldName, $separator = '')
- {
- $form->addGroup($element,
- $this->getFieldName($fieldName),
- $this->getFieldLabel($fieldName),
- $separator,
- false);
- }
-
- /**
- * DB_DataObject_FormBuilder_QuickForm::_addElementToForm()
- *
- * Adds a QuickForm element to a form object
- * Used in _generateForm().
- *
- * @param object $form The form object to add the element to
- * @param object $element The element object to be added
- * @access protected
- * @see DB_DataObject_FormBuilder::_generateForm()
- */
- function _addElementToForm(&$form, &$element)
- {
- $form->addElement($element);
- }
-
- /**
- * DB_DataObject_FormBuilder_QuickForm::_addSubmitButtonToForm()
- *
- * @param HTML_QuickForm the form to add the submit button to
- * @param string the name of the submit element to be created
- * @param string the text to be put on the submit button
- */
- function _addSubmitButtonToForm(&$form, $fieldName, $text)
- {
- $element =& $this->_createSubmitButton($fieldName, $text);
- $this->_addElementToForm($form, $element);
- }
-
- /**
- * DB_DataObject_FormBuilder_QuickForm::_createSubmitButton()
- *
- * Returns a QuickForm element for a submit button.
- * Used in _generateForm().
- *
- * @param string the name of the submit button
- * @param string the text to put in the button
- * @return object The HTML_QuickForm_element object.
- * @access protected
- * @see DB_DataObject_FormBuilder::_generateForm()
- */
- function &_createSubmitButton($fieldName, $text)
- {
- $element =& HTML_QuickForm::createElement('submit', $fieldName, $text);
- $attr = $this->_getAttributes('submit', $fieldName);
- $element->updateAttributes($attr);
- return $element;
- }
-
- /**
- * DB_DataObject_FormBuilder_QuickForm::_createDateElement()
- *
- * Returns a QuickForm element for entering date values.
- * Used in _generateForm().
- *
- * @param string $fieldName The field name to use for the element
- * @return object The HTML_QuickForm_element object.
- * @access protected
- * @see DB_DataObject_FormBuilder::_generateForm()
- */
- function &_createDateElement($fieldName) {
- $dateOptions = array('format' => $this->dateElementFormat,
- 'language' => $this->dateFieldLanguage);
- if (method_exists($this->_do, 'dateoptions')) {
- $dateOptions = array_merge($dateOptions, $this->_do->dateOptions($fieldName));
- }
- if (!isset($dateOptions['addEmptyOption']) && in_array($fieldName, $this->selectAddEmpty)) {
- $dateOptions['addEmptyOption'] = true;
- }
- $element =& HTML_QuickForm::createElement($this->_getQFType('date'),
- $this->getFieldName($fieldName),
- $this->getFieldLabel($fieldName),
- $dateOptions);
- $attr = $this->_getAttributes('date', $fieldName);
- $element->updateAttributes($attr);
- return $element;
- }
-
- /**
- * DB_DataObject_FormBuilder_QuickForm::_createTimeElement()
- *
- * Returns a QuickForm element for entering time values.
- * Used in _generateForm().
- * Note by Frank: The only reason for this is the difference in timeoptions so it
- * probably would be better integrated with _createDateElement
- *
- * @param string $fieldName The field name to use for the element
- * @return object The HTML_QuickForm_element object.
- * @access protected
- * @see DB_DataObject_FormBuilder::_generateForm()
- */
- function &_createTimeElement($fieldName) {
- $timeOptions = array('format' => $this->timeElementFormat,
- 'language' => $this->dateFieldLanguage);
- if (method_exists($this->_do, 'timeoptions')) { // Frank: I'm trying to trace this but am unsure of it //
- $timeOptions = array_merge($timeOptions, $this->_do->timeOptions($fieldName));
- }
- if (!isset($timeOptions['addEmptyOption']) && in_array($fieldName, $this->selectAddEmpty)) {
- $timeOptions['addEmptyOption'] = true;
- }
- $element =& HTML_QuickForm::createElement($this->_getQFType('time'),
- $this->getFieldName($fieldName),
- $this->getFieldLabel($fieldName),
- $timeOptions);
- $attr = $this->_getAttributes('time', $fieldName);
- $element->updateAttributes($attr);
- return $element;
- }
-
- /**
- * DB_DataObject_FormBuilder_QuickForm::_createDateTimeElement()
- *
- * Returns a QuickForm element for entering date values.
- * Used in _generateForm().
- *
- * @param string $fieldName The field name to use for the element
- * @return object The HTML_QuickForm_element object.
- * @access protected
- * @see DB_DataObject_FormBuilder::_generateForm()
- */
- function &_createDateTimeElement($fieldName) {
- $dateOptions = array('format' => $this->dateTimeElementFormat,
- 'language' => $this->dateFieldLanguage);
- if (method_exists($this->_do, 'datetimeoptions')) {
- $dateOptions = array_merge($dateOptions, $this->_do->dateTimeOptions($fieldName));
- }
- if (!isset($dateOptions['addEmptyOption']) && in_array($fieldName, $this->selectAddEmpty)) {
- $dateOptions['addEmptyOption'] = true;
- }
- $element =& HTML_QuickForm::createElement($this->_getQFType('datetime'),
- $this->getFieldName($fieldName),
- $this->getFieldLabel($fieldName),
- $dateOptions);
- $attr = $this->_getAttributes('datetime', $fieldName);
- $element->updateAttributes($attr);
- return $element;
- }
-
- /**
- * DB_DataObject_FormBuilder_QuickForm::_addElementTableToForm
- *
- * Adds an elementTable to the form
- *
- * @param HTML_QuickForm $form the form to add the element to
- * @param string $fieldName the name of the element to be added
- * @param array $columnNames an array of the column names
- * @param array $rowNames an array of the row names
- * @param array $rows an array of rows, each row being an array of HTML_QuickForm elements
- */
- function _addElementTableToForm(&$form, $fieldName, $columnNames, $rowNames, &$rows) {
- if (!HTML_QuickForm::isTypeRegistered('elementTable')) {
- HTML_QuickForm::registerElementType('elementTable',
- 'DB/DataObject/FormBuilder/QuickForm/ElementTable.php',
- 'DB_DataObject_FormBuilder_QuickForm_ElementTable');
- }
- $element =& HTML_QuickForm::createElement($this->_getQFType('elementTable'),
- $this->getFieldName($fieldName),
- $this->getFieldLabel($fieldName));
- $element->setColumnNames($columnNames);
- $element->setRowNames($rowNames);
- $element->setRows($rows);
- $attr = $this->_getAttributes('elementTable', $fieldName);
- $element->updateAttributes($attr);
- $this->_addElementToForm($form, $element);
- }
-
- /**
- * DB_DataObject_FormBuilder_QuickForm::_setFormDefaults()
- *
- * @param HTML_QuickForm the form to set the defaults on
- * @param array Assoc array of default values (@see HTML_QuickForm::setDefaults)
- */
- function _setFormDefaults(&$form, $defaults)
- {
- $form->setDefaults($defaults);
- }
-
- /**
- * DB_DataObject_FormBuilder_QuickForm::_setFormElementRequired()
- *
- * Adds a required rule for a specific element to a form
- * Used in _generateForm().
- *
- * @param object $form The form object to add the rule to
- * @param object $fieldName The name of the required field
- * @access protected
- * @see DB_DataObject_FormBuilder::_generateForm()
- */
- function _setFormElementRequired(&$form, $fieldName)
- {
- $this->_addFieldRulesToForm($form,
- array(array('validator' => 'required',
- 'rule' => false,
- 'message' => $this->requiredRuleMessage)),
- $fieldName);
- }
-
- /**
- * DB_DataObject_FormBuilder_QuickForm::_addFieldRulesToForm()
- *
- * Adds a set of rules to a form that will apply to a specific element
- * Used in _generateForm().
- *
- * @param object $form The form object to add the ruleset to
- * @param array $rules Array of rule names to be enforced on the element (must be registered QuickForm rules)
- * @param string $fieldName Name of the form element in question
- * @access protected
- * @see DB_DataObject_FormBuilder::_generateForm()
- */
- function _addFieldRulesToForm(&$form, $rules, $fieldName)
- {
- $fieldLabel = $this->getFieldLabel($fieldName);
- $ruleSide = $this->clientRules ? 'client' : 'server';
- foreach ($rules as $rule) {
- if ($rule['rule'] === false) {
- $form->addRule($this->getFieldName($fieldName),
- sprintf($rule['message'], $fieldLabel),
- $rule['validator'],
- '',
- $ruleSide);
- } else {
- $form->addRule($this->getFieldName($fieldName),
- sprintf($rule['message'], $fieldLabel),
- $rule['validator'],
- $rule['rule'],
- $ruleSide);
- } // End if
- } // End while
- }
-
- /**
- * DB_DataObject_FormBuilder_QuickForm::_freezeFormElements()
- *
- * Freezes a list of form elements (set read-only).
- * Used in _generateForm().
- *
- * @param object $form The form object in question
- * @param array $elements_to_freeze List of element names to be frozen
- * @access protected
- * @see DB_DataObject_FormBuilder::_generateForm()
- */
- function _freezeFormElements(&$form, $elementsToFreeze)
- {
- foreach ($elementsToFreeze as $elementToFreeze) {
- $elementToFreeze = $this->getFieldName($elementToFreeze);
- if ($form->elementExists($elementToFreeze)) {
- $el =& $form->getElement($elementToFreeze);
- $el->freeze();
- }
- }
- }
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Justin Patrin <justinpatrin@php.net> |
-// +----------------------------------------------------------------------+
-
-/**
- * @package DB_DataObject_FormBuilder
- * @author Justin Patrin <justinpatrin@php.net>
- * @version $Id: ElementTable.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
- */
-
-require_once('HTML/QuickForm/element.php');
-
-/**
- * An HTML_QuickForm element which creates a table of elements
- */
-class DB_DataObject_FormBuilder_QuickForm_ElementTable extends HTML_QuickForm_element {
-
- /**
- * Array of arrays of HTML_QuickForm elements
- *
- * @var array
- */
- var $_rows = array();
-
- /**
- * Array of column names (strings)
- *
- * @var array
- */
- var $_columnNames = array();
-
- /**
- * Array of row names (strings)
- *
- * @var array
- */
- var $_rowNames = array();
-
- /**
- * Constructor
- *
- * @param string name for the element
- * @param string label for the element
- */
- function DB_DataObject_FormBuilder_QuickForm_ElementTable($name = null, $label = null/*, $columnNames = null,
- $rowNames = null, $rows = null, $attributes = null*/) {
- parent::HTML_QuickForm_element($name, $label);
- //$this->setRows($rows);
- //$this->setColumnNames($columnNames);
- //$this->setRowNames($rowNames);
- }
-
- /**
- * Sets the column names
- *
- * @param array array of column names (strings)
- */
- function setColumnNames($columnNames) {
- $this->_columnNames = $columnNames;
- }
-
- /**
- * Adds a column name
- *
- * @param string name of the column
- */
- function addColumnName($columnName) {
- $this->_columnNames[] = $columnName;
- }
-
- /**
- * Set the row names
- *
- * @param array array of row names (strings)
- */
- function setRowNames($rowNames) {
- $this->_rowNames = $rowNames;
- }
-
- /**
- * Sets the rows
- *
- * @param array array of HTML_QuickForm elements
- */
- function setRows(&$rows) {
- $this->_rows =& $rows;
- }
-
- /**
- * Adds a row to the table
- *
- * @param array array of HTML_QuickForm elements
- * @param string name of the row
- */
- function addRow(&$row, $rowName = null) {
- $this->_rows[] =& $row;
- if ($rowName !== null) {
- $this->addRowName($rowName);
- }
- }
-
- /**
- * Adds a row name
- *
- * @param string name of the row
- */
- function addRowName($rowName) {
- $this->_rowNames[] = $rowName;
- }
-
- /**
- * Freezes all checkboxes in the table
- */
- function freeze() {
- parent::freeze();
- foreach (array_keys($this->_rows) as $key) {
- foreach (array_keys($this->_rows[$key]) as $key2) {
- $this->_rows[$key][$key2]->freeze();
- }
- }
- }
-
- /**
- * Returns Html for the group
- *
- * @access public
- * @return string
- */
- function toHtml()
- {
- include_once ('HTML/Table.php');
- $tripleLinkTable = new HTML_Table();
- $tripleLinkTable->setAutoGrow(true);
- $tripleLinkTable->setAutoFill('');
- $tripleLinkTable->updateAttributes($this->getAttributes());
- $row = 0;
- $col = 0;
-
- foreach ($this->_columnNames as $key => $value) {
- ++$col;
- $tripleLinkTable->setCellContents($row, $col, $value);
- $tripleLinkTable->setCellAttributes($row, $col, array('style' => 'text-align: center'));
- }
-
- foreach (array_keys($this->_rows) as $key) {
- ++$row;
- $col = 0;
- $tripleLinkTable->setCellContents($row, $col, $this->_rowNames[$key]);
- foreach (array_keys($this->_rows[$key]) as $key2) {
- ++$col;
- $tripleLinkTable->setCellContents($row, $col, $this->_rows[$key][$key2]->toHTML());
- $tripleLinkTable->setCellAttributes($row, $col, array('style' => 'text-align: center'));
- }
- }
- $hrAttrs = array('bgcolor' => 'lightgrey');
- $tripleLinkTable->setRowAttributes(0, $hrAttrs, true);
- $tripleLinkTable->setColAttributes(0, $hrAttrs);
- return $tripleLinkTable->toHTML();
-
- /*include_once('HTML/QuickForm/Renderer/Default.php');
- $renderer =& new HTML_QuickForm_Renderer_Default();
- $renderer->setElementTemplate('{element}');
- $this->accept($renderer);
- return $renderer->toHtml();*/
- } //end func toHtml
-
- /**
- * Called by HTML_QuickForm whenever form event is made on this element
- *
- * @param string Name of event
- * @param mixed event arguments
- * @param object calling object
- * @access public
- * @return bool true
- */
- function onQuickFormEvent($event, $arg, &$caller)
- {
- switch ($event) {
- case 'updateValue':
- foreach (array_keys($this->_rows) as $key) {
- foreach (array_keys($this->_rows[$key]) as $key2) {
- $this->_rows[$key][$key2]->onQuickFormEvent('updateValue', null, $caller);
- }
- }
- break;
-
- default:
- parent::onQuickFormEvent($event, $arg, $caller);
- }
- return true;
- }
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Alan Knowles <alan@akbkhome.com>
-// +----------------------------------------------------------------------+
-// $Id: Generator.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
-
-/**
- * Generation tools for DB_DataObject
- *
- * Config _$ptions
- * [DB_DataObject_Generator]
- * ; optional default = DB/DataObject.php
- * extends_location =
- * ; optional default = DB_DataObject
- * extends =
- * ; leave blank to not generate template stuff.
- * make_template = display,list,edit
- *
- * ; options for Template Generation (using FlexyTemplate
- * [DB_DataObject_Generator_Template_Flexy]
- * templateDir = /home/xxx/templates
- * compileDir = /home/xxx/compiled",
- * filters = php,simpletags,bodyonly
- * forceCompile = 0
- *
- * ; fileds to flags as hidden for template generation(preg_match format)
- * hideFields = password
- * ; fields to flag as read only.. (preg_match format)
- * readOnlyFields = created|person_created|modified|person_modified
- * ; fields to flag as links (from lists->edit/view) (preg_match formate)
- * linkFields = id|username|name
- * ; alter the extends field when updating a class (defaults to only replacing DB_DataObject)
- * generator_class_rewrite = ANY|specific_name // default is DB_DataObject
- *
- * @package DB_DataObject
- * @category DB
- */
-
-/**
- * Needed classes
- */
-require_once 'DB/DataObject.php';
-//require_once('Config.php');
-
-/**
- * Generator class
- *
- * @package DB_DataObject
- */
-class DB_DataObject_Generator extends DB_DataObject
-{
- /* =========================================================== */
- /* Utility functions - for building db config files */
- /* =========================================================== */
-
- /**
- * Array of table names
- *
- * @var array
- * @access private
- */
- var $tables;
-
- /**
- * associative array table -> array of table row objects
- *
- * @var array
- * @access private
- */
- var $_definitions;
-
- /**
- * active table being output
- *
- * @var string
- * @access private
- */
- var $table; // active tablename
-
-
- /**
- * The 'starter' = call this to start the process
- *
- * @access public
- * @return none
- */
- function start()
- {
- $options = &PEAR::getStaticProperty('DB_DataObject','options');
- $databases = array();
- foreach($options as $k=>$v) {
- if (substr($k,0,9) == 'database_') {
- $databases[substr($k,9)] = $v;
- }
- }
-
- if (@$options['database']) {
- require_once 'DB.php';
- $dsn = DB::parseDSN($options['database']);
- if (!isset($database[$dsn['database']])) {
- $databases[$dsn['database']] = $options['database'];
- }
- }
-
- foreach($databases as $databasename => $database) {
- if (!$database) continue;
- $this->debug("CREATING FOR $databasename\n");
- $class = get_class($this);
- $t = new $class;
- $t->_database_dsn = $database;
- $t->_database = $databasename;
- $t->_createTableList();
-
- foreach(get_class_methods($class) as $method) {
- if (substr($method,0,8 ) != 'generate') {
- continue;
- }
- $this->debug("calling $method");
- $t->$method();
- }
- }
- $this->debug("DONE\n\n");
- }
-
- /**
- * Output File was config object, now just string
- * Used to generate the Tables
- *
- * @var string outputbuffer for table definitions
- * @access private
- */
- var $_newConfig;
-
- /**
- * Build a list of tables;
- * Currently this is very Mysql Specific - ideas for more generic stiff welcome
- *
- * @access private
- * @return none
- */
- function _createTableList()
- {
- $this->_connect();
- $options = &PEAR::getStaticProperty('DB_DataObject','options');
-
- $__DB= &$GLOBALS['_DB_DATAOBJECT']['CONNECTIONS'][$this->_database_dsn_md5];
-
- $this->tables = $__DB->getListOf('tables');
-
- if (is_a($this->tables , 'PEAR_Error')) {
- return PEAR::raiseError($this->tables->toString(), null, PEAR_ERROR_DIE);
- }
- // build views as well if asked to.
- if (!empty($options['build_views'])) {
- $this->tables = array_merge ($this->tables, $__DB->getListOf('views'));
- }
-
-
- // declare a temporary table to be filled with matching tables names
- $tmp_table = array();
-
-
- foreach($this->tables as $table) {
- if (isset($options['generator_include_regex']) &&
- !preg_match($options['generator_include_regex'],$table)) {
- continue;
- } else if (isset($options['generator_exclude_regex']) &&
- preg_match($options['generator_exclude_regex'],$table)) {
- continue;
- }
-
- // we find a matching table, just store it into a temporary array
- $tmp_table[] = $table;
-
- $defs = $__DB->tableInfo($table);
- if (is_a($defs,'PEAR_Error')) {
- echo $defs->toString();
- exit;
- }
- // cast all definitions to objects - as we deal with that better.
- foreach($defs as $def) {
- if (is_array($def)) {
- $this->_definitions[$table][] = (object) $def;
- }
- }
- }
- // the temporary table array is now the right one (tables names matching
- // with regex expressions have been removed)
- $this->tables = $tmp_table;
- //print_r($this->_definitions);
- }
-
- /**
- * Auto generation of table data.
- *
- * it will output to db_oo_{database} the table definitions
- *
- * @access private
- * @return none
- */
- function generateDefinitions()
- {
- $this->debug("Generating Definitions file: ");
- if (!$this->tables) {
- $this->debug("-- NO TABLES -- \n");
- return;
- }
-
- $options = &PEAR::getStaticProperty('DB_DataObject','options');
-
-
- //$this->_newConfig = new Config('IniFile');
- $this->_newConfig = '';
- foreach($this->tables as $this->table) {
- $this->_generateDefinitionsTable();
- }
- $this->_connect();
- // dont generate a schema if location is not set
- // it's created on the fly!
- if (!@$options['schema_location'] && @!$options["ini_{$this->_database}"] ) {
- return;
- }
- $base = @$options['schema_location'];
- if (isset($options["ini_{$this->_database}"])) {
- $file = $options["ini_{$this->_database}"];
- } else {
- $file = "{$base}/{$this->_database}.ini";
- }
-
- if (!file_exists(dirname($file))) {
- require_once 'System.php';
- System::mkdir(array('-p','-m',0755,dirname($file)));
- }
- $this->debug("Writing ini as {$file}\n");
- touch($file);
- //print_r($this->_newConfig);
- $fh = fopen($file,'w');
- fwrite($fh,$this->_newConfig);
- fclose($fh);
- //$ret = $this->_newConfig->writeInput($file,false);
-
- //if (PEAR::isError($ret) ) {
- // return PEAR::raiseError($ret->message,null,PEAR_ERROR_DIE);
- // }
- }
-
- /**
- * The table geneation part
- *
- * @access private
- * @return tabledef and keys array.
- */
- function _generateDefinitionsTable()
- {
- global $_DB_DATAOBJECT;
-
- $defs = $this->_definitions[$this->table];
- $this->_newConfig .= "\n[{$this->table}]\n";
- $keys_out = "\n[{$this->table}__keys]\n";
- $keys_out_primary = '';
- $keys_out_secondary = '';
- if (@$_DB_DATAOBJECT['CONFIG']['debug'] > 2) {
- echo "TABLE STRUCTURE FOR {$this->table}\n";
- print_r($defs);
- }
- $DB = $this->getDatabaseConnection();
- $dbtype = $DB->phptype;
-
- $ret = array(
- 'table' => array(),
- 'keys' => array(),
- );
-
- $ret_keys_primary = array();
- $ret_keys_secondary = array();
-
-
-
- foreach($defs as $t) {
-
- $n=0;
-
- switch (strtoupper($t->type)) {
-
- case 'INT':
- case 'INT2': // postgres
- case 'INT4': // postgres
- case 'INT8': // postgres
- case 'SERIAL4': // postgres
- case 'SERIAL8': // postgres
- case 'INTEGER':
- case 'TINYINT':
- case 'SMALLINT':
- case 'MEDIUMINT':
- case 'BIGINT':
- $type = DB_DATAOBJECT_INT;
- if ($t->len == 1) {
- $type += DB_DATAOBJECT_BOOL;
- }
- break;
-
- case 'REAL':
- case 'DOUBLE':
- case 'FLOAT':
- case 'FLOAT8': // double precision (postgres)
- case 'DECIMAL':
- case 'NUMERIC':
- $type = DB_DATAOBJECT_INT; // should really by FLOAT!!! / MONEY...
- break;
-
- case 'YEAR':
- $type = DB_DATAOBJECT_INT;
- break;
-
- case 'BIT':
- case 'BOOL':
- case 'BOOLEAN':
-
- $type = DB_DATAOBJECT_BOOL;
- // postgres needs to quote '0'
- if ($dbtype == 'pgsql') {
- $type += DB_DATAOBJECT_STR;
- }
- break;
-
- case 'STRING':
- case 'CHAR':
- case 'VARCHAR':
- case 'VARCHAR2':
- case 'TINYTEXT':
- case 'TEXT':
- case 'MEDIUMTEXT':
- case 'LONGTEXT':
- case 'ENUM':
- case 'SET': // not really but oh well
- case 'TIMESTAMPTZ': // postgres
- case 'BPCHAR': // postgres
- case 'INTERVAL': // postgres (eg. '12 days')
-
- case 'CIDR': // postgres IP net spec
- case 'INET': // postgres IP
- case 'MACADDR': // postgress network Mac address.
-
-
- $type = DB_DATAOBJECT_STR;
- break;
-
- case 'DATE':
- $type = DB_DATAOBJECT_STR + DB_DATAOBJECT_DATE;
- break;
-
- case 'TIME':
- $type = DB_DATAOBJECT_STR + DB_DATAOBJECT_TIME;
- break;
-
-
- case 'DATETIME':
-
- $type = DB_DATAOBJECT_STR + DB_DATAOBJECT_DATE + DB_DATAOBJECT_TIME;
- break;
-
- case 'TIMESTAMP': // do other databases use this???
-
- $type = ($dbtype == 'mysql') ?
- DB_DATAOBJECT_MYSQLTIMESTAMP :
- DB_DATAOBJECT_STR + DB_DATAOBJECT_DATE + DB_DATAOBJECT_TIME;
- break;
-
-
- case 'TINYBLOB':
- case 'BLOB': /// these should really be ignored!!!???
- case 'MEDIUMBLOB':
- case 'LONGBLOB':
- case 'BYTEA': // postgres blob support..
- $type = DB_DATAOBJECT_STR + DB_DATAOBJECT_BLOB;
- break;
-
-
- }
-
-
- if (!strlen(trim($t->name))) {
- continue;
- }
-
- if (preg_match('/not_null/i',$t->flags)) {
- $type += DB_DATAOBJECT_NOTNULL;
- }
-
- $this->_newConfig .= "{$t->name} = $type\n";
- $ret['table'][$t->name] = $type;
- // i've no idea if this will work well on other databases?
- // only use primary key or nextval(), cause the setFrom blocks you setting all key items...
- // if no keys exist fall back to using unique
- //echo "\n{$t->name} => {$t->flags}\n";
- if (preg_match("/(auto_increment|nextval\()/i",rawurldecode($t->flags))) {
- // native sequences = 2
- $keys_out_primary .= "{$t->name} = N\n";
- $ret_keys_primary[$t->name] = 'N';
- } else if (preg_match("/(primary|unique)/i",$t->flags)) {
- // keys.. = 1
- $keys_out_secondary .= "{$t->name} = K\n";
- $ret_keys_secondary[$t->name] = 'K';
- }
-
-
-
-
- }
-
- $this->_newConfig .= $keys_out . (empty($keys_out_primary) ? $keys_out_secondary : $keys_out_primary);
- $ret['keys'] = empty($keys_out_primary) ? $ret_keys_secondary : $ret_keys_primary;
-
- if (@$_DB_DATAOBJECT['CONFIG']['debug'] > 2) {
- print_r(array("dump for {$this->table}", $ret));
- }
-
- return $ret;
-
-
- }
-
- /*
- * building the class files
- * for each of the tables output a file!
- */
- function generateClasses()
- {
- //echo "Generating Class files: \n";
- $options = &PEAR::getStaticProperty('DB_DataObject','options');
- $base = $options['class_location'];
- if (!file_exists($base)) {
- require_once 'System.php';
- System::mkdir(array('-p',$base));
- }
- $class_prefix = $options['class_prefix'];
- if ($extends = @$options['extends']) {
- $this->_extends = $extends;
- $this->_extendsFile = $options['extends_location'];
- }
-
- foreach($this->tables as $this->table) {
- $this->table = trim($this->table);
- $this->classname = $class_prefix.preg_replace('/[^A-Z0-9]/i','_',ucfirst($this->table));
- $i = '';
- $outfilename = "{$base}/".preg_replace('/[^A-Z0-9]/i','_',ucfirst($this->table)).".php";
- if (file_exists($outfilename))
- $i = implode('',file($outfilename));
- $out = $this->_generateClassTable($i);
- $this->debug( "writing $this->classname\n");
- $fh = fopen($outfilename, "w");
- fputs($fh,$out);
- fclose($fh);
- }
- //echo $out;
- }
-
- /**
- * class being extended (can be overridden by [DB_DataObject_Generator] extends=xxxx
- *
- * @var string
- * @access private
- */
- var $_extends = 'DB_DataObject';
-
- /**
- * line to use for require('DB/DataObject.php');
- *
- * @var string
- * @access private
- */
- var $_extendsFile = "DB/DataObject.php";
-
- /**
- * class being generated
- *
- * @var string
- * @access private
- */
- var $_className;
-
- /**
- * The table class geneation part - single file.
- *
- * @access private
- * @return none
- */
- function _generateClassTable($input = '')
- {
- // title = expand me!
- $foot = "";
- $head = "<?php\n/**\n * Table Definition for {$this->table}\n */\n";
- // requires
- $head .= "require_once '{$this->_extendsFile}';\n\n";
- // add dummy class header in...
- // class
- $head .= "class {$this->classname} extends {$this->_extends} \n{";
-
- $body = "\n ###START_AUTOCODE\n";
- $body .= " /* the code below is auto generated do not remove the above tag */\n\n";
- // table
- $padding = (30 - strlen($this->table));
- if ($padding < 2) $padding =2;
- $p = str_repeat(' ',$padding) ;
- $body .= " var \$__table = '{$this->table}'; {$p}// table name\n";
-
-
- // if we are using the option database_{databasename} = dsn
- // then we should add var $_database = here
- // as database names may not always match..
- $options = &PEAR::getStaticProperty('DB_DataObject','options');
- if (isset($options["database_{$this->_database}"])) {
- $body .= " var \$_database = '{$this->_database}'; {$p}// database name (used with database_{*} config)\n";
- }
-
-
-
-
- $defs = $this->_definitions[$this->table];
-
- // show nice information!
- $connections = array();
- $sets = array();
- foreach($defs as $t) {
- if (!strlen(trim($t->name))) {
- continue;
- }
- $padding = (30 - strlen($t->name));
- if ($padding < 2) $padding =2;
- $p = str_repeat(' ',$padding) ;
- $body .=" var \${$t->name}; {$p}// {$t->type}({$t->len}) {$t->flags}\n";
- // can not do set as PEAR::DB table info doesnt support it.
- //if (substr($t->Type,0,3) == "set")
- // $sets[$t->Field] = "array".substr($t->Type,3);
- $body .= $this->derivedHookVar($t,$padding);
- }
-
- // THIS IS TOTALLY BORKED old FC creation
- // IT WILL BE REMOVED!!!!! in DataObjects 1.6
- // grep -r __clone * to find all it's uses
- // and replace them with $x = clone($y);
- // due to the change in the PHP5 clone design.
-
- if ( substr(phpversion(),0,1) < 5) {
- $body .= "\n";
- $body .= " /* ZE2 compatibility trick*/\n";
- $body .= " function __clone() { return \$this;}\n";
- }
-
- // simple creation tools ! (static stuff!)
- $body .= "\n";
- $body .= " /* Static get */\n";
- $body .= " function staticGet(\$k,\$v=NULL) { return DB_DataObject::staticGet('{$this->classname}',\$k,\$v); }\n";
-
- /*
- theoretically there is scope here to introduce 'list' methods
- based up 'xxxx_up' column!!! for heiracitcal trees..
- */
-
- // set methods
- //foreach ($sets as $k=>$v) {
- // $kk = strtoupper($k);
- // $body .=" function getSets{$k}() { return {$v}; }\n";
- //}
- $body .= $this->derivedHookFunctions();
-
- $body .= "\n /* the code above is auto generated do not remove the tag below */";
- $body .= "\n ###END_AUTOCODE\n";
-
- $foot .= "}\n";
- $full = $head . $body . $foot;
-
- if (!$input) {
- return $full;
- }
- if (!preg_match('/(\n|\r\n)\s*###START_AUTOCODE(\n|\r\n)/s',$input)) {
- return $full;
- }
- if (!preg_match('/(\n|\r\n)\s*###END_AUTOCODE(\n|\r\n)/s',$input)) {
- return $full;
- }
-
-
- /* this will only replace extends DB_DataObject by default,
- unless use set generator_class_rewrite to ANY or a name*/
-
- $class_rewrite = 'DB_DataObject';
- $options = &PEAR::getStaticProperty('DB_DataObject','options');
- if (!($class_rewrite = @$options['generator_class_rewrite'])) {
- $class_rewrite = 'DB_DataObject';
- }
- if ($class_rewrite == 'ANY') {
- $class_rewrite = '[a-z_]+';
- }
-
- $input = preg_replace(
- '/(\n|\r\n)class\s*[a-z0-9_]+\s*extends\s*' .$class_rewrite . '\s*\{(\n|\r\n)/si',
- "\nclass {$this->classname} extends {$this->_extends} \n{\n",
- $input);
-
- return preg_replace(
- '/(\n|\r\n)\s*###START_AUTOCODE(\n|\r\n).*(\n|\r\n)\s*###END_AUTOCODE(\n|\r\n)/s',
- $body,$input);
- }
-
- /**
- * hook to add extra methods to all classes
- *
- * called once for each class, use with $this->table and
- * $this->_definitions[$this->table], to get data out of the current table,
- * use it to add extra methods to the default classes.
- *
- * @access public
- * @return string added to class eg. functions.
- */
- function derivedHookFunctions()
- {
- // This is so derived generator classes can generate functions
- // It MUST NOT be changed here!!!
- return "";
- }
-
- /**
- * hook for var lines
- * called each time a var line is generated, override to add extra var
- * lines
- *
- * @param object t containing type,len,flags etc. from tableInfo call
- * @param int padding number of spaces
- * @access public
- * @return string added to class eg. functions.
- */
- function derivedHookVar(&$t,$padding)
- {
- // This is so derived generator classes can generate variabels
- // It MUST NOT be changed here!!!
- return "";
- }
-
-
- /**
- * getProxyFull - create a class definition on the fly and instantate it..
- *
- * similar to generated files - but also evals the class definitoin code.
- *
- *
- * @param string database name
- * @param string table name of table to create proxy for.
- *
- *
- * @return object Instance of class. or PEAR Error
- * @access public
- */
- function getProxyFull($database,$table) {
-
- if ($err = $this->fillTableSchema($database,$table)) {
- return $err;
- }
-
-
- $options = &PEAR::getStaticProperty('DB_DataObject','options');
- $class_prefix = $options['class_prefix'];
-
- if ($extends = @$options['extends']) {
- $this->_extends = $extends;
- $this->_extendsFile = $options['extends_location'];
- }
-
-
- $classname = $this->classname = $class_prefix.preg_replace('/[^A-Z0-9]/i','_',ucfirst(trim($this->table)));
-
- $out = $this->_generateClassTable();
- //echo $out;
- eval('?>'.$out);
- return new $classname;
-
- }
-
- /**
- * fillTableSchema - set the database schema on the fly
- *
- *
- *
- * @param string database name
- * @param string table name of table to create schema info for
- *
- * @return none | PEAR::error()
- * @access public
- */
- function fillTableSchema($database,$table) {
- global $_DB_DATAOBJECT;
- $this->_database = $database;
- $this->_connect();
- $table = trim($table);
-
- $__DB= &$GLOBALS['_DB_DATAOBJECT']['CONNECTIONS'][$this->_database_dsn_md5];
-
- $defs = $__DB->tableInfo($table);
- if (PEAR::isError($defs)) {
- return $defs;
- }
- if (@$_DB_DATAOBJECT['CONFIG']['debug'] > 2) {
- $this->debug("getting def for $database/$table",'fillTable');
- $this->debug(print_r($defs,true),'defs');
- }
- // cast all definitions to objects - as we deal with that better.
-
-
- foreach($defs as $def) {
- if (is_array($def)) {
- $this->_definitions[$table][] = (object) $def;
- }
- }
-
- $this->table = trim($table);
- $ret = $this->_generateDefinitionsTable();
-
- $_DB_DATAOBJECT['INI'][$database][$table] = $ret['table'];
- $_DB_DATAOBJECT['INI'][$database][$table.'__keys'] = $ret['keys'];
- return false;
-
- }
-
-
-
-}
+++ /dev/null
-#!/usr/bin/php -q
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Alan Knowles <alan@akbkhome.com>
-// +----------------------------------------------------------------------+
-//
-// $Id: createTables.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
-//
-define('DB_DATAOBJECT_NO_OVERLOAD', 0);
-require_once 'DB/DataObject/Generator.php';
-
-if (!ini_get('register_argc_argv')) {
- PEAR::raiseError("\nERROR: You must turn register_argc_argv On in you php.ini file for this to work\neg.\n\nregister_argc_argv = On\n\n", null, PEAR_ERROR_DIE);
- exit;
-}
-
-if (!@$_SERVER['argv'][1]) {
- PEAR::raiseError("\nERROR: createTable.php usage:\n\nC:\php\pear\DB\DataObjects\createTable.php example.ini\n\n", null, PEAR_ERROR_DIE);
- exit;
-}
-
-$config = parse_ini_file($_SERVER['argv'][1], true);
-
-$options = &PEAR::getStaticProperty('DB_DataObject','options');
-$options = $config['DB_DataObject'];
-
-if (!$options) {
- PEAR::raiseError("\nERROR: could not read ini file\n\n", null, PEAR_ERROR_DIE);
- exit;
-}
-set_time_limit(0);
-DB_DataObject::debugLevel(1);
-$generator = new DB_DataObject_Generator;
-$generator->start();
-
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 foldmethod=marker: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Stig Bakken <ssb@php.net> |
-// | Tomas V.V.Cox <cox@idecnet.com> |
-// | Maintainer: Daniel Convissor <danielc@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: common.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
-
-require_once 'PEAR.php';
-
-/**
- * DB_common is a base class for DB implementations, and must be
- * inherited by all such
- *
- * @package DB
- * @version $Id: common.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
- * @category Database
- * @author Stig Bakken <ssb@php.net>
- * @author Tomas V.V.Cox <cox@idecnet.com>
- */
-class DB_common extends PEAR
-{
- // {{{ properties
-
- /**
- * assoc of capabilities for this DB implementation
- * $features['limit'] => 'emulate' => emulate with fetch row by number
- * 'alter' => alter the query
- * false => skip rows
- * @var array
- */
- var $features = array();
-
- /**
- * assoc mapping native error codes to DB ones
- * @var array
- */
- var $errorcode_map = array();
-
- /**
- * DB type (mysql, oci8, odbc etc.)
- * @var string
- */
- var $phptype;
-
- /**
- * @var string
- */
- var $prepare_tokens;
-
- /**
- * @var string
- */
- var $prepare_types;
-
- /**
- * @var string
- */
- var $prepared_queries;
-
- /**
- * @var integer
- */
- var $prepare_maxstmt = 0;
-
- /**
- * @var string
- */
- var $last_query = '';
-
- /**
- * @var integer
- */
- var $fetchmode = DB_FETCHMODE_ORDERED;
-
- /**
- * @var string
- */
- var $fetchmode_object_class = 'stdClass';
-
- /**
- * Run-time configuration options.
- *
- * The 'optimize' option has been deprecated. Use the 'portability'
- * option instead.
- *
- * @see DB_common::setOption()
- * @var array
- */
- var $options = array(
- 'persistent' => false,
- 'ssl' => false,
- 'debug' => 0,
- 'seqname_format' => '%s_seq',
- 'autofree' => false,
- 'portability' => DB_PORTABILITY_NONE,
- 'optimize' => 'performance', // Deprecated. Use 'portability'.
- );
-
- /**
- * DB handle
- * @var resource
- */
- var $dbh;
-
- // }}}
- // {{{ toString()
-
- /**
- * String conversation
- *
- * @return string
- * @access private
- */
- function toString()
- {
- $info = strtolower(get_class($this));
- $info .= ': (phptype=' . $this->phptype .
- ', dbsyntax=' . $this->dbsyntax .
- ')';
-
- if ($this->connection) {
- $info .= ' [connected]';
- }
-
- return $info;
- }
-
- // }}}
- // {{{ constructor
-
- /**
- * Constructor
- */
- function DB_common()
- {
- $this->PEAR('DB_Error');
- }
-
- // }}}
- // {{{ quoteString()
-
- /**
- * DEPRECATED: Quotes a string so it can be safely used within string
- * delimiters in a query
- *
- * @return string quoted string
- *
- * @see DB_common::quoteSmart(), DB_common::escapeSimple()
- * @deprecated Deprecated in release 1.2 or lower
- * @internal
- */
- function quoteString($string)
- {
- $string = $this->quote($string);
- if ($string{0} == "'") {
- return substr($string, 1, -1);
- }
- return $string;
- }
-
- // }}}
- // {{{ quote()
-
- /**
- * DEPRECATED: Quotes a string so it can be safely used in a query
- *
- * @param string $string the input string to quote
- *
- * @return string The NULL string or the string quotes
- * in magic_quote_sybase style
- *
- * @see DB_common::quoteSmart(), DB_common::escapeSimple()
- * @deprecated Deprecated in release 1.6.0
- * @internal
- */
- function quote($string = null)
- {
- return ($string === null) ? 'NULL' : "'".str_replace("'", "''", $string)."'";
- }
-
- // }}}
- // {{{ quoteIdentifier()
-
- /**
- * Quote a string so it can be safely used as a table or column name
- *
- * Delimiting style depends on which database driver is being used.
- *
- * NOTE: just because you CAN use delimited identifiers doesn't mean
- * you SHOULD use them. In general, they end up causing way more
- * problems than they solve.
- *
- * Portability is broken by using the following characters inside
- * delimited identifiers:
- * + backtick (<kbd>`</kbd>) -- due to MySQL
- * + double quote (<kbd>"</kbd>) -- due to Oracle
- * + brackets (<kbd>[</kbd> or <kbd>]</kbd>) -- due to Access
- *
- * Delimited identifiers are known to generally work correctly under
- * the following drivers:
- * + mssql
- * + mysql
- * + mysqli
- * + oci8
- * + odbc(access)
- * + odbc(db2)
- * + pgsql
- * + sqlite
- * + sybase
- *
- * InterBase doesn't seem to be able to use delimited identifiers
- * via PHP 4. They work fine under PHP 5.
- *
- * @param string $str identifier name to be quoted
- *
- * @return string quoted identifier string
- *
- * @since 1.6.0
- * @access public
- */
- function quoteIdentifier($str)
- {
- return '"' . str_replace('"', '""', $str) . '"';
- }
-
- // }}}
- // {{{ quoteSmart()
-
- /**
- * Format input so it can be safely used in a query
- *
- * The output depends on the PHP data type of input and the database
- * type being used.
- *
- * @param mixed $in data to be quoted
- *
- * @return mixed the format of the results depends on the input's
- * PHP type:
- *
- * <ul>
- * <li>
- * <kbd>input</kbd> -> <samp>returns</samp>
- * </li>
- * <li>
- * <kbd>null</kbd> -> the string <samp>NULL</samp>
- * </li>
- * <li>
- * <kbd>integer</kbd> or <kbd>double</kbd> -> the unquoted number
- * </li>
- * <li>
- * &type.bool; -> output depends on the driver in use
- * Most drivers return integers: <samp>1</samp> if
- * <kbd>true</kbd> or <samp>0</samp> if
- * <kbd>false</kbd>.
- * Some return strings: <samp>TRUE</samp> if
- * <kbd>true</kbd> or <samp>FALSE</samp> if
- * <kbd>false</kbd>.
- * Finally one returns strings: <samp>T</samp> if
- * <kbd>true</kbd> or <samp>F</samp> if
- * <kbd>false</kbd>. Here is a list of each DBMS,
- * the values returned and the suggested column type:
- * <ul>
- * <li>
- * <kbd>dbase</kbd> -> <samp>T/F</samp>
- * (<kbd>Logical</kbd>)
- * </li>
- * <li>
- * <kbd>fbase</kbd> -> <samp>TRUE/FALSE</samp>
- * (<kbd>BOOLEAN</kbd>)
- * </li>
- * <li>
- * <kbd>ibase</kbd> -> <samp>1/0</samp>
- * (<kbd>SMALLINT</kbd>) [1]
- * </li>
- * <li>
- * <kbd>ifx</kbd> -> <samp>1/0</samp>
- * (<kbd>SMALLINT</kbd>) [1]
- * </li>
- * <li>
- * <kbd>msql</kbd> -> <samp>1/0</samp>
- * (<kbd>INTEGER</kbd>)
- * </li>
- * <li>
- * <kbd>mssql</kbd> -> <samp>1/0</samp>
- * (<kbd>BIT</kbd>)
- * </li>
- * <li>
- * <kbd>mysql</kbd> -> <samp>1/0</samp>
- * (<kbd>TINYINT(1)</kbd>)
- * </li>
- * <li>
- * <kbd>mysqli</kbd> -> <samp>1/0</samp>
- * (<kbd>TINYINT(1)</kbd>)
- * </li>
- * <li>
- * <kbd>oci8</kbd> -> <samp>1/0</samp>
- * (<kbd>NUMBER(1)</kbd>)
- * </li>
- * <li>
- * <kbd>odbc</kbd> -> <samp>1/0</samp>
- * (<kbd>SMALLINT</kbd>) [1]
- * </li>
- * <li>
- * <kbd>pgsql</kbd> -> <samp>TRUE/FALSE</samp>
- * (<kbd>BOOLEAN</kbd>)
- * </li>
- * <li>
- * <kbd>sqlite</kbd> -> <samp>1/0</samp>
- * (<kbd>INTEGER</kbd>)
- * </li>
- * <li>
- * <kbd>sybase</kbd> -> <samp>1/0</samp>
- * (<kbd>TINYINT(1)</kbd>)
- * </li>
- * </ul>
- * [1] Accommodate the lowest common denominator because not all
- * versions of have <kbd>BOOLEAN</kbd>.
- * </li>
- * <li>
- * other (including strings and numeric strings) ->
- * the data with single quotes escaped by preceeding
- * single quotes, backslashes are escaped by preceeding
- * backslashes, then the whole string is encapsulated
- * between single quotes
- * </li>
- * </ul>
- *
- * @since 1.6.0
- * @see DB_common::escapeSimple()
- * @access public
- */
- function quoteSmart($in)
- {
- if (is_int($in) || is_double($in)) {
- return $in;
- } elseif (is_bool($in)) {
- return $in ? 1 : 0;
- } elseif (is_null($in)) {
- return 'NULL';
- } else {
- return "'" . $this->escapeSimple($in) . "'";
- }
- }
-
- // }}}
- // {{{ escapeSimple()
-
- /**
- * Escape a string according to the current DBMS's standards
- *
- * In SQLite, this makes things safe for inserts/updates, but may
- * cause problems when performing text comparisons against columns
- * containing binary data. See the
- * {@link http://php.net/sqlite_escape_string PHP manual} for more info.
- *
- * @param string $str the string to be escaped
- *
- * @return string the escaped string
- *
- * @since 1.6.0
- * @see DB_common::quoteSmart()
- * @access public
- */
- function escapeSimple($str) {
- return str_replace("'", "''", $str);
- }
-
- // }}}
- // {{{ provides()
-
- /**
- * Tell whether a DB implementation or its backend extension
- * supports a given feature
- *
- * @param array $feature name of the feature (see the DB class doc)
- * @return bool whether this DB implementation supports $feature
- * @access public
- */
- function provides($feature)
- {
- return $this->features[$feature];
- }
-
- // }}}
- // {{{ errorCode()
-
- /**
- * Map native error codes to DB's portable ones
- *
- * Requires that the DB implementation's constructor fills
- * in the <var>$errorcode_map</var> property.
- *
- * @param mixed $nativecode the native error code, as returned by the
- * backend database extension (string or integer)
- *
- * @return int a portable DB error code, or DB_ERROR if this DB
- * implementation has no mapping for the given error code.
- *
- * @access public
- */
- function errorCode($nativecode)
- {
- if (isset($this->errorcode_map[$nativecode])) {
- return $this->errorcode_map[$nativecode];
- }
- // Fall back to DB_ERROR if there was no mapping.
- return DB_ERROR;
- }
-
- // }}}
- // {{{ errorMessage()
-
- /**
- * Map a DB error code to a textual message. This is actually
- * just a wrapper for DB::errorMessage()
- *
- * @param integer $dbcode the DB error code
- *
- * @return string the corresponding error message, of false
- * if the error code was unknown
- *
- * @access public
- */
- function errorMessage($dbcode)
- {
- return DB::errorMessage($this->errorcode_map[$dbcode]);
- }
-
- // }}}
- // {{{ raiseError()
-
- /**
- * Communicate an error and invoke error callbacks, etc
- *
- * Basically a wrapper for PEAR::raiseError without the message string.
- *
- * @param mixed integer error code, or a PEAR error object (all
- * other parameters are ignored if this parameter is
- * an object
- *
- * @param int error mode, see PEAR_Error docs
- *
- * @param mixed If error mode is PEAR_ERROR_TRIGGER, this is the
- * error level (E_USER_NOTICE etc). If error mode is
- * PEAR_ERROR_CALLBACK, this is the callback function,
- * either as a function name, or as an array of an
- * object and method name. For other error modes this
- * parameter is ignored.
- *
- * @param string Extra debug information. Defaults to the last
- * query and native error code.
- *
- * @param mixed Native error code, integer or string depending the
- * backend.
- *
- * @return object a PEAR error object
- *
- * @access public
- * @see PEAR_Error
- */
- function &raiseError($code = DB_ERROR, $mode = null, $options = null,
- $userinfo = null, $nativecode = null)
- {
- // The error is yet a DB error object
- if (is_object($code)) {
- // because we the static PEAR::raiseError, our global
- // handler should be used if it is set
- if ($mode === null && !empty($this->_default_error_mode)) {
- $mode = $this->_default_error_mode;
- $options = $this->_default_error_options;
- }
- $tmp = PEAR::raiseError($code, null, $mode, $options, null, null, true);
- return $tmp;
- }
-
- if ($userinfo === null) {
- $userinfo = $this->last_query;
- }
-
- if ($nativecode) {
- $userinfo .= ' [nativecode=' . trim($nativecode) . ']';
- }
-
- $tmp = PEAR::raiseError(null, $code, $mode, $options, $userinfo,
- 'DB_Error', true);
- return $tmp;
- }
-
- // }}}
- // {{{ setFetchMode()
-
- /**
- * Sets which fetch mode should be used by default on queries
- * on this connection
- *
- * @param integer $fetchmode DB_FETCHMODE_ORDERED or
- * DB_FETCHMODE_ASSOC, possibly bit-wise OR'ed with
- * DB_FETCHMODE_FLIPPED.
- *
- * @param string $object_class The class of the object
- * to be returned by the fetch methods when
- * the DB_FETCHMODE_OBJECT mode is selected.
- * If no class is specified by default a cast
- * to object from the assoc array row will be done.
- * There is also the posibility to use and extend the
- * 'DB_row' class.
- *
- * @see DB_FETCHMODE_ORDERED
- * @see DB_FETCHMODE_ASSOC
- * @see DB_FETCHMODE_FLIPPED
- * @see DB_FETCHMODE_OBJECT
- * @see DB_row::DB_row()
- * @access public
- */
- function setFetchMode($fetchmode, $object_class = 'stdClass')
- {
- switch ($fetchmode) {
- case DB_FETCHMODE_OBJECT:
- $this->fetchmode_object_class = $object_class;
- case DB_FETCHMODE_ORDERED:
- case DB_FETCHMODE_ASSOC:
- $this->fetchmode = $fetchmode;
- break;
- default:
- return $this->raiseError('invalid fetchmode mode');
- }
- }
-
- // }}}
- // {{{ setOption()
-
- /**
- * Set run-time configuration options for PEAR DB
- *
- * Options, their data types, default values and description:
- * <ul>
- * <li>
- * <var>autofree</var> <kbd>boolean</kbd> = <samp>false</samp>
- * <br />should results be freed automatically when there are no
- * more rows?
- * </li><li>
- * <var>debug</var> <kbd>integer</kbd> = <samp>0</samp>
- * <br />debug level
- * </li><li>
- * <var>persistent</var> <kbd>boolean</kbd> = <samp>false</samp>
- * <br />should the connection be persistent?
- * </li><li>
- * <var>portability</var> <kbd>integer</kbd> = <samp>DB_PORTABILITY_NONE</samp>
- * <br />portability mode constant (see below)
- * </li><li>
- * <var>seqname_format</var> <kbd>string</kbd> = <samp>%s_seq</samp>
- * <br />the sprintf() format string used on sequence names. This
- * format is applied to sequence names passed to
- * createSequence(), nextID() and dropSequence().
- * </li><li>
- * <var>ssl</var> <kbd>boolean</kbd> = <samp>false</samp>
- * <br />use ssl to connect?
- * </li>
- * </ul>
- *
- * -----------------------------------------
- *
- * PORTABILITY MODES
- *
- * These modes are bitwised, so they can be combined using <kbd>|</kbd>
- * and removed using <kbd>^</kbd>. See the examples section below on how
- * to do this.
- *
- * <samp>DB_PORTABILITY_NONE</samp>
- * turn off all portability features
- *
- * This mode gets automatically turned on if the deprecated
- * <var>optimize</var> option gets set to <samp>performance</samp>.
- *
- *
- * <samp>DB_PORTABILITY_LOWERCASE</samp>
- * convert names of tables and fields to lower case when using
- * <kbd>get*()</kbd>, <kbd>fetch*()</kbd> and <kbd>tableInfo()</kbd>
- *
- * This mode gets automatically turned on in the following databases
- * if the deprecated option <var>optimize</var> gets set to
- * <samp>portability</samp>:
- * + oci8
- *
- *
- * <samp>DB_PORTABILITY_RTRIM</samp>
- * right trim the data output by <kbd>get*()</kbd> <kbd>fetch*()</kbd>
- *
- *
- * <samp>DB_PORTABILITY_DELETE_COUNT</samp>
- * force reporting the number of rows deleted
- *
- * Some DBMS's don't count the number of rows deleted when performing
- * simple <kbd>DELETE FROM tablename</kbd> queries. This portability
- * mode tricks such DBMS's into telling the count by adding
- * <samp>WHERE 1=1</samp> to the end of <kbd>DELETE</kbd> queries.
- *
- * This mode gets automatically turned on in the following databases
- * if the deprecated option <var>optimize</var> gets set to
- * <samp>portability</samp>:
- * + fbsql
- * + mysql
- * + mysqli
- * + sqlite
- *
- *
- * <samp>DB_PORTABILITY_NUMROWS</samp>
- * enable hack that makes <kbd>numRows()</kbd> work in Oracle
- *
- * This mode gets automatically turned on in the following databases
- * if the deprecated option <var>optimize</var> gets set to
- * <samp>portability</samp>:
- * + oci8
- *
- *
- * <samp>DB_PORTABILITY_ERRORS</samp>
- * makes certain error messages in certain drivers compatible
- * with those from other DBMS's
- *
- * + mysql, mysqli: change unique/primary key constraints
- * DB_ERROR_ALREADY_EXISTS -> DB_ERROR_CONSTRAINT
- *
- * + odbc(access): MS's ODBC driver reports 'no such field' as code
- * 07001, which means 'too few parameters.' When this option is on
- * that code gets mapped to DB_ERROR_NOSUCHFIELD.
- * DB_ERROR_MISMATCH -> DB_ERROR_NOSUCHFIELD
- *
- *
- * <samp>DB_PORTABILITY_NULL_TO_EMPTY</samp>
- * convert null values to empty strings in data output by get*() and
- * fetch*(). Needed because Oracle considers empty strings to be null,
- * while most other DBMS's know the difference between empty and null.
- *
- *
- * <samp>DB_PORTABILITY_ALL</samp>
- * turn on all portability features
- *
- * -----------------------------------------
- *
- * Example 1. Simple setOption() example
- * <code> <?php
- * $dbh->setOption('autofree', true);
- * ?></code>
- *
- * Example 2. Portability for lowercasing and trimming
- * <code> <?php
- * $dbh->setOption('portability',
- * DB_PORTABILITY_LOWERCASE | DB_PORTABILITY_RTRIM);
- * ?></code>
- *
- * Example 3. All portability options except trimming
- * <code> <?php
- * $dbh->setOption('portability',
- * DB_PORTABILITY_ALL ^ DB_PORTABILITY_RTRIM);
- * ?></code>
- *
- * @param string $option option name
- * @param mixed $value value for the option
- *
- * @return int DB_OK on success. DB_Error object on failure.
- *
- * @see DB_common::$options
- */
- function setOption($option, $value)
- {
- if (isset($this->options[$option])) {
- $this->options[$option] = $value;
-
- /*
- * Backwards compatibility check for the deprecated 'optimize'
- * option. Done here in case settings change after connecting.
- */
- if ($option == 'optimize') {
- if ($value == 'portability') {
- switch ($this->phptype) {
- case 'oci8':
- $this->options['portability'] =
- DB_PORTABILITY_LOWERCASE |
- DB_PORTABILITY_NUMROWS;
- break;
- case 'fbsql':
- case 'mysql':
- case 'mysqli':
- case 'sqlite':
- $this->options['portability'] =
- DB_PORTABILITY_DELETE_COUNT;
- break;
- }
- } else {
- $this->options['portability'] = DB_PORTABILITY_NONE;
- }
- }
-
- return DB_OK;
- }
- return $this->raiseError("unknown option $option");
- }
-
- // }}}
- // {{{ getOption()
-
- /**
- * Returns the value of an option
- *
- * @param string $option option name
- *
- * @return mixed the option value
- */
- function getOption($option)
- {
- if (isset($this->options[$option])) {
- return $this->options[$option];
- }
- return $this->raiseError("unknown option $option");
- }
-
- // }}}
- // {{{ prepare()
-
- /**
- * Prepares a query for multiple execution with execute()
- *
- * Creates a query that can be run multiple times. Each time it is run,
- * the placeholders, if any, will be replaced by the contents of
- * execute()'s $data argument.
- *
- * Three types of placeholders can be used:
- * + <kbd>?</kbd> scalar value (i.e. strings, integers). The system
- * will automatically quote and escape the data.
- * + <kbd>!</kbd> value is inserted 'as is'
- * + <kbd>&</kbd> requires a file name. The file's contents get
- * inserted into the query (i.e. saving binary
- * data in a db)
- *
- * Example 1.
- * <code> <?php
- * $sth = $dbh->prepare('INSERT INTO tbl (a, b, c) VALUES (?, !, &)');
- * $data = array(
- * "John's text",
- * "'it''s good'",
- * 'filename.txt'
- * );
- * $res = $dbh->execute($sth, $data);
- * ?></code>
- *
- * Use backslashes to escape placeholder characters if you don't want
- * them to be interpreted as placeholders:
- * <pre>
- * "UPDATE foo SET col=? WHERE col='over \& under'"
- * </pre>
- *
- * With some database backends, this is emulated.
- *
- * {@internal ibase and oci8 have their own prepare() methods.}}
- *
- * @param string $query query to be prepared
- *
- * @return mixed DB statement resource on success. DB_Error on failure.
- *
- * @see DB_common::execute()
- * @access public
- */
- function prepare($query)
- {
- $tokens = preg_split('/((?<!\\\)[&?!])/', $query, -1,
- PREG_SPLIT_DELIM_CAPTURE);
- $token = 0;
- $types = array();
- $newtokens = array();
-
- foreach ($tokens as $val) {
- switch ($val) {
- case '?':
- $types[$token++] = DB_PARAM_SCALAR;
- break;
- case '&':
- $types[$token++] = DB_PARAM_OPAQUE;
- break;
- case '!':
- $types[$token++] = DB_PARAM_MISC;
- break;
- default:
- $newtokens[] = preg_replace('/\\\([&?!])/', "\\1", $val);
- }
- }
-
- $this->prepare_tokens[] = &$newtokens;
- end($this->prepare_tokens);
-
- $k = key($this->prepare_tokens);
- $this->prepare_types[$k] = $types;
- $this->prepared_queries[$k] = implode(' ', $newtokens);
-
- return $k;
- }
-
- // }}}
- // {{{ autoPrepare()
-
- /**
- * Automaticaly generate an insert or update query and pass it to prepare()
- *
- * @param string $table name of the table
- * @param array $table_fields ordered array containing the fields names
- * @param int $mode type of query to make (DB_AUTOQUERY_INSERT or DB_AUTOQUERY_UPDATE)
- * @param string $where in case of update queries, this string will be put after the sql WHERE statement
- * @return resource handle for the query
- * @see DB_common::prepare(), DB_common::buildManipSQL()
- * @access public
- */
- function autoPrepare($table, $table_fields, $mode = DB_AUTOQUERY_INSERT, $where = false)
- {
- $query = $this->buildManipSQL($table, $table_fields, $mode, $where);
- return $this->prepare($query);
- }
-
- // }}}
- // {{{ autoExecute()
-
- /**
- * Automaticaly generate an insert or update query and call prepare()
- * and execute() with it
- *
- * @param string $table name of the table
- * @param array $fields_values assoc ($key=>$value) where $key is a field name and $value its value
- * @param int $mode type of query to make (DB_AUTOQUERY_INSERT or DB_AUTOQUERY_UPDATE)
- * @param string $where in case of update queries, this string will be put after the sql WHERE statement
- * @return mixed a new DB_Result or a DB_Error when fail
- * @see DB_common::autoPrepare(), DB_common::buildManipSQL()
- * @access public
- */
- function autoExecute($table, $fields_values, $mode = DB_AUTOQUERY_INSERT, $where = false)
- {
- $sth = $this->autoPrepare($table, array_keys($fields_values), $mode, $where);
- $ret =& $this->execute($sth, array_values($fields_values));
- $this->freePrepared($sth);
- return $ret;
-
- }
-
- // }}}
- // {{{ buildManipSQL()
-
- /**
- * Make automaticaly an sql query for prepare()
- *
- * Example : buildManipSQL('table_sql', array('field1', 'field2', 'field3'), DB_AUTOQUERY_INSERT)
- * will return the string : INSERT INTO table_sql (field1,field2,field3) VALUES (?,?,?)
- * NB : - This belongs more to a SQL Builder class, but this is a simple facility
- * - Be carefull ! If you don't give a $where param with an UPDATE query, all
- * the records of the table will be updated !
- *
- * @param string $table name of the table
- * @param array $table_fields ordered array containing the fields names
- * @param int $mode type of query to make (DB_AUTOQUERY_INSERT or DB_AUTOQUERY_UPDATE)
- * @param string $where in case of update queries, this string will be put after the sql WHERE statement
- * @return string sql query for prepare()
- * @access public
- */
- function buildManipSQL($table, $table_fields, $mode, $where = false)
- {
- if (count($table_fields) == 0) {
- $this->raiseError(DB_ERROR_NEED_MORE_DATA);
- }
- $first = true;
- switch ($mode) {
- case DB_AUTOQUERY_INSERT:
- $values = '';
- $names = '';
- foreach ($table_fields as $value) {
- if ($first) {
- $first = false;
- } else {
- $names .= ',';
- $values .= ',';
- }
- $names .= $value;
- $values .= '?';
- }
- return "INSERT INTO $table ($names) VALUES ($values)";
- case DB_AUTOQUERY_UPDATE:
- $set = '';
- foreach ($table_fields as $value) {
- if ($first) {
- $first = false;
- } else {
- $set .= ',';
- }
- $set .= "$value = ?";
- }
- $sql = "UPDATE $table SET $set";
- if ($where) {
- $sql .= " WHERE $where";
- }
- return $sql;
- default:
- $this->raiseError(DB_ERROR_SYNTAX);
- }
- }
-
- // }}}
- // {{{ execute()
-
- /**
- * Executes a DB statement prepared with prepare()
- *
- * Example 1.
- * <code> <?php
- * $sth = $dbh->prepare('INSERT INTO tbl (a, b, c) VALUES (?, !, &)');
- * $data = array(
- * "John's text",
- * "'it''s good'",
- * 'filename.txt'
- * );
- * $res =& $dbh->execute($sth, $data);
- * ?></code>
- *
- * @param resource $stmt a DB statement resource returned from prepare()
- * @param mixed $data array, string or numeric data to be used in
- * execution of the statement. Quantity of items
- * passed must match quantity of placeholders in
- * query: meaning 1 placeholder for non-array
- * parameters or 1 placeholder per array element.
- *
- * @return object a new DB_Result or a DB_Error when fail
- *
- * {@internal ibase and oci8 have their own execute() methods.}}
- *
- * @see DB_common::prepare()
- * @access public
- */
- function &execute($stmt, $data = array())
- {
- $realquery = $this->executeEmulateQuery($stmt, $data);
- if (DB::isError($realquery)) {
- return $realquery;
- }
- $result = $this->simpleQuery($realquery);
-
- if (DB::isError($result) || $result === DB_OK) {
- return $result;
- } else {
- $tmp =& new DB_result($this, $result);
- return $tmp;
- }
- }
-
- // }}}
- // {{{ executeEmulateQuery()
-
- /**
- * Emulates the execute statement, when not supported
- *
- * @param resource $stmt a DB statement resource returned from execute()
- * @param mixed $data array, string or numeric data to be used in
- * execution of the statement. Quantity of items
- * passed must match quantity of placeholders in
- * query: meaning 1 placeholder for non-array
- * parameters or 1 placeholder per array element.
- *
- * @return mixed a string containing the real query run when emulating
- * prepare/execute. A DB error code is returned on failure.
- *
- * @see DB_common::execute()
- * @access private
- */
- function executeEmulateQuery($stmt, $data = array())
- {
- if (!is_array($data)) {
- $data = array($data);
- }
-
- if (count($this->prepare_types[$stmt]) != count($data)) {
- $this->last_query = $this->prepared_queries[$stmt];
- return $this->raiseError(DB_ERROR_MISMATCH);
- }
-
- $realquery = $this->prepare_tokens[$stmt][0];
-
- $i = 0;
- foreach ($data as $value) {
- if ($this->prepare_types[$stmt][$i] == DB_PARAM_SCALAR) {
- $realquery .= $this->quoteSmart($value);
- } elseif ($this->prepare_types[$stmt][$i] == DB_PARAM_OPAQUE) {
- $fp = @fopen($value, 'rb');
- if (!$fp) {
- return $this->raiseError(DB_ERROR_ACCESS_VIOLATION);
- }
- $realquery .= $this->quoteSmart(fread($fp, filesize($value)));
- fclose($fp);
- } else {
- $realquery .= $value;
- }
-
- $realquery .= $this->prepare_tokens[$stmt][++$i];
- }
-
- return $realquery;
- }
-
- // }}}
- // {{{ executeMultiple()
-
- /**
- * This function does several execute() calls on the same
- * statement handle
- *
- * $data must be an array indexed numerically
- * from 0, one execute call is done for every "row" in the array.
- *
- * If an error occurs during execute(), executeMultiple() does not
- * execute the unfinished rows, but rather returns that error.
- *
- * @param resource $stmt query handle from prepare()
- * @param array $data numeric array containing the
- * data to insert into the query
- *
- * @return mixed DB_OK or DB_Error
- *
- * @see DB_common::prepare(), DB_common::execute()
- * @access public
- */
- function executeMultiple($stmt, $data)
- {
- foreach ($data as $value) {
- $res =& $this->execute($stmt, $value);
- if (DB::isError($res)) {
- return $res;
- }
- }
- return DB_OK;
- }
-
- // }}}
- // {{{ freePrepared()
-
- /**
- * Free the resource used in a prepared query
- *
- * @param $stmt The resurce returned by the prepare() function
- * @see DB_common::prepare()
- */
- function freePrepared($stmt)
- {
- // Free the internal prepared vars
- if (isset($this->prepare_tokens[$stmt])) {
- unset($this->prepare_tokens[$stmt]);
- unset($this->prepare_types[$stmt]);
- unset($this->prepared_queries[$stmt]);
- return true;
- }
- return false;
- }
-
- // }}}
- // {{{ modifyQuery()
-
- /**
- * This method is used by backends to alter queries for various
- * reasons
- *
- * It is defined here to assure that all implementations
- * have this method defined.
- *
- * @param string $query query to modify
- *
- * @return the new (modified) query
- *
- * @access private
- */
- function modifyQuery($query) {
- return $query;
- }
-
- // }}}
- // {{{ modifyLimitQuery()
-
- /**
- * This method is used by backends to alter limited queries
- *
- * @param string $query query to modify
- * @param integer $from the row to start to fetching
- * @param integer $count the numbers of rows to fetch
- *
- * @return the new (modified) query
- *
- * @access private
- */
- function modifyLimitQuery($query, $from, $count, $params = array())
- {
- return $query;
- }
-
- // }}}
- // {{{ query()
-
- /**
- * Send a query to the database and return any results with a
- * DB_result object
- *
- * The query string can be either a normal statement to be sent directly
- * to the server OR if <var>$params</var> are passed the query can have
- * placeholders and it will be passed through prepare() and execute().
- *
- * @param string $query the SQL query or the statement to prepare
- * @param mixed $params array, string or numeric data to be used in
- * execution of the statement. Quantity of items
- * passed must match quantity of placeholders in
- * query: meaning 1 placeholder for non-array
- * parameters or 1 placeholder per array element.
- *
- * @return mixed a DB_result object or DB_OK on success, a DB
- * error on failure
- *
- * @see DB_result, DB_common::prepare(), DB_common::execute()
- * @access public
- */
- function &query($query, $params = array())
- {
- if (sizeof($params) > 0) {
- $sth = $this->prepare($query);
- if (DB::isError($sth)) {
- return $sth;
- }
- $ret =& $this->execute($sth, $params);
- $this->freePrepared($sth);
- return $ret;
- } else {
- $result = $this->simpleQuery($query);
- if (DB::isError($result) || $result === DB_OK) {
- return $result;
- } else {
- $tmp =& new DB_result($this, $result);
- return $tmp;
- }
- }
- }
-
- // }}}
- // {{{ limitQuery()
-
- /**
- * Generates a limited query
- *
- * @param string $query query
- * @param integer $from the row to start to fetching
- * @param integer $count the numbers of rows to fetch
- * @param array $params required for a statement
- *
- * @return mixed a DB_Result object, DB_OK or a DB_Error
- *
- * @access public
- */
- function &limitQuery($query, $from, $count, $params = array())
- {
- $query = $this->modifyLimitQuery($query, $from, $count, $params);
- if (DB::isError($query)){
- return $query;
- }
- $result =& $this->query($query, $params);
- if (is_a($result, 'DB_result')) {
- $result->setOption('limit_from', $from);
- $result->setOption('limit_count', $count);
- }
- return $result;
- }
-
- // }}}
- // {{{ getOne()
-
- /**
- * Fetch the first column of the first row of data returned from
- * a query
- *
- * Takes care of doing the query and freeing the results when finished.
- *
- * @param string $query the SQL query
- * @param mixed $params array, string or numeric data to be used in
- * execution of the statement. Quantity of items
- * passed must match quantity of placeholders in
- * query: meaning 1 placeholder for non-array
- * parameters or 1 placeholder per array element.
- *
- * @return mixed the returned value of the query. DB_Error on failure.
- *
- * @access public
- */
- function &getOne($query, $params = array())
- {
- settype($params, 'array');
- if (sizeof($params) > 0) {
- $sth = $this->prepare($query);
- if (DB::isError($sth)) {
- return $sth;
- }
- $res =& $this->execute($sth, $params);
- $this->freePrepared($sth);
- } else {
- $res =& $this->query($query);
- }
-
- if (DB::isError($res)) {
- return $res;
- }
-
- $err = $res->fetchInto($row, DB_FETCHMODE_ORDERED);
- $res->free();
-
- if ($err !== DB_OK) {
- return $err;
- }
-
- return $row[0];
- }
-
- // }}}
- // {{{ getRow()
-
- /**
- * Fetch the first row of data returned from a query
- *
- * Takes care of doing the query and freeing the results when finished.
- *
- * @param string $query the SQL query
- * @param array $params array to be used in execution of the statement.
- * Quantity of array elements must match quantity
- * of placeholders in query. This function does
- * NOT support scalars.
- * @param int $fetchmode the fetch mode to use
- *
- * @return array the first row of results as an array indexed from
- * 0, or a DB error code.
- *
- * @access public
- */
- function &getRow($query,
- $params = array(),
- $fetchmode = DB_FETCHMODE_DEFAULT)
- {
- // compat check, the params and fetchmode parameters used to
- // have the opposite order
- if (!is_array($params)) {
- if (is_array($fetchmode)) {
- if ($params === null) {
- $tmp = DB_FETCHMODE_DEFAULT;
- } else {
- $tmp = $params;
- }
- $params = $fetchmode;
- $fetchmode = $tmp;
- } elseif ($params !== null) {
- $fetchmode = $params;
- $params = array();
- }
- }
-
- if (sizeof($params) > 0) {
- $sth = $this->prepare($query);
- if (DB::isError($sth)) {
- return $sth;
- }
- $res =& $this->execute($sth, $params);
- $this->freePrepared($sth);
- } else {
- $res =& $this->query($query);
- }
-
- if (DB::isError($res)) {
- return $res;
- }
-
- $err = $res->fetchInto($row, $fetchmode);
-
- $res->free();
-
- if ($err !== DB_OK) {
- return $err;
- }
-
- return $row;
- }
-
- // }}}
- // {{{ getCol()
-
- /**
- * Fetch a single column from a result set and return it as an
- * indexed array
- *
- * @param string $query the SQL query
- * @param mixed $col which column to return (integer [column number,
- * starting at 0] or string [column name])
- * @param mixed $params array, string or numeric data to be used in
- * execution of the statement. Quantity of items
- * passed must match quantity of placeholders in
- * query: meaning 1 placeholder for non-array
- * parameters or 1 placeholder per array element.
- *
- * @return array an indexed array with the data from the first
- * row at index 0, or a DB error code
- *
- * @see DB_common::query()
- * @access public
- */
- function &getCol($query, $col = 0, $params = array())
- {
- settype($params, 'array');
- if (sizeof($params) > 0) {
- $sth = $this->prepare($query);
-
- if (DB::isError($sth)) {
- return $sth;
- }
-
- $res =& $this->execute($sth, $params);
- $this->freePrepared($sth);
- } else {
- $res =& $this->query($query);
- }
-
- if (DB::isError($res)) {
- return $res;
- }
-
- $fetchmode = is_int($col) ? DB_FETCHMODE_ORDERED : DB_FETCHMODE_ASSOC;
- $ret = array();
-
- while (is_array($row = $res->fetchRow($fetchmode))) {
- $ret[] = $row[$col];
- }
-
- $res->free();
-
- if (DB::isError($row)) {
- $ret = $row;
- }
-
- return $ret;
- }
-
- // }}}
- // {{{ getAssoc()
-
- /**
- * Fetch the entire result set of a query and return it as an
- * associative array using the first column as the key
- *
- * If the result set contains more than two columns, the value
- * will be an array of the values from column 2-n. If the result
- * set contains only two columns, the returned value will be a
- * scalar with the value of the second column (unless forced to an
- * array with the $force_array parameter). A DB error code is
- * returned on errors. If the result set contains fewer than two
- * columns, a DB_ERROR_TRUNCATED error is returned.
- *
- * For example, if the table "mytable" contains:
- *
- * <pre>
- * ID TEXT DATE
- * --------------------------------
- * 1 'one' 944679408
- * 2 'two' 944679408
- * 3 'three' 944679408
- * </pre>
- *
- * Then the call getAssoc('SELECT id,text FROM mytable') returns:
- * <pre>
- * array(
- * '1' => 'one',
- * '2' => 'two',
- * '3' => 'three',
- * )
- * </pre>
- *
- * ...while the call getAssoc('SELECT id,text,date FROM mytable') returns:
- * <pre>
- * array(
- * '1' => array('one', '944679408'),
- * '2' => array('two', '944679408'),
- * '3' => array('three', '944679408')
- * )
- * </pre>
- *
- * If the more than one row occurs with the same value in the
- * first column, the last row overwrites all previous ones by
- * default. Use the $group parameter if you don't want to
- * overwrite like this. Example:
- *
- * <pre>
- * getAssoc('SELECT category,id,name FROM mytable', false, null,
- * DB_FETCHMODE_ASSOC, true) returns:
- *
- * array(
- * '1' => array(array('id' => '4', 'name' => 'number four'),
- * array('id' => '6', 'name' => 'number six')
- * ),
- * '9' => array(array('id' => '4', 'name' => 'number four'),
- * array('id' => '6', 'name' => 'number six')
- * )
- * )
- * </pre>
- *
- * Keep in mind that database functions in PHP usually return string
- * values for results regardless of the database's internal type.
- *
- * @param string $query the SQL query
- * @param boolean $force_array used only when the query returns
- * exactly two columns. If true, the values
- * of the returned array will be one-element
- * arrays instead of scalars.
- * @param mixed $params array, string or numeric data to be used in
- * execution of the statement. Quantity of items
- * passed must match quantity of placeholders in
- * query: meaning 1 placeholder for non-array
- * parameters or 1 placeholder per array element.
- * @param boolean $group if true, the values of the returned array
- * is wrapped in another array. If the same
- * key value (in the first column) repeats
- * itself, the values will be appended to
- * this array instead of overwriting the
- * existing values.
- *
- * @return array associative array with results from the query.
- * DB Error on failure.
- *
- * @access public
- */
- function &getAssoc($query, $force_array = false, $params = array(),
- $fetchmode = DB_FETCHMODE_DEFAULT, $group = false)
- {
- settype($params, 'array');
- if (sizeof($params) > 0) {
- $sth = $this->prepare($query);
-
- if (DB::isError($sth)) {
- return $sth;
- }
-
- $res =& $this->execute($sth, $params);
- $this->freePrepared($sth);
- } else {
- $res =& $this->query($query);
- }
-
- if (DB::isError($res)) {
- return $res;
- }
- if ($fetchmode == DB_FETCHMODE_DEFAULT) {
- $fetchmode = $this->fetchmode;
- }
- $cols = $res->numCols();
-
- if ($cols < 2) {
- $tmp =& $this->raiseError(DB_ERROR_TRUNCATED);
- return $tmp;
- }
-
- $results = array();
-
- if ($cols > 2 || $force_array) {
- // return array values
- // XXX this part can be optimized
- if ($fetchmode == DB_FETCHMODE_ASSOC) {
- while (is_array($row = $res->fetchRow(DB_FETCHMODE_ASSOC))) {
- reset($row);
- $key = current($row);
- unset($row[key($row)]);
- if ($group) {
- $results[$key][] = $row;
- } else {
- $results[$key] = $row;
- }
- }
- } elseif ($fetchmode == DB_FETCHMODE_OBJECT) {
- while ($row = $res->fetchRow(DB_FETCHMODE_OBJECT)) {
- $arr = get_object_vars($row);
- $key = current($arr);
- if ($group) {
- $results[$key][] = $row;
- } else {
- $results[$key] = $row;
- }
- }
- } else {
- while (is_array($row = $res->fetchRow(DB_FETCHMODE_ORDERED))) {
- // we shift away the first element to get
- // indices running from 0 again
- $key = array_shift($row);
- if ($group) {
- $results[$key][] = $row;
- } else {
- $results[$key] = $row;
- }
- }
- }
- if (DB::isError($row)) {
- $results = $row;
- }
- } else {
- // return scalar values
- while (is_array($row = $res->fetchRow(DB_FETCHMODE_ORDERED))) {
- if ($group) {
- $results[$row[0]][] = $row[1];
- } else {
- $results[$row[0]] = $row[1];
- }
- }
- if (DB::isError($row)) {
- $results = $row;
- }
- }
-
- $res->free();
-
- return $results;
- }
-
- // }}}
- // {{{ getAll()
-
- /**
- * Fetch all the rows returned from a query
- *
- * @param string $query the SQL query
- * @param array $params array to be used in execution of the statement.
- * Quantity of array elements must match quantity
- * of placeholders in query. This function does
- * NOT support scalars.
- * @param int $fetchmode the fetch mode to use
- *
- * @return array an nested array. DB error on failure.
- *
- * @access public
- */
- function &getAll($query,
- $params = array(),
- $fetchmode = DB_FETCHMODE_DEFAULT)
- {
- // compat check, the params and fetchmode parameters used to
- // have the opposite order
- if (!is_array($params)) {
- if (is_array($fetchmode)) {
- if ($params === null) {
- $tmp = DB_FETCHMODE_DEFAULT;
- } else {
- $tmp = $params;
- }
- $params = $fetchmode;
- $fetchmode = $tmp;
- } elseif ($params !== null) {
- $fetchmode = $params;
- $params = array();
- }
- }
-
- if (sizeof($params) > 0) {
- $sth = $this->prepare($query);
-
- if (DB::isError($sth)) {
- return $sth;
- }
-
- $res =& $this->execute($sth, $params);
- $this->freePrepared($sth);
- } else {
- $res =& $this->query($query);
- }
-
- if (DB::isError($res) || $res === DB_OK) {
- return $res;
- }
-
- $results = array();
- while (DB_OK === $res->fetchInto($row, $fetchmode)) {
- if ($fetchmode & DB_FETCHMODE_FLIPPED) {
- foreach ($row as $key => $val) {
- $results[$key][] = $val;
- }
- } else {
- $results[] = $row;
- }
- }
-
- $res->free();
-
- if (DB::isError($row)) {
- $tmp =& $this->raiseError($row);
- return $tmp;
- }
- return $results;
- }
-
- // }}}
- // {{{ autoCommit()
-
- /**
- * enable automatic Commit
- *
- * @param boolean $onoff
- * @return mixed DB_Error
- *
- * @access public
- */
- function autoCommit($onoff=false)
- {
- return $this->raiseError(DB_ERROR_NOT_CAPABLE);
- }
-
- // }}}
- // {{{ commit()
-
- /**
- * starts a Commit
- *
- * @return mixed DB_Error
- *
- * @access public
- */
- function commit()
- {
- return $this->raiseError(DB_ERROR_NOT_CAPABLE);
- }
-
- // }}}
- // {{{ rollback()
-
- /**
- * starts a rollback
- *
- * @return mixed DB_Error
- *
- * @access public
- */
- function rollback()
- {
- return $this->raiseError(DB_ERROR_NOT_CAPABLE);
- }
-
- // }}}
- // {{{ numRows()
-
- /**
- * Returns the number of rows in a result object
- *
- * @param object DB_Result the result object to check
- *
- * @return mixed DB_Error or the number of rows
- *
- * @access public
- */
- function numRows($result)
- {
- return $this->raiseError(DB_ERROR_NOT_CAPABLE);
- }
-
- // }}}
- // {{{ affectedRows()
-
- /**
- * Returns the affected rows of a query
- *
- * @return mixed DB_Error or number of rows
- *
- * @access public
- */
- function affectedRows()
- {
- return $this->raiseError(DB_ERROR_NOT_CAPABLE);
- }
-
- // }}}
- // {{{ errorNative()
-
- /**
- * Returns an errormessage, provides by the database
- *
- * @return mixed DB_Error or message
- *
- * @access public
- */
- function errorNative()
- {
- return $this->raiseError(DB_ERROR_NOT_CAPABLE);
- }
-
- // }}}
- // {{{ getSequenceName()
-
- /**
- * Generate the name used inside the database for a sequence
- *
- * The createSequence() docblock contains notes about storing sequence
- * names.
- *
- * @param string $sqn the sequence's public name
- *
- * @return string the sequence's name in the backend
- *
- * @see DB_common::createSequence(), DB_common::dropSequence(),
- * DB_common::nextID(), DB_common::setOption()
- * @access private
- */
- function getSequenceName($sqn)
- {
- return sprintf($this->getOption('seqname_format'),
- preg_replace('/[^a-z0-9_.]/i', '_', $sqn));
- }
-
- // }}}
- // {{{ nextId()
-
- /**
- * Returns the next free id in a sequence
- *
- * @param string $seq_name name of the sequence
- * @param boolean $ondemand when true, the seqence is automatically
- * created if it does not exist
- *
- * @return int the next id number in the sequence. DB_Error if problem.
- *
- * @see DB_common::createSequence(), DB_common::dropSequence(),
- * DB_common::getSequenceName()
- * @access public
- */
- function nextId($seq_name, $ondemand = true)
- {
- return $this->raiseError(DB_ERROR_NOT_CAPABLE);
- }
-
- // }}}
- // {{{ createSequence()
-
- /**
- * Creates a new sequence
- *
- * The name of a given sequence is determined by passing the string
- * provided in the <var>$seq_name</var> argument through PHP's sprintf()
- * function using the value from the <var>seqname_format</var> option as
- * the sprintf()'s format argument.
- *
- * <var>seqname_format</var> is set via setOption().
- *
- * @param string $seq_name name of the new sequence
- *
- * @return int DB_OK on success. A DB_Error object is returned if
- * problems arise.
- *
- * @see DB_common::dropSequence(), DB_common::getSequenceName(),
- * DB_common::nextID()
- * @access public
- */
- function createSequence($seq_name)
- {
- return $this->raiseError(DB_ERROR_NOT_CAPABLE);
- }
-
- // }}}
- // {{{ dropSequence()
-
- /**
- * Deletes a sequence
- *
- * @param string $seq_name name of the sequence to be deleted
- *
- * @return int DB_OK on success. DB_Error if problems.
- *
- * @see DB_common::createSequence(), DB_common::getSequenceName(),
- * DB_common::nextID()
- * @access public
- */
- function dropSequence($seq_name)
- {
- return $this->raiseError(DB_ERROR_NOT_CAPABLE);
- }
-
- // }}}
- // {{{ tableInfo()
-
- /**
- * Returns information about a table or a result set
- *
- * The format of the resulting array depends on which <var>$mode</var>
- * you select. The sample output below is based on this query:
- * <pre>
- * SELECT tblFoo.fldID, tblFoo.fldPhone, tblBar.fldId
- * FROM tblFoo
- * JOIN tblBar ON tblFoo.fldId = tblBar.fldId
- * </pre>
- *
- * <ul>
- * <li>
- *
- * <kbd>null</kbd> (default)
- * <pre>
- * [0] => Array (
- * [table] => tblFoo
- * [name] => fldId
- * [type] => int
- * [len] => 11
- * [flags] => primary_key not_null
- * )
- * [1] => Array (
- * [table] => tblFoo
- * [name] => fldPhone
- * [type] => string
- * [len] => 20
- * [flags] =>
- * )
- * [2] => Array (
- * [table] => tblBar
- * [name] => fldId
- * [type] => int
- * [len] => 11
- * [flags] => primary_key not_null
- * )
- * </pre>
- *
- * </li><li>
- *
- * <kbd>DB_TABLEINFO_ORDER</kbd>
- *
- * <p>In addition to the information found in the default output,
- * a notation of the number of columns is provided by the
- * <samp>num_fields</samp> element while the <samp>order</samp>
- * element provides an array with the column names as the keys and
- * their location index number (corresponding to the keys in the
- * the default output) as the values.</p>
- *
- * <p>If a result set has identical field names, the last one is
- * used.</p>
- *
- * <pre>
- * [num_fields] => 3
- * [order] => Array (
- * [fldId] => 2
- * [fldTrans] => 1
- * )
- * </pre>
- *
- * </li><li>
- *
- * <kbd>DB_TABLEINFO_ORDERTABLE</kbd>
- *
- * <p>Similar to <kbd>DB_TABLEINFO_ORDER</kbd> but adds more
- * dimensions to the array in which the table names are keys and
- * the field names are sub-keys. This is helpful for queries that
- * join tables which have identical field names.</p>
- *
- * <pre>
- * [num_fields] => 3
- * [ordertable] => Array (
- * [tblFoo] => Array (
- * [fldId] => 0
- * [fldPhone] => 1
- * )
- * [tblBar] => Array (
- * [fldId] => 2
- * )
- * )
- * </pre>
- *
- * </li>
- * </ul>
- *
- * The <samp>flags</samp> element contains a space separated list
- * of extra information about the field. This data is inconsistent
- * between DBMS's due to the way each DBMS works.
- * + <samp>primary_key</samp>
- * + <samp>unique_key</samp>
- * + <samp>multiple_key</samp>
- * + <samp>not_null</samp>
- *
- * Most DBMS's only provide the <samp>table</samp> and <samp>flags</samp>
- * elements if <var>$result</var> is a table name. The following DBMS's
- * provide full information from queries:
- * + fbsql
- * + mysql
- *
- * If the 'portability' option has <samp>DB_PORTABILITY_LOWERCASE</samp>
- * turned on, the names of tables and fields will be lowercased.
- *
- * @param object|string $result DB_result object from a query or a
- * string containing the name of a table.
- * While this also accepts a query result
- * resource identifier, this behavior is
- * deprecated.
- * @param int $mode either unused or one of the tableInfo modes:
- * <kbd>DB_TABLEINFO_ORDERTABLE</kbd>,
- * <kbd>DB_TABLEINFO_ORDER</kbd> or
- * <kbd>DB_TABLEINFO_FULL</kbd> (which does both).
- * These are bitwise, so the first two can be
- * combined using <kbd>|</kbd>.
- * @return array an associative array with the information requested.
- * If something goes wrong an error object is returned.
- *
- * @see DB_common::setOption()
- * @access public
- */
- function tableInfo($result, $mode = null)
- {
- /*
- * If the DB_<driver> class has a tableInfo() method, that one
- * overrides this one. But, if the driver doesn't have one,
- * this method runs and tells users about that fact.
- */
- return $this->raiseError(DB_ERROR_NOT_CAPABLE);
- }
-
- // }}}
- // {{{ getTables()
-
- /**
- * @deprecated Deprecated in release 1.2 or lower
- */
- function getTables()
- {
- return $this->getListOf('tables');
- }
-
- // }}}
- // {{{ getListOf()
-
- /**
- * list internal DB info
- * valid values for $type are db dependent,
- * often: databases, users, view, functions
- *
- * @param string $type type of requested info
- *
- * @return mixed DB_Error or the requested data
- *
- * @access public
- */
- function getListOf($type)
- {
- $sql = $this->getSpecialQuery($type);
- if ($sql === null) { // No support
- return $this->raiseError(DB_ERROR_UNSUPPORTED);
- } elseif (is_int($sql) || DB::isError($sql)) { // Previous error
- return $this->raiseError($sql);
- } elseif (is_array($sql)) { // Already the result
- return $sql;
- }
- return $this->getCol($sql); // Launch this query
- }
-
- // }}}
- // {{{ getSpecialQuery()
-
- /**
- * Returns the query needed to get some backend info
- *
- * @param string $type What kind of info you want to retrieve
- *
- * @return string The SQL query string
- *
- * @access public
- */
- function getSpecialQuery($type)
- {
- return $this->raiseError(DB_ERROR_UNSUPPORTED);
- }
-
- // }}}
- // {{{ _rtrimArrayValues()
-
- /**
- * Right trim all strings in an array
- *
- * @param array $array the array to be trimmed (passed by reference)
- * @return void
- * @access private
- */
- function _rtrimArrayValues(&$array)
- {
- foreach ($array as $key => $value) {
- if (is_string($value)) {
- $array[$key] = rtrim($value);
- }
- }
- }
-
- // }}}
- // {{{ _convertNullArrayValuesToEmpty()
-
- /**
- * Convert all null values in an array to empty strings
- *
- * @param array $array the array to be de-nullified (passed by reference)
- * @return void
- * @access private
- */
- function _convertNullArrayValuesToEmpty(&$array)
- {
- foreach ($array as $key => $value) {
- if (is_null($value)) {
- $array[$key] = '';
- }
- }
- }
-
- // }}}
-}
-
-/*
- * Local variables:
- * tab-width: 4
- * c-basic-offset: 4
- * End:
- */
-
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 foldmethod=marker: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Tomas V.V.Cox <cox@idecnet.com> |
-// | Maintainer: Daniel Convissor <danielc@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: dbase.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
-
-
-// XXX legend:
-// You have to compile your PHP with the --enable-dbase option
-
-
-require_once 'DB/common.php';
-
-/**
- * Database independent query interface definition for PHP's dbase
- * extension.
- *
- * @package DB
- * @version $Id: dbase.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
- * @category Database
- * @author Stig Bakken <ssb@php.net>
- */
-class DB_dbase extends DB_common
-{
- // {{{ properties
-
- var $connection;
- var $phptype, $dbsyntax;
- var $prepare_tokens = array();
- var $prepare_types = array();
- var $res_row = array();
- var $result = 0;
-
- // }}}
- // {{{ constructor
-
- /**
- * DB_mysql constructor.
- *
- * @access public
- */
- function DB_dbase()
- {
- $this->DB_common();
- $this->phptype = 'dbase';
- $this->dbsyntax = 'dbase';
- $this->features = array(
- 'prepare' => false,
- 'pconnect' => false,
- 'transactions' => false,
- 'limit' => false
- );
- $this->errorcode_map = array();
- }
-
- // }}}
- // {{{ connect()
-
- function connect($dsninfo, $persistent = false)
- {
- if (!DB::assertExtension('dbase')) {
- return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
- }
- $this->dsn = $dsninfo;
- ob_start();
- $conn = @dbase_open($dsninfo['database'], 0);
- $error = ob_get_contents();
- ob_end_clean();
- if (!$conn) {
- return $this->raiseError(DB_ERROR_CONNECT_FAILED, null,
- null, null, strip_tags($error));
- }
- $this->connection = $conn;
- return DB_OK;
- }
-
- // }}}
- // {{{ disconnect()
-
- function disconnect()
- {
- $ret = @dbase_close($this->connection);
- $this->connection = null;
- return $ret;
- }
-
- // }}}
- // {{{ &query()
-
- function &query($query = null)
- {
- // emulate result resources
- $this->res_row[$this->result] = 0;
- $tmp =& new DB_result($this, $this->result++);
- return $tmp;
- }
-
- // }}}
- // {{{ fetchInto()
-
- /**
- * Fetch a row and insert the data into an existing array.
- *
- * Formating of the array and the data therein are configurable.
- * See DB_result::fetchInto() for more information.
- *
- * @param resource $result query result identifier
- * @param array $arr (reference) array where data from the row
- * should be placed
- * @param int $fetchmode how the resulting array should be indexed
- * @param int $rownum the row number to fetch
- *
- * @return mixed DB_OK on success, null when end of result set is
- * reached or on failure
- *
- * @see DB_result::fetchInto()
- * @access private
- */
- function fetchInto($result, &$arr, $fetchmode, $rownum=null)
- {
- if ($rownum === null) {
- $rownum = $this->res_row[$result]++;
- }
- if ($fetchmode & DB_FETCHMODE_ASSOC) {
- $arr = @dbase_get_record_with_names($this->connection, $rownum);
- if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE && $arr) {
- $arr = array_change_key_case($arr, CASE_LOWER);
- }
- } else {
- $arr = @dbase_get_record($this->connection, $rownum);
- }
- if (!$arr) {
- return null;
- }
- if ($this->options['portability'] & DB_PORTABILITY_RTRIM) {
- $this->_rtrimArrayValues($arr);
- }
- if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) {
- $this->_convertNullArrayValuesToEmpty($arr);
- }
- return DB_OK;
- }
-
- // }}}
- // {{{ numCols()
-
- function numCols($foo)
- {
- return @dbase_numfields($this->connection);
- }
-
- // }}}
- // {{{ numRows()
-
- function numRows($foo)
- {
- return @dbase_numrecords($this->connection);
- }
-
- // }}}
- // {{{ quoteSmart()
-
- /**
- * Format input so it can be safely used in a query
- *
- * @param mixed $in data to be quoted
- *
- * @return mixed Submitted variable's type = returned value:
- * + null = the string <samp>NULL</samp>
- * + boolean = <samp>T</samp> if true or
- * <samp>F</samp> if false. Use the <kbd>Logical</kbd>
- * data type.
- * + integer or double = the unquoted number
- * + other (including strings and numeric strings) =
- * the data with single quotes escaped by preceeding
- * single quotes then the whole string is encapsulated
- * between single quotes
- *
- * @internal
- */
- function quoteSmart($in)
- {
- if (is_int($in) || is_double($in)) {
- return $in;
- } elseif (is_bool($in)) {
- return $in ? 'T' : 'F';
- } elseif (is_null($in)) {
- return 'NULL';
- } else {
- return "'" . $this->escapeSimple($in) . "'";
- }
- }
-
- // }}}
-
-}
-
-/*
- * Local variables:
- * tab-width: 4
- * c-basic-offset: 4
- * End:
- */
-
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 foldmethod=marker: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Frank M. Kromann <frank@frontbase.com> |
-// | Maintainer: Daniel Convissor <danielc@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: fbsql.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
-
-
-// XXX legend:
-//
-// XXX ERRORMSG: The error message from the fbsql function should
-// be registered here.
-//
-// TODO/wishlist:
-// longReadlen
-// binmode
-
-
-require_once 'DB/common.php';
-
-/**
- * Database independent query interface definition for PHP's FrontBase
- * extension.
- *
- * @package DB
- * @version $Id: fbsql.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
- * @category Database
- * @author Frank M. Kromann <frank@frontbase.com>
- */
-class DB_fbsql extends DB_common
-{
- // {{{ properties
-
- var $connection;
- var $phptype, $dbsyntax;
- var $prepare_tokens = array();
- var $prepare_types = array();
- var $num_rows = array();
- var $fetchmode = DB_FETCHMODE_ORDERED; /* Default fetch mode */
-
- // }}}
- // {{{ constructor
-
- /**
- * DB_fbsql constructor.
- *
- * @access public
- */
- function DB_fbsql()
- {
- $this->DB_common();
- $this->phptype = 'fbsql';
- $this->dbsyntax = 'fbsql';
- $this->features = array(
- 'prepare' => false,
- 'pconnect' => true,
- 'transactions' => true,
- 'limit' => 'emulate'
- );
- $this->errorcode_map = array(
- 1004 => DB_ERROR_CANNOT_CREATE,
- 1005 => DB_ERROR_CANNOT_CREATE,
- 1006 => DB_ERROR_CANNOT_CREATE,
- 1007 => DB_ERROR_ALREADY_EXISTS,
- 1008 => DB_ERROR_CANNOT_DROP,
- 1046 => DB_ERROR_NODBSELECTED,
- 1050 => DB_ERROR_ALREADY_EXISTS,
- 1051 => DB_ERROR_NOSUCHTABLE,
- 1054 => DB_ERROR_NOSUCHFIELD,
- 1062 => DB_ERROR_ALREADY_EXISTS,
- 1064 => DB_ERROR_SYNTAX,
- 1100 => DB_ERROR_NOT_LOCKED,
- 1136 => DB_ERROR_VALUE_COUNT_ON_ROW,
- 1146 => DB_ERROR_NOSUCHTABLE,
- );
- }
-
- // }}}
- // {{{ connect()
-
- /**
- * Connect to a database and log in as the specified user.
- *
- * @param $dsn the data source name (see DB::parseDSN for syntax)
- * @param $persistent (optional) whether the connection should
- * be persistent
- * @access public
- * @return int DB_OK on success, a DB error on failure
- */
- function connect($dsninfo, $persistent = false)
- {
- if (!DB::assertExtension('fbsql')) {
- return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
- }
-
- $this->dsn = $dsninfo;
- $dbhost = $dsninfo['hostspec'] ? $dsninfo['hostspec'] : 'localhost';
-
- $php_errormsg = '';
- $connect_function = $persistent ? 'fbsql_pconnect' : 'fbsql_connect';
-
- if ($dbhost && $dsninfo['username'] && $dsninfo['password']) {
- $conn = @$connect_function($dbhost, $dsninfo['username'],
- $dsninfo['password']);
- } elseif ($dbhost && $dsninfo['username']) {
- $conn = @$connect_function($dbhost, $dsninfo['username']);
- } elseif ($dbhost) {
- $conn = @$connect_function($dbhost);
- } else {
- $conn = false;
- }
- if (!$conn) {
- if (empty($php_errormsg)) {
- return $this->raiseError(DB_ERROR_CONNECT_FAILED);
- } else {
- return $this->raiseError(DB_ERROR_CONNECT_FAILED, null, null,
- null, $php_errormsg);
- }
- }
-
- if ($dsninfo['database']) {
- if (!fbsql_select_db($dsninfo['database'], $conn)) {
- return $this->fbsqlRaiseError();
- }
- }
-
- $this->connection = $conn;
- return DB_OK;
- }
-
- // }}}
- // {{{ disconnect()
-
- /**
- * Log out and disconnect from the database.
- *
- * @access public
- *
- * @return bool true on success, false if not connected.
- */
- function disconnect()
- {
- $ret = @fbsql_close($this->connection);
- $this->connection = null;
- return $ret;
- }
-
- // }}}
- // {{{ simpleQuery()
-
- /**
- * Send a query to fbsql and return the results as a fbsql resource
- * identifier.
- *
- * @param the SQL query
- *
- * @access public
- *
- * @return mixed returns a valid fbsql result for successful SELECT
- * queries, DB_OK for other successful queries. A DB error is
- * returned on failure.
- */
- function simpleQuery($query)
- {
- $this->last_query = $query;
- $query = $this->modifyQuery($query);
- $result = @fbsql_query("$query;", $this->connection);
- if (!$result) {
- return $this->fbsqlRaiseError();
- }
- // Determine which queries that should return data, and which
- // should return an error code only.
- if (DB::isManip($query)) {
- return DB_OK;
- }
- $numrows = $this->numrows($result);
- if (is_object($numrows)) {
- return $numrows;
- }
- $this->num_rows[$result] = $numrows;
- return $result;
- }
-
- // }}}
- // {{{ nextResult()
-
- /**
- * Move the internal fbsql result pointer to the next available result
- *
- * @param a valid fbsql result resource
- *
- * @access public
- *
- * @return true if a result is available otherwise return false
- */
- function nextResult($result)
- {
- return @fbsql_next_result($result);
- }
-
- // }}}
- // {{{ fetchInto()
-
- /**
- * Fetch a row and insert the data into an existing array.
- *
- * Formating of the array and the data therein are configurable.
- * See DB_result::fetchInto() for more information.
- *
- * @param resource $result query result identifier
- * @param array $arr (reference) array where data from the row
- * should be placed
- * @param int $fetchmode how the resulting array should be indexed
- * @param int $rownum the row number to fetch
- *
- * @return mixed DB_OK on success, null when end of result set is
- * reached or on failure
- *
- * @see DB_result::fetchInto()
- * @access private
- */
- function fetchInto($result, &$arr, $fetchmode, $rownum=null)
- {
- if ($rownum !== null) {
- if (!@fbsql_data_seek($result, $rownum)) {
- return null;
- }
- }
- if ($fetchmode & DB_FETCHMODE_ASSOC) {
- $arr = @fbsql_fetch_array($result, FBSQL_ASSOC);
- if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE && $arr) {
- $arr = array_change_key_case($arr, CASE_LOWER);
- }
- } else {
- $arr = @fbsql_fetch_row($result);
- }
- if (!$arr) {
- $errno = @fbsql_errno($this->connection);
- if (!$errno) {
- return null;
- }
- return $this->fbsqlRaiseError($errno);
- }
- if ($this->options['portability'] & DB_PORTABILITY_RTRIM) {
- $this->_rtrimArrayValues($arr);
- }
- if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) {
- $this->_convertNullArrayValuesToEmpty($arr);
- }
- return DB_OK;
- }
-
- // }}}
- // {{{ freeResult()
-
- /**
- * Free the internal resources associated with $result.
- *
- * @param $result fbsql result identifier
- *
- * @access public
- *
- * @return bool true on success, false if $result is invalid
- */
- function freeResult($result)
- {
- return @fbsql_free_result($result);
- }
-
- // }}}
- // {{{ autoCommit()
-
- function autoCommit($onoff=false)
- {
- if ($onoff) {
- $this->query("SET COMMIT TRUE");
- } else {
- $this->query("SET COMMIT FALSE");
- }
- }
-
- // }}}
- // {{{ commit()
-
- function commit()
- {
- @fbsql_commit();
- }
-
- // }}}
- // {{{ rollback()
-
- function rollback()
- {
- @fbsql_rollback();
- }
-
- // }}}
- // {{{ numCols()
-
- /**
- * Get the number of columns in a result set.
- *
- * @param $result fbsql result identifier
- *
- * @access public
- *
- * @return int the number of columns per row in $result
- */
- function numCols($result)
- {
- $cols = @fbsql_num_fields($result);
-
- if (!$cols) {
- return $this->fbsqlRaiseError();
- }
-
- return $cols;
- }
-
- // }}}
- // {{{ numRows()
-
- /**
- * Get the number of rows in a result set.
- *
- * @param $result fbsql result identifier
- *
- * @access public
- *
- * @return int the number of rows in $result
- */
- function numRows($result)
- {
- $rows = @fbsql_num_rows($result);
- if ($rows === null) {
- return $this->fbsqlRaiseError();
- }
- return $rows;
- }
-
- // }}}
- // {{{ affectedRows()
-
- /**
- * Gets the number of rows affected by the data manipulation
- * query. For other queries, this function returns 0.
- *
- * @return number of rows affected by the last query
- */
- function affectedRows()
- {
- if (DB::isManip($this->last_query)) {
- $result = @fbsql_affected_rows($this->connection);
- } else {
- $result = 0;
- }
- return $result;
- }
-
- // }}}
- // {{{ errorNative()
-
- /**
- * Get the native error code of the last error (if any) that
- * occured on the current connection.
- *
- * @access public
- *
- * @return int native fbsql error code
- */
- function errorNative()
- {
- return @fbsql_errno($this->connection);
- }
-
- // }}}
- // {{{ nextId()
-
- /**
- * Returns the next free id in a sequence
- *
- * @param string $seq_name name of the sequence
- * @param boolean $ondemand when true, the seqence is automatically
- * created if it does not exist
- *
- * @return int the next id number in the sequence. DB_Error if problem.
- *
- * @internal
- * @see DB_common::nextID()
- * @access public
- */
- function nextId($seq_name, $ondemand = true)
- {
- $seqname = $this->getSequenceName($seq_name);
- $repeat = 0;
- do {
- $result = $this->query("INSERT INTO ${seqname} VALUES(NULL)");
- if ($ondemand && DB::isError($result) &&
- $result->getCode() == DB_ERROR_NOSUCHTABLE) {
- $repeat = 1;
- $result = $this->createSequence($seq_name);
- if (DB::isError($result)) {
- return $result;
- }
- } else {
- $repeat = 0;
- }
- } while ($repeat);
- if (DB::isError($result)) {
- return $result;
- }
- return @fbsql_insert_id($this->connection);
- }
-
- /**
- * Creates a new sequence
- *
- * @param string $seq_name name of the new sequence
- *
- * @return int DB_OK on success. A DB_Error object is returned if
- * problems arise.
- *
- * @internal
- * @see DB_common::createSequence()
- * @access public
- */
- function createSequence($seq_name)
- {
- $seqname = $this->getSequenceName($seq_name);
- return $this->query("CREATE TABLE ${seqname} ".
- '(id INTEGER UNSIGNED AUTO_INCREMENT NOT NULL,'.
- ' PRIMARY KEY(id))');
- }
-
- // }}}
- // {{{ dropSequence()
-
- /**
- * Deletes a sequence
- *
- * @param string $seq_name name of the sequence to be deleted
- *
- * @return int DB_OK on success. DB_Error if problems.
- *
- * @internal
- * @see DB_common::dropSequence()
- * @access public
- */
- function dropSequence($seq_name)
- {
- $seqname = $this->getSequenceName($seq_name);
- return $this->query("DROP TABLE ${seqname} RESTRICT");
- }
-
- // }}}
- // {{{ modifyQuery()
-
- function modifyQuery($query)
- {
- if ($this->options['portability'] & DB_PORTABILITY_DELETE_COUNT) {
- // "DELETE FROM table" gives 0 affected rows in fbsql.
- // This little hack lets you know how many rows were deleted.
- if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $query)) {
- $query = preg_replace('/^\s*DELETE\s+FROM\s+(\S+)\s*$/',
- 'DELETE FROM \1 WHERE 1=1', $query);
- }
- }
- return $query;
- }
-
- // }}}
- // {{{ quoteSmart()
-
- /**
- * Format input so it can be safely used in a query
- *
- * @param mixed $in data to be quoted
- *
- * @return mixed Submitted variable's type = returned value:
- * + null = the string <samp>NULL</samp>
- * + boolean = string <samp>TRUE</samp> or <samp>FALSE</samp>
- * + integer or double = the unquoted number
- * + other (including strings and numeric strings) =
- * the data escaped according to MySQL's settings
- * then encapsulated between single quotes
- *
- * @internal
- */
- function quoteSmart($in)
- {
- if (is_int($in) || is_double($in)) {
- return $in;
- } elseif (is_bool($in)) {
- return $in ? 'TRUE' : 'FALSE';
- } elseif (is_null($in)) {
- return 'NULL';
- } else {
- return "'" . $this->escapeSimple($in) . "'";
- }
- }
-
- // }}}
- // {{{ fbsqlRaiseError()
-
- /**
- * Gather information about an error, then use that info to create a
- * DB error object and finally return that object.
- *
- * @param integer $errno PEAR error number (usually a DB constant) if
- * manually raising an error
- * @return object DB error object
- * @see DB_common::errorCode()
- * @see DB_common::raiseError()
- */
- function fbsqlRaiseError($errno = null)
- {
- if ($errno === null) {
- $errno = $this->errorCode(fbsql_errno($this->connection));
- }
- return $this->raiseError($errno, null, null, null,
- @fbsql_error($this->connection));
- }
-
- // }}}
- // {{{ tableInfo()
-
- /**
- * Returns information about a table or a result set.
- *
- * @param object|string $result DB_result object from a query or a
- * string containing the name of a table
- * @param int $mode a valid tableInfo mode
- * @return array an associative array with the information requested
- * or an error object if something is wrong
- * @access public
- * @internal
- * @see DB_common::tableInfo()
- */
- function tableInfo($result, $mode = null) {
- if (isset($result->result)) {
- /*
- * Probably received a result object.
- * Extract the result resource identifier.
- */
- $id = $result->result;
- $got_string = false;
- } elseif (is_string($result)) {
- /*
- * Probably received a table name.
- * Create a result resource identifier.
- */
- $id = @fbsql_list_fields($this->dsn['database'],
- $result, $this->connection);
- $got_string = true;
- } else {
- /*
- * Probably received a result resource identifier.
- * Copy it.
- * Depricated. Here for compatibility only.
- */
- $id = $result;
- $got_string = false;
- }
-
- if (!is_resource($id)) {
- return $this->fbsqlRaiseError(DB_ERROR_NEED_MORE_DATA);
- }
-
- if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) {
- $case_func = 'strtolower';
- } else {
- $case_func = 'strval';
- }
-
- $count = @fbsql_num_fields($id);
-
- // made this IF due to performance (one if is faster than $count if's)
- if (!$mode) {
- for ($i=0; $i<$count; $i++) {
- $res[$i]['table'] = $case_func(@fbsql_field_table($id, $i));
- $res[$i]['name'] = $case_func(@fbsql_field_name($id, $i));
- $res[$i]['type'] = @fbsql_field_type($id, $i);
- $res[$i]['len'] = @fbsql_field_len($id, $i);
- $res[$i]['flags'] = @fbsql_field_flags($id, $i);
- }
- } else { // full
- $res["num_fields"]= $count;
-
- for ($i=0; $i<$count; $i++) {
- $res[$i]['table'] = $case_func(@fbsql_field_table($id, $i));
- $res[$i]['name'] = $case_func(@fbsql_field_name($id, $i));
- $res[$i]['type'] = @fbsql_field_type($id, $i);
- $res[$i]['len'] = @fbsql_field_len($id, $i);
- $res[$i]['flags'] = @fbsql_field_flags($id, $i);
-
- if ($mode & DB_TABLEINFO_ORDER) {
- $res['order'][$res[$i]['name']] = $i;
- }
- if ($mode & DB_TABLEINFO_ORDERTABLE) {
- $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
- }
- }
- }
-
- // free the result only if we were called on a table
- if ($got_string) {
- @fbsql_free_result($id);
- }
- return $res;
- }
-
- // }}}
- // {{{ getSpecialQuery()
-
- /**
- * Returns the query needed to get some backend info
- * @param string $type What kind of info you want to retrieve
- * @return string The SQL query string
- */
- function getSpecialQuery($type)
- {
- switch ($type) {
- case 'tables':
- return 'select "table_name" from information_schema.tables';
- default:
- return null;
- }
- }
-
- // }}}
-}
-
-/*
- * Local variables:
- * tab-width: 4
- * c-basic-offset: 4
- * End:
- */
-
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 foldmethod=marker: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Sterling Hughes <sterling@php.net> |
-// | Maintainer: Daniel Convissor <danielc@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: ibase.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
-
-
-// Bugs:
-// - If dbsyntax is not firebird, the limitQuery may fail
-
-
-require_once 'DB/common.php';
-
-/**
- * Database independent query interface definition for PHP's Interbase
- * extension.
- *
- * @package DB
- * @version $Id: ibase.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
- * @category Database
- * @author Sterling Hughes <sterling@php.net>
- */
-class DB_ibase extends DB_common
-{
-
- // {{{ properties
-
- var $connection;
- var $phptype, $dbsyntax;
- var $autocommit = 1;
- var $manip_query = array();
-
- // }}}
- // {{{ constructor
-
- function DB_ibase()
- {
- $this->DB_common();
- $this->phptype = 'ibase';
- $this->dbsyntax = 'ibase';
- $this->features = array(
- 'prepare' => true,
- 'pconnect' => true,
- 'transactions' => true,
- 'limit' => false
- );
- // just a few of the tons of Interbase error codes listed in the
- // Language Reference section of the Interbase manual
- $this->errorcode_map = array(
- -104 => DB_ERROR_SYNTAX,
- -150 => DB_ERROR_ACCESS_VIOLATION,
- -151 => DB_ERROR_ACCESS_VIOLATION,
- -155 => DB_ERROR_NOSUCHTABLE,
- 88 => DB_ERROR_NOSUCHTABLE,
- -157 => DB_ERROR_NOSUCHFIELD,
- -158 => DB_ERROR_VALUE_COUNT_ON_ROW,
- -170 => DB_ERROR_MISMATCH,
- -171 => DB_ERROR_MISMATCH,
- -172 => DB_ERROR_INVALID,
- -204 => DB_ERROR_INVALID,
- -205 => DB_ERROR_NOSUCHFIELD,
- -206 => DB_ERROR_NOSUCHFIELD,
- -208 => DB_ERROR_INVALID,
- -219 => DB_ERROR_NOSUCHTABLE,
- -297 => DB_ERROR_CONSTRAINT,
- -530 => DB_ERROR_CONSTRAINT,
- -607 => DB_ERROR_NOSUCHTABLE,
- -803 => DB_ERROR_CONSTRAINT,
- -551 => DB_ERROR_ACCESS_VIOLATION,
- -552 => DB_ERROR_ACCESS_VIOLATION,
- -922 => DB_ERROR_NOSUCHDB,
- -923 => DB_ERROR_CONNECT_FAILED,
- -924 => DB_ERROR_CONNECT_FAILED
- );
- }
-
- // }}}
- // {{{ connect()
-
- function connect($dsninfo, $persistent = false)
- {
- if (!DB::assertExtension('interbase')) {
- return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
- }
- $this->dsn = $dsninfo;
- $dbhost = $dsninfo['hostspec'] ?
- ($dsninfo['hostspec'] . ':' . $dsninfo['database']) :
- $dsninfo['database'];
-
- $connect_function = $persistent ? 'ibase_pconnect' : 'ibase_connect';
-
- $params = array();
- $params[] = $dbhost;
- $params[] = $dsninfo['username'] ? $dsninfo['username'] : null;
- $params[] = $dsninfo['password'] ? $dsninfo['password'] : null;
- $params[] = isset($dsninfo['charset']) ? $dsninfo['charset'] : null;
- $params[] = isset($dsninfo['buffers']) ? $dsninfo['buffers'] : null;
- $params[] = isset($dsninfo['dialect']) ? $dsninfo['dialect'] : null;
- $params[] = isset($dsninfo['role']) ? $dsninfo['role'] : null;
-
- $conn = @call_user_func_array($connect_function, $params);
- if (!$conn) {
- return $this->ibaseRaiseError(DB_ERROR_CONNECT_FAILED);
- }
- $this->connection = $conn;
- if ($this->dsn['dbsyntax'] == 'firebird') {
- $this->features['limit'] = 'alter';
- }
- return DB_OK;
- }
-
- // }}}
- // {{{ disconnect()
-
- function disconnect()
- {
- $ret = @ibase_close($this->connection);
- $this->connection = null;
- return $ret;
- }
-
- // }}}
- // {{{ simpleQuery()
-
- function simpleQuery($query)
- {
- $ismanip = DB::isManip($query);
- $this->last_query = $query;
- $query = $this->modifyQuery($query);
- $result = @ibase_query($this->connection, $query);
- if (!$result) {
- return $this->ibaseRaiseError();
- }
- if ($this->autocommit && $ismanip) {
- @ibase_commit($this->connection);
- }
- // Determine which queries that should return data, and which
- // should return an error code only.
- return $ismanip ? DB_OK : $result;
- }
-
- // }}}
- // {{{ modifyLimitQuery()
-
- /**
- * This method is used by backends to alter limited queries
- * Uses the new FIRST n SKIP n Firebird 1.0 syntax, so it is
- * only compatible with Firebird 1.x
- *
- * @param string $query query to modify
- * @param integer $from the row to start to fetching
- * @param integer $count the numbers of rows to fetch
- *
- * @return the new (modified) query
- * @author Ludovico Magnocavallo <ludo@sumatrasolutions.com>
- * @access private
- */
- function modifyLimitQuery($query, $from, $count, $params = array())
- {
- if ($this->dsn['dbsyntax'] == 'firebird') {
- //$from++; // SKIP starts from 1, ie SKIP 1 starts from the first record
- // (cox) Seems that SKIP starts in 0
- $query = preg_replace('/^\s*select\s(.*)$/is',
- "SELECT FIRST $count SKIP $from $1", $query);
- }
- return $query;
- }
-
- // }}}
- // {{{ nextResult()
-
- /**
- * Move the internal ibase result pointer to the next available result
- *
- * @param a valid fbsql result resource
- *
- * @access public
- *
- * @return true if a result is available otherwise return false
- */
- function nextResult($result)
- {
- return false;
- }
-
- // }}}
- // {{{ fetchInto()
-
- /**
- * Fetch a row and insert the data into an existing array.
- *
- * Formating of the array and the data therein are configurable.
- * See DB_result::fetchInto() for more information.
- *
- * @param resource $result query result identifier
- * @param array $arr (reference) array where data from the row
- * should be placed
- * @param int $fetchmode how the resulting array should be indexed
- * @param int $rownum the row number to fetch
- *
- * @return mixed DB_OK on success, null when end of result set is
- * reached or on failure
- *
- * @see DB_result::fetchInto()
- * @access private
- */
- function fetchInto($result, &$arr, $fetchmode, $rownum=null)
- {
- if ($rownum !== null) {
- return $this->ibaseRaiseError(DB_ERROR_NOT_CAPABLE);
- }
- if ($fetchmode & DB_FETCHMODE_ASSOC) {
- if (function_exists('ibase_fetch_assoc')) {
- $arr = @ibase_fetch_assoc($result);
- } else {
- $arr = get_object_vars(ibase_fetch_object($result));
- }
- if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE && $arr) {
- $arr = array_change_key_case($arr, CASE_LOWER);
- }
- } else {
- $arr = @ibase_fetch_row($result);
- }
- if (!$arr) {
- if ($errmsg = @ibase_errmsg()) {
- return $this->ibaseRaiseError(null, $errmsg);
- } else {
- return null;
- }
- }
- if ($this->options['portability'] & DB_PORTABILITY_RTRIM) {
- $this->_rtrimArrayValues($arr);
- }
- if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) {
- $this->_convertNullArrayValuesToEmpty($arr);
- }
- return DB_OK;
- }
-
- // }}}
- // {{{ freeResult()
-
- function freeResult($result)
- {
- return @ibase_free_result($result);
- }
-
- // }}}
- // {{{ freeQuery()
-
- function freeQuery($query)
- {
- @ibase_free_query($query);
- return true;
- }
-
- // }}}
- // {{{ numCols()
-
- function numCols($result)
- {
- $cols = @ibase_num_fields($result);
- if (!$cols) {
- return $this->ibaseRaiseError();
- }
- return $cols;
- }
-
- // }}}
- // {{{ prepare()
-
- /**
- * Prepares a query for multiple execution with execute().
- *
- * prepare() requires a generic query as string like <code>
- * INSERT INTO numbers VALUES (?, ?, ?)
- * </code>. The <kbd>?</kbd> characters are placeholders.
- *
- * Three types of placeholders can be used:
- * + <kbd>?</kbd> a quoted scalar value, i.e. strings, integers
- * + <kbd>!</kbd> value is inserted 'as is'
- * + <kbd>&</kbd> requires a file name. The file's contents get
- * inserted into the query (i.e. saving binary
- * data in a db)
- *
- * Use backslashes to escape placeholder characters if you don't want
- * them to be interpreted as placeholders. Example: <code>
- * "UPDATE foo SET col=? WHERE col='over \& under'"
- * </code>
- *
- * @param string $query query to be prepared
- * @return mixed DB statement resource on success. DB_Error on failure.
- */
- function prepare($query)
- {
- $tokens = preg_split('/((?<!\\\)[&?!])/', $query, -1,
- PREG_SPLIT_DELIM_CAPTURE);
- $token = 0;
- $types = array();
- $newquery = '';
-
- foreach ($tokens as $key => $val) {
- switch ($val) {
- case '?':
- $types[$token++] = DB_PARAM_SCALAR;
- break;
- case '&':
- $types[$token++] = DB_PARAM_OPAQUE;
- break;
- case '!':
- $types[$token++] = DB_PARAM_MISC;
- break;
- default:
- $tokens[$key] = preg_replace('/\\\([&?!])/', "\\1", $val);
- $newquery .= $tokens[$key] . '?';
- }
- }
-
- $newquery = substr($newquery, 0, -1);
- $this->last_query = $query;
- $newquery = $this->modifyQuery($newquery);
- $stmt = @ibase_prepare($this->connection, $newquery);
- $this->prepare_types[(int)$stmt] = $types;
- $this->manip_query[(int)$stmt] = DB::isManip($query);
- return $stmt;
- }
-
- // }}}
- // {{{ execute()
-
- /**
- * Executes a DB statement prepared with prepare().
- *
- * @param resource $stmt a DB statement resource returned from prepare()
- * @param mixed $data array, string or numeric data to be used in
- * execution of the statement. Quantity of items
- * passed must match quantity of placeholders in
- * query: meaning 1 for non-array items or the
- * quantity of elements in the array.
- * @return object a new DB_Result or a DB_Error when fail
- * @see DB_ibase::prepare()
- * @access public
- */
- function &execute($stmt, $data = array())
- {
- if (!is_array($data)) {
- $data = array($data);
- }
-
- $types =& $this->prepare_types[$stmt];
- if (count($types) != count($data)) {
- $tmp =& $this->raiseError(DB_ERROR_MISMATCH);
- return $tmp;
- }
-
- $i = 0;
- foreach ($data as $key => $value) {
- if ($types[$i] == DB_PARAM_MISC) {
- /*
- * ibase doesn't seem to have the ability to pass a
- * parameter along unchanged, so strip off quotes from start
- * and end, plus turn two single quotes to one single quote,
- * in order to avoid the quotes getting escaped by
- * ibase and ending up in the database.
- */
- $data[$key] = preg_replace("/^'(.*)'$/", "\\1", $data[$key]);
- $data[$key] = str_replace("''", "'", $data[$key]);
- } elseif ($types[$i] == DB_PARAM_OPAQUE) {
- $fp = @fopen($data[$key], 'rb');
- if (!$fp) {
- $tmp =& $this->raiseError(DB_ERROR_ACCESS_VIOLATION);
- return $tmp;
- }
- $data[$key] = fread($fp, filesize($data[$key]));
- fclose($fp);
- }
- $i++;
- }
-
- array_unshift($data, $stmt);
-
- $res = call_user_func_array('ibase_execute', $data);
- if (!$res) {
- $tmp =& $this->ibaseRaiseError();
- return $tmp;
- }
- /* XXX need this?
- if ($this->autocommit && $this->manip_query[(int)$stmt]) {
- @ibase_commit($this->connection);
- }*/
- if ($this->manip_query[(int)$stmt]) {
- $tmp = DB_OK;
- } else {
- $tmp =& new DB_result($this, $res);
- }
- return $tmp;
- }
-
- /**
- * Free the internal resources associated with a prepared query.
- *
- * @param $stmt The interbase_query resource type
- *
- * @return bool true on success, false if $result is invalid
- */
- function freePrepared($stmt)
- {
- if (!is_resource($stmt)) {
- return false;
- }
- @ibase_free_query($stmt);
- unset($this->prepare_tokens[(int)$stmt]);
- unset($this->prepare_types[(int)$stmt]);
- unset($this->manip_query[(int)$stmt]);
- return true;
- }
-
- // }}}
- // {{{ autoCommit()
-
- function autoCommit($onoff = false)
- {
- $this->autocommit = $onoff ? 1 : 0;
- return DB_OK;
- }
-
- // }}}
- // {{{ commit()
-
- function commit()
- {
- return @ibase_commit($this->connection);
- }
-
- // }}}
- // {{{ rollback()
-
- function rollback()
- {
- return @ibase_rollback($this->connection);
- }
-
- // }}}
- // {{{ transactionInit()
-
- function transactionInit($trans_args = 0)
- {
- return $trans_args ? @ibase_trans($trans_args, $this->connection) : @ibase_trans();
- }
-
- // }}}
- // {{{ nextId()
-
- /**
- * Returns the next free id in a sequence
- *
- * @param string $seq_name name of the sequence
- * @param boolean $ondemand when true, the seqence is automatically
- * created if it does not exist
- *
- * @return int the next id number in the sequence. DB_Error if problem.
- *
- * @internal
- * @see DB_common::nextID()
- * @access public
- */
- function nextId($seq_name, $ondemand = true)
- {
- $sqn = strtoupper($this->getSequenceName($seq_name));
- $repeat = 0;
- do {
- $this->pushErrorHandling(PEAR_ERROR_RETURN);
- $result =& $this->query("SELECT GEN_ID(${sqn}, 1) "
- . 'FROM RDB$GENERATORS '
- . "WHERE RDB\$GENERATOR_NAME='${sqn}'");
- $this->popErrorHandling();
- if ($ondemand && DB::isError($result)) {
- $repeat = 1;
- $result = $this->createSequence($seq_name);
- if (DB::isError($result)) {
- return $result;
- }
- } else {
- $repeat = 0;
- }
- } while ($repeat);
- if (DB::isError($result)) {
- return $this->raiseError($result);
- }
- $arr = $result->fetchRow(DB_FETCHMODE_ORDERED);
- $result->free();
- return $arr[0];
- }
-
- // }}}
- // {{{ createSequence()
-
- /**
- * Create the sequence
- *
- * @param string $seq_name the name of the sequence
- * @return mixed DB_OK on success or DB error on error
- * @access public
- */
- function createSequence($seq_name)
- {
- $sqn = strtoupper($this->getSequenceName($seq_name));
- $this->pushErrorHandling(PEAR_ERROR_RETURN);
- $result = $this->query("CREATE GENERATOR ${sqn}");
- $this->popErrorHandling();
-
- return $result;
- }
-
- // }}}
- // {{{ dropSequence()
-
- /**
- * Drop a sequence
- *
- * @param string $seq_name the name of the sequence
- * @return mixed DB_OK on success or DB error on error
- * @access public
- */
- function dropSequence($seq_name)
- {
- $sqn = strtoupper($this->getSequenceName($seq_name));
- return $this->query('DELETE FROM RDB$GENERATORS '
- . "WHERE RDB\$GENERATOR_NAME='${sqn}'");
- }
-
- // }}}
- // {{{ _ibaseFieldFlags()
-
- /**
- * get the Flags of a Field
- *
- * @param string $field_name the name of the field
- * @param string $table_name the name of the table
- *
- * @return string The flags of the field ("primary_key", "unique_key", "not_null"
- * "default", "computed" and "blob" are supported)
- * @access private
- */
- function _ibaseFieldFlags($field_name, $table_name)
- {
- $sql = 'SELECT R.RDB$CONSTRAINT_TYPE CTYPE'
- .' FROM RDB$INDEX_SEGMENTS I'
- .' JOIN RDB$RELATION_CONSTRAINTS R ON I.RDB$INDEX_NAME=R.RDB$INDEX_NAME'
- .' WHERE I.RDB$FIELD_NAME=\'' . $field_name . '\''
- .' AND UPPER(R.RDB$RELATION_NAME)=\'' . strtoupper($table_name) . '\'';
-
- $result = @ibase_query($this->connection, $sql);
- if (!$result) {
- return $this->ibaseRaiseError();
- }
-
- $flags = '';
- if ($obj = @ibase_fetch_object($result)) {
- @ibase_free_result($result);
- if (isset($obj->CTYPE) && trim($obj->CTYPE) == 'PRIMARY KEY') {
- $flags .= 'primary_key ';
- }
- if (isset($obj->CTYPE) && trim($obj->CTYPE) == 'UNIQUE') {
- $flags .= 'unique_key ';
- }
- }
-
- $sql = 'SELECT R.RDB$NULL_FLAG AS NFLAG,'
- .' R.RDB$DEFAULT_SOURCE AS DSOURCE,'
- .' F.RDB$FIELD_TYPE AS FTYPE,'
- .' F.RDB$COMPUTED_SOURCE AS CSOURCE'
- .' FROM RDB$RELATION_FIELDS R '
- .' JOIN RDB$FIELDS F ON R.RDB$FIELD_SOURCE=F.RDB$FIELD_NAME'
- .' WHERE UPPER(R.RDB$RELATION_NAME)=\'' . strtoupper($table_name) . '\''
- .' AND R.RDB$FIELD_NAME=\'' . $field_name . '\'';
-
- $result = @ibase_query($this->connection, $sql);
- if (!$result) {
- return $this->ibaseRaiseError();
- }
- if ($obj = @ibase_fetch_object($result)) {
- @ibase_free_result($result);
- if (isset($obj->NFLAG)) {
- $flags .= 'not_null ';
- }
- if (isset($obj->DSOURCE)) {
- $flags .= 'default ';
- }
- if (isset($obj->CSOURCE)) {
- $flags .= 'computed ';
- }
- if (isset($obj->FTYPE) && $obj->FTYPE == 261) {
- $flags .= 'blob ';
- }
- }
-
- return trim($flags);
- }
-
- // }}}
- // {{{ tableInfo()
-
- /**
- * Returns information about a table or a result set.
- *
- * NOTE: only supports 'table' and 'flags' if <var>$result</var>
- * is a table name.
- *
- * @param object|string $result DB_result object from a query or a
- * string containing the name of a table
- * @param int $mode a valid tableInfo mode
- * @return array an associative array with the information requested
- * or an error object if something is wrong
- * @access public
- * @internal
- * @see DB_common::tableInfo()
- */
- function tableInfo($result, $mode = null)
- {
- if (isset($result->result)) {
- /*
- * Probably received a result object.
- * Extract the result resource identifier.
- */
- $id = $result->result;
- $got_string = false;
- } elseif (is_string($result)) {
- /*
- * Probably received a table name.
- * Create a result resource identifier.
- */
- $id = @ibase_query($this->connection,
- "SELECT * FROM $result WHERE 1=0");
- $got_string = true;
- } else {
- /*
- * Probably received a result resource identifier.
- * Copy it.
- * Depricated. Here for compatibility only.
- */
- $id = $result;
- $got_string = false;
- }
-
- if (!is_resource($id)) {
- return $this->ibaseRaiseError(DB_ERROR_NEED_MORE_DATA);
- }
-
- if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) {
- $case_func = 'strtolower';
- } else {
- $case_func = 'strval';
- }
-
- $count = @ibase_num_fields($id);
-
- // made this IF due to performance (one if is faster than $count if's)
- if (!$mode) {
- for ($i=0; $i<$count; $i++) {
- $info = @ibase_field_info($id, $i);
- $res[$i]['table'] = $got_string ? $case_func($result) : '';
- $res[$i]['name'] = $case_func($info['name']);
- $res[$i]['type'] = $info['type'];
- $res[$i]['len'] = $info['length'];
- $res[$i]['flags'] = ($got_string) ? $this->_ibaseFieldFlags($info['name'], $result) : '';
- }
- } else { // full
- $res['num_fields']= $count;
-
- for ($i=0; $i<$count; $i++) {
- $info = @ibase_field_info($id, $i);
- $res[$i]['table'] = $got_string ? $case_func($result) : '';
- $res[$i]['name'] = $case_func($info['name']);
- $res[$i]['type'] = $info['type'];
- $res[$i]['len'] = $info['length'];
- $res[$i]['flags'] = ($got_string) ? $this->_ibaseFieldFlags($info['name'], $result) : '';
-
- if ($mode & DB_TABLEINFO_ORDER) {
- $res['order'][$res[$i]['name']] = $i;
- }
- if ($mode & DB_TABLEINFO_ORDERTABLE) {
- $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
- }
- }
- }
-
- // free the result only if we were called on a table
- if ($got_string) {
- @ibase_free_result($id);
- }
- return $res;
- }
-
- // }}}
- // {{{ ibaseRaiseError()
-
- /**
- * Gather information about an error, then use that info to create a
- * DB error object and finally return that object.
- *
- * @param integer $db_errno PEAR error number (usually a DB constant) if
- * manually raising an error
- * @param string $native_errmsg text of error message if known
- * @return object DB error object
- * @see DB_common::errorCode()
- * @see DB_common::raiseError()
- */
- function &ibaseRaiseError($db_errno = null, $native_errmsg = null)
- {
- if ($native_errmsg === null) {
- $native_errmsg = @ibase_errmsg();
- }
- // memo for the interbase php module hackers: we need something similar
- // to mysql_errno() to retrieve error codes instead of this ugly hack
- if (preg_match('/^([^0-9\-]+)([0-9\-]+)\s+(.*)$/', $native_errmsg, $m)) {
- $native_errno = (int)$m[2];
- } else {
- $native_errno = null;
- }
- // try to map the native error to the DB one
- if ($db_errno === null) {
- if ($native_errno) {
- // try to interpret Interbase error code (that's why we need ibase_errno()
- // in the interbase module to return the real error code)
- switch ($native_errno) {
- case -204:
- if (is_int(strpos($m[3], 'Table unknown'))) {
- $db_errno = DB_ERROR_NOSUCHTABLE;
- }
- break;
- default:
- $db_errno = $this->errorCode($native_errno);
- }
- } else {
- $error_regexps = array(
- '/[tT]able not found/' => DB_ERROR_NOSUCHTABLE,
- '/[tT]able .* already exists/' => DB_ERROR_ALREADY_EXISTS,
- '/validation error for column .* value "\*\*\* null/' => DB_ERROR_CONSTRAINT_NOT_NULL,
- '/violation of [\w ]+ constraint/' => DB_ERROR_CONSTRAINT,
- '/conversion error from string/' => DB_ERROR_INVALID_NUMBER,
- '/no permission for/' => DB_ERROR_ACCESS_VIOLATION,
- '/arithmetic exception, numeric overflow, or string truncation/' => DB_ERROR_DIVZERO
- );
- foreach ($error_regexps as $regexp => $code) {
- if (preg_match($regexp, $native_errmsg)) {
- $db_errno = $code;
- $native_errno = null;
- break;
- }
- }
- }
- }
- $tmp =& $this->raiseError($db_errno, null, null, null, $native_errmsg);
- return $tmp;
- }
-
- // }}}
-
-}
-
-/*
- * Local variables:
- * tab-width: 4
- * c-basic-offset: 4
- * End:
- */
-
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 foldmethod=marker: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Tomas V.V.Cox <cox@idecnet.com> |
-// | Maintainer: Daniel Convissor <danielc@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: ifx.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
-
-
-// Legend:
-// For more info on Informix errors see:
-// http://www.informix.com/answers/english/ierrors.htm
-//
-// TODO:
-// - set needed env Informix vars on connect
-// - implement native prepare/execute
-
-
-require_once 'DB/common.php';
-
-/**
- * Database independent query interface definition for PHP's Informix
- * extension.
- *
- * @package DB
- * @version $Id: ifx.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
- * @category Database
- * @author Tomas V.V.Cox <cox@idecnet.com>
- */
-class DB_ifx extends DB_common
-{
- // {{{ properties
-
- var $connection;
- var $affected = 0;
- var $dsn = array();
- var $transaction_opcount = 0;
- var $autocommit = true;
- var $fetchmode = DB_FETCHMODE_ORDERED; /* Default fetch mode */
-
- // }}}
- // {{{ constructor
-
- function DB_ifx()
- {
- $this->phptype = 'ifx';
- $this->dbsyntax = 'ifx';
- $this->features = array(
- 'prepare' => false,
- 'pconnect' => true,
- 'transactions' => true,
- 'limit' => 'emulate'
- );
- $this->errorcode_map = array(
- '-201' => DB_ERROR_SYNTAX,
- '-206' => DB_ERROR_NOSUCHTABLE,
- '-217' => DB_ERROR_NOSUCHFIELD,
- '-239' => DB_ERROR_CONSTRAINT,
- '-253' => DB_ERROR_SYNTAX,
- '-292' => DB_ERROR_CONSTRAINT_NOT_NULL,
- '-310' => DB_ERROR_ALREADY_EXISTS,
- '-329' => DB_ERROR_NODBSELECTED,
- '-346' => DB_ERROR_CONSTRAINT,
- '-386' => DB_ERROR_CONSTRAINT_NOT_NULL,
- '-391' => DB_ERROR_CONSTRAINT_NOT_NULL,
- '-554' => DB_ERROR_SYNTAX,
- '-691' => DB_ERROR_CONSTRAINT,
- '-703' => DB_ERROR_CONSTRAINT_NOT_NULL,
- '-1204' => DB_ERROR_INVALID_DATE,
- '-1205' => DB_ERROR_INVALID_DATE,
- '-1206' => DB_ERROR_INVALID_DATE,
- '-1209' => DB_ERROR_INVALID_DATE,
- '-1210' => DB_ERROR_INVALID_DATE,
- '-1212' => DB_ERROR_INVALID_DATE,
- '-1213' => DB_ERROR_INVALID_NUMBER,
- );
- }
-
- // }}}
- // {{{ connect()
-
- /**
- * Connect to a database and log in as the specified user.
- *
- * @param $dsn the data source name (see DB::parseDSN for syntax)
- * @param $persistent (optional) whether the connection should
- * be persistent
- *
- * @return int DB_OK on success, a DB error code on failure
- */
- function connect($dsninfo, $persistent = false)
- {
- if (!DB::assertExtension('informix') &&
- !DB::assertExtension('Informix'))
- {
- return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
- }
- $this->dsn = $dsninfo;
- $dbhost = $dsninfo['hostspec'] ? '@' . $dsninfo['hostspec'] : '';
- $dbname = $dsninfo['database'] ? $dsninfo['database'] . $dbhost : '';
- $user = $dsninfo['username'] ? $dsninfo['username'] : '';
- $pw = $dsninfo['password'] ? $dsninfo['password'] : '';
-
- $connect_function = $persistent ? 'ifx_pconnect' : 'ifx_connect';
-
- $this->connection = @$connect_function($dbname, $user, $pw);
- if (!is_resource($this->connection)) {
- return $this->ifxraiseError(DB_ERROR_CONNECT_FAILED);
- }
- return DB_OK;
- }
-
- // }}}
- // {{{ disconnect()
-
- /**
- * Log out and disconnect from the database.
- *
- * @return bool true on success, false if not connected.
- */
- function disconnect()
- {
- $ret = @ifx_close($this->connection);
- $this->connection = null;
- return $ret;
- }
-
- // }}}
- // {{{ simpleQuery()
-
- /**
- * Send a query to Informix and return the results as a
- * Informix resource identifier.
- *
- * @param $query the SQL query
- *
- * @return int returns a valid Informix result for successful SELECT
- * queries, DB_OK for other successful queries. A DB error code
- * is returned on failure.
- */
- function simpleQuery($query)
- {
- $ismanip = DB::isManip($query);
- $this->last_query = $query;
- $this->affected = null;
- if (preg_match('/(SELECT)/i', $query)) { //TESTME: Use !DB::isManip()?
- // the scroll is needed for fetching absolute row numbers
- // in a select query result
- $result = @ifx_query($query, $this->connection, IFX_SCROLL);
- } else {
- if (!$this->autocommit && $ismanip) {
- if ($this->transaction_opcount == 0) {
- $result = @ifx_query('BEGIN WORK', $this->connection);
- if (!$result) {
- return $this->ifxraiseError();
- }
- }
- $this->transaction_opcount++;
- }
- $result = @ifx_query($query, $this->connection);
- }
- if (!$result) {
- return $this->ifxraiseError();
- }
- $this->affected = @ifx_affected_rows($result);
- // Determine which queries should return data, and which
- // should return an error code only.
- if (preg_match('/(SELECT)/i', $query)) {
- return $result;
- }
- // XXX Testme: free results inside a transaction
- // may cause to stop it and commit the work?
-
- // Result has to be freed even with a insert or update
- @ifx_free_result($result);
-
- return DB_OK;
- }
-
- // }}}
- // {{{ nextResult()
-
- /**
- * Move the internal ifx result pointer to the next available result
- *
- * @param a valid fbsql result resource
- *
- * @access public
- *
- * @return true if a result is available otherwise return false
- */
- function nextResult($result)
- {
- return false;
- }
-
- // }}}
- // {{{ affectedRows()
-
- /**
- * Gets the number of rows affected by the last query.
- * if the last query was a select, returns 0.
- *
- * @return number of rows affected by the last query
- */
- function affectedRows()
- {
- if (DB::isManip($this->last_query)) {
- return $this->affected;
- } else {
- return 0;
- }
-
- }
-
- // }}}
- // {{{ fetchInto()
-
- /**
- * Fetch a row and insert the data into an existing array.
- *
- * Formating of the array and the data therein are configurable.
- * See DB_result::fetchInto() for more information.
- *
- * @param resource $result query result identifier
- * @param array $arr (reference) array where data from the row
- * should be placed
- * @param int $fetchmode how the resulting array should be indexed
- * @param int $rownum the row number to fetch
- *
- * @return mixed DB_OK on success, null when end of result set is
- * reached or on failure
- *
- * @see DB_result::fetchInto()
- * @access private
- */
- function fetchInto($result, &$arr, $fetchmode, $rownum=null)
- {
- if (($rownum !== null) && ($rownum < 0)) {
- return null;
- }
- if ($rownum === null) {
- /*
- * Even though fetch_row() should return the next row if
- * $rownum is null, it doesn't in all cases. Bug 598.
- */
- $rownum = 'NEXT';
- } else {
- // Index starts at row 1, unlike most DBMS's starting at 0.
- $rownum++;
- }
- if (!$arr = @ifx_fetch_row($result, $rownum)) {
- return null;
- }
- if ($fetchmode !== DB_FETCHMODE_ASSOC) {
- $i=0;
- $order = array();
- foreach ($arr as $val) {
- $order[$i++] = $val;
- }
- $arr = $order;
- } elseif ($fetchmode == DB_FETCHMODE_ASSOC &&
- $this->options['portability'] & DB_PORTABILITY_LOWERCASE)
- {
- $arr = array_change_key_case($arr, CASE_LOWER);
- }
- if ($this->options['portability'] & DB_PORTABILITY_RTRIM) {
- $this->_rtrimArrayValues($arr);
- }
- if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) {
- $this->_convertNullArrayValuesToEmpty($arr);
- }
- return DB_OK;
- }
-
- // }}}
- // {{{ numRows()
-
- function numRows($result)
- {
- return $this->raiseError(DB_ERROR_NOT_CAPABLE);
- }
-
- // }}}
- // {{{ numCols()
-
- /**
- * Get the number of columns in a result set.
- *
- * @param $result Informix result identifier
- *
- * @return int the number of columns per row in $result
- */
- function numCols($result)
- {
- if (!$cols = @ifx_num_fields($result)) {
- return $this->ifxraiseError();
- }
- return $cols;
- }
-
- // }}}
- // {{{ freeResult()
-
- /**
- * Free the internal resources associated with $result.
- *
- * @param $result Informix result identifier
- *
- * @return bool true on success, false if $result is invalid
- */
- function freeResult($result)
- {
- return @ifx_free_result($result);
- }
-
- // }}}
- // {{{ autoCommit()
-
- /**
- * Enable/disable automatic commits
- */
- function autoCommit($onoff = true)
- {
- // XXX if $this->transaction_opcount > 0, we should probably
- // issue a warning here.
- $this->autocommit = $onoff ? true : false;
- return DB_OK;
- }
-
- // }}}
- // {{{ commit()
-
- /**
- * Commit the current transaction.
- */
- function commit()
- {
- if ($this->transaction_opcount > 0) {
- $result = @ifx_query('COMMIT WORK', $this->connection);
- $this->transaction_opcount = 0;
- if (!$result) {
- return $this->ifxRaiseError();
- }
- }
- return DB_OK;
- }
-
- // }}}
- // {{{ rollback()
-
- /**
- * Roll back (undo) the current transaction.
- */
- function rollback()
- {
- if ($this->transaction_opcount > 0) {
- $result = @ifx_query('ROLLBACK WORK', $this->connection);
- $this->transaction_opcount = 0;
- if (!$result) {
- return $this->ifxRaiseError();
- }
- }
- return DB_OK;
- }
-
- // }}}
- // {{{ ifxraiseError()
-
- /**
- * Gather information about an error, then use that info to create a
- * DB error object and finally return that object.
- *
- * @param integer $errno PEAR error number (usually a DB constant) if
- * manually raising an error
- * @return object DB error object
- * @see errorNative()
- * @see errorCode()
- * @see DB_common::raiseError()
- */
- function ifxraiseError($errno = null)
- {
- if ($errno === null) {
- $errno = $this->errorCode(ifx_error());
- }
-
- return $this->raiseError($errno, null, null, null,
- $this->errorNative());
- }
-
- // }}}
- // {{{ errorCode()
-
- /**
- * Map native error codes to DB's portable ones.
- *
- * Requires that the DB implementation's constructor fills
- * in the <var>$errorcode_map</var> property.
- *
- * @param string $nativecode error code returned by the database
- * @return int a portable DB error code, or DB_ERROR if this DB
- * implementation has no mapping for the given error code.
- */
- function errorCode($nativecode)
- {
- if (ereg('SQLCODE=(.*)]', $nativecode, $match)) {
- $code = $match[1];
- if (isset($this->errorcode_map[$code])) {
- return $this->errorcode_map[$code];
- }
- }
- return DB_ERROR;
- }
-
- // }}}
- // {{{ errorNative()
-
- /**
- * Get the native error message of the last error (if any) that
- * occured on the current connection.
- *
- * @return int native Informix error code
- */
- function errorNative()
- {
- return @ifx_error() . ' ' . @ifx_errormsg();
- }
-
- // }}}
- // {{{ getSpecialQuery()
-
- /**
- * Returns the query needed to get some backend info
- * @param string $type What kind of info you want to retrieve
- * @return string The SQL query string
- */
- function getSpecialQuery($type)
- {
- switch ($type) {
- case 'tables':
- return 'select tabname from systables where tabid >= 100';
- default:
- return null;
- }
- }
-
- // }}}
- // {{{ tableInfo()
-
- /**
- * Returns information about a table or a result set.
- *
- * NOTE: only supports 'table' if <var>$result</var> is a table name.
- *
- * If analyzing a query result and the result has duplicate field names,
- * an error will be raised saying
- * <samp>can't distinguish duplicate field names</samp>.
- *
- * @param object|string $result DB_result object from a query or a
- * string containing the name of a table
- * @param int $mode a valid tableInfo mode
- * @return array an associative array with the information requested
- * or an error object if something is wrong
- * @access public
- * @internal
- * @since 1.6.0
- * @see DB_common::tableInfo()
- */
- function tableInfo($result, $mode = null)
- {
- if (isset($result->result)) {
- /*
- * Probably received a result object.
- * Extract the result resource identifier.
- */
- $id = $result->result;
- $got_string = false;
- } elseif (is_string($result)) {
- /*
- * Probably received a table name.
- * Create a result resource identifier.
- */
- $id = @ifx_query("SELECT * FROM $result WHERE 1=0",
- $this->connection);
- $got_string = true;
- } else {
- /*
- * Probably received a result resource identifier.
- * Copy it.
- */
- $id = $result;
- $got_string = false;
- }
-
- if (!is_resource($id)) {
- return $this->ifxRaiseError(DB_ERROR_NEED_MORE_DATA);
- }
-
- $flds = @ifx_fieldproperties($id);
- $count = @ifx_num_fields($id);
-
- if (count($flds) != $count) {
- return $this->raiseError("can't distinguish duplicate field names");
- }
-
- if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) {
- $case_func = 'strtolower';
- } else {
- $case_func = 'strval';
- }
-
- $i = 0;
- // made this IF due to performance (one if is faster than $count if's)
- if (!$mode) {
- foreach ($flds as $key => $value) {
- $props = explode(';', $value);
-
- $res[$i]['table'] = $got_string ? $case_func($result) : '';
- $res[$i]['name'] = $case_func($key);
- $res[$i]['type'] = $props[0];
- $res[$i]['len'] = $props[1];
- $res[$i]['flags'] = $props[4] == 'N' ? 'not_null' : '';
- $i++;
- }
-
- } else { // full
- $res['num_fields'] = $count;
-
- foreach ($flds as $key => $value) {
- $props = explode(';', $value);
-
- $res[$i]['table'] = $got_string ? $case_func($result) : '';
- $res[$i]['name'] = $case_func($key);
- $res[$i]['type'] = $props[0];
- $res[$i]['len'] = $props[1];
- $res[$i]['flags'] = $props[4] == 'N' ? 'not_null' : '';
-
- if ($mode & DB_TABLEINFO_ORDER) {
- $res['order'][$res[$i]['name']] = $i;
- }
- if ($mode & DB_TABLEINFO_ORDERTABLE) {
- $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
- }
- $i++;
- }
- }
-
- // free the result only if we were called on a table
- if ($got_string) {
- @ifx_free_result($id);
- }
- return $res;
- }
-
- // }}}
-
-}
-
-/*
- * Local variables:
- * tab-width: 4
- * c-basic-offset: 4
- * End:
- */
-
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 foldmethod=marker: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Sterling Hughes <sterling@php.net> |
-// | Maintainer: Daniel Convissor <danielc@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: msql.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
-
-require_once 'DB/common.php';
-
-/**
- * Database independent query interface definition for PHP's Mini-SQL
- * extension.
- *
- * @package DB
- * @version $Id: msql.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
- * @category Database
- * @author Sterling Hughes <sterling@php.net>
- */
-class DB_msql extends DB_common
-{
- // {{{ properties
-
- var $connection;
- var $phptype, $dbsyntax;
- var $prepare_tokens = array();
- var $prepare_types = array();
-
- // }}}
- // {{{ constructor
-
- function DB_msql()
- {
- $this->DB_common();
- $this->phptype = 'msql';
- $this->dbsyntax = 'msql';
- $this->features = array(
- 'prepare' => false,
- 'pconnect' => true,
- 'transactions' => false,
- 'limit' => 'emulate'
- );
- }
-
- // }}}
- // {{{ connect()
-
- function connect($dsninfo, $persistent = false)
- {
- if (!DB::assertExtension('msql')) {
- return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
- }
-
- $this->dsn = $dsninfo;
- $dbhost = $dsninfo['hostspec'] ? $dsninfo['hostspec'] : 'localhost';
-
- $connect_function = $persistent ? 'msql_pconnect' : 'msql_connect';
-
- if ($dbhost && $dsninfo['username'] && $dsninfo['password']) {
- $conn = $connect_function($dbhost, $dsninfo['username'],
- $dsninfo['password']);
- } elseif ($dbhost && $dsninfo['username']) {
- $conn = $connect_function($dbhost, $dsninfo['username']);
- } else {
- $conn = $connect_function($dbhost);
- }
- if (!$conn) {
- $this->raiseError(DB_ERROR_CONNECT_FAILED);
- }
- if (!@msql_select_db($dsninfo['database'], $conn)){
- return $this->raiseError(DB_ERROR_NODBSELECTED);
- }
- $this->connection = $conn;
- return DB_OK;
- }
-
- // }}}
- // {{{ disconnect()
-
- function disconnect()
- {
- $ret = @msql_close($this->connection);
- $this->connection = null;
- return $ret;
- }
-
- // }}}
- // {{{ simpleQuery()
-
- function simpleQuery($query)
- {
- $this->last_query = $query;
- $query = $this->modifyQuery($query);
- $result = @msql_query($query, $this->connection);
- if (!$result) {
- return $this->raiseError();
- }
- // Determine which queries that should return data, and which
- // should return an error code only.
- return DB::isManip($query) ? DB_OK : $result;
- }
-
-
- // }}}
- // {{{ nextResult()
-
- /**
- * Move the internal msql result pointer to the next available result
- *
- * @param a valid fbsql result resource
- *
- * @access public
- *
- * @return true if a result is available otherwise return false
- */
- function nextResult($result)
- {
- return false;
- }
-
- // }}}
- // {{{ fetchInto()
-
- /**
- * Fetch a row and insert the data into an existing array.
- *
- * Formating of the array and the data therein are configurable.
- * See DB_result::fetchInto() for more information.
- *
- * @param resource $result query result identifier
- * @param array $arr (reference) array where data from the row
- * should be placed
- * @param int $fetchmode how the resulting array should be indexed
- * @param int $rownum the row number to fetch
- *
- * @return mixed DB_OK on success, null when end of result set is
- * reached or on failure
- *
- * @see DB_result::fetchInto()
- * @access private
- */
- function fetchInto($result, &$arr, $fetchmode, $rownum=null)
- {
- if ($rownum !== null) {
- if (!@msql_data_seek($result, $rownum)) {
- return null;
- }
- }
- if ($fetchmode & DB_FETCHMODE_ASSOC) {
- $arr = @msql_fetch_array($result, MSQL_ASSOC);
- if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE && $arr) {
- $arr = array_change_key_case($arr, CASE_LOWER);
- }
- } else {
- $arr = @msql_fetch_row($result);
- }
- if (!$arr) {
- if ($error = @msql_error()) {
- return $this->raiseError($error);
- } else {
- return null;
- }
- }
- if ($this->options['portability'] & DB_PORTABILITY_RTRIM) {
- $this->_rtrimArrayValues($arr);
- }
- if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) {
- $this->_convertNullArrayValuesToEmpty($arr);
- }
- return DB_OK;
- }
-
- // }}}
- // {{{ freeResult()
-
- function freeResult($result)
- {
- return @msql_free_result($result);
- }
-
- // }}}
- // {{{ numCols()
-
- function numCols($result)
- {
- $cols = @msql_num_fields($result);
- if (!$cols) {
- return $this->raiseError();
- }
- return $cols;
- }
-
- // }}}
- // {{{ numRows()
-
- function numRows($result)
- {
- $rows = @msql_num_rows($result);
- if (!$rows) {
- return $this->raiseError();
- }
- return $rows;
- }
-
- // }}}
- // {{{ affected()
-
- /**
- * Gets the number of rows affected by a query.
- *
- * @return number of rows affected by the last query
- */
- function affectedRows()
- {
- return @msql_affected_rows($this->connection);
- }
-
- // }}}
-
-}
-
-/*
- * Local variables:
- * tab-width: 4
- * c-basic-offset: 4
- * End:
- */
-
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 foldmethod=marker: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Sterling Hughes <sterling@php.net> |
-// | Maintainer: Daniel Convissor <danielc@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: mssql.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
-
-require_once 'DB/common.php';
-
-/**
- * Database independent query interface definition for PHP's Microsoft SQL Server
- * extension.
- *
- * @package DB
- * @version $Id: mssql.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
- * @category Database
- * @author Sterling Hughes <sterling@php.net>
- */
-class DB_mssql extends DB_common
-{
- // {{{ properties
-
- var $connection;
- var $phptype, $dbsyntax;
- var $prepare_tokens = array();
- var $prepare_types = array();
- var $transaction_opcount = 0;
- var $autocommit = true;
- var $_db = null;
-
- // }}}
- // {{{ constructor
-
- function DB_mssql()
- {
- $this->DB_common();
- $this->phptype = 'mssql';
- $this->dbsyntax = 'mssql';
- $this->features = array(
- 'prepare' => false,
- 'pconnect' => true,
- 'transactions' => true,
- 'limit' => 'emulate'
- );
- // XXX Add here error codes ie: 'S100E' => DB_ERROR_SYNTAX
- $this->errorcode_map = array(
- 170 => DB_ERROR_SYNTAX,
- 207 => DB_ERROR_NOSUCHFIELD,
- 208 => DB_ERROR_NOSUCHTABLE,
- 245 => DB_ERROR_INVALID_NUMBER,
- 515 => DB_ERROR_CONSTRAINT_NOT_NULL,
- 547 => DB_ERROR_CONSTRAINT,
- 2627 => DB_ERROR_CONSTRAINT,
- 2714 => DB_ERROR_ALREADY_EXISTS,
- 3701 => DB_ERROR_NOSUCHTABLE,
- 8134 => DB_ERROR_DIVZERO,
- );
- }
-
- // }}}
- // {{{ connect()
-
- function connect($dsninfo, $persistent = false)
- {
- if (!DB::assertExtension('mssql') && !DB::assertExtension('sybase')
- && !DB::assertExtension('sybase_ct'))
- {
- return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
- }
- $this->dsn = $dsninfo;
- $dbhost = $dsninfo['hostspec'] ? $dsninfo['hostspec'] : 'localhost';
- $dbhost .= $dsninfo['port'] ? ':' . $dsninfo['port'] : '';
-
- $connect_function = $persistent ? 'mssql_pconnect' : 'mssql_connect';
-
- if ($dbhost && $dsninfo['username'] && $dsninfo['password']) {
- $conn = @$connect_function($dbhost, $dsninfo['username'],
- $dsninfo['password']);
- } elseif ($dbhost && $dsninfo['username']) {
- $conn = @$connect_function($dbhost, $dsninfo['username']);
- } else {
- $conn = @$connect_function($dbhost);
- }
- if (!$conn) {
- return $this->raiseError(DB_ERROR_CONNECT_FAILED, null, null,
- null, @mssql_get_last_message());
- }
- if ($dsninfo['database']) {
- if (!@mssql_select_db($dsninfo['database'], $conn)) {
- return $this->raiseError(DB_ERROR_NODBSELECTED, null, null,
- null, @mssql_get_last_message());
- }
- $this->_db = $dsninfo['database'];
- }
- $this->connection = $conn;
- return DB_OK;
- }
-
- // }}}
- // {{{ disconnect()
-
- function disconnect()
- {
- $ret = @mssql_close($this->connection);
- $this->connection = null;
- return $ret;
- }
-
- // }}}
- // {{{ simpleQuery()
-
- function simpleQuery($query)
- {
- $ismanip = DB::isManip($query);
- $this->last_query = $query;
- if (!@mssql_select_db($this->_db, $this->connection)) {
- return $this->mssqlRaiseError(DB_ERROR_NODBSELECTED);
- }
- $query = $this->modifyQuery($query);
- if (!$this->autocommit && $ismanip) {
- if ($this->transaction_opcount == 0) {
- $result = @mssql_query('BEGIN TRAN', $this->connection);
- if (!$result) {
- return $this->mssqlRaiseError();
- }
- }
- $this->transaction_opcount++;
- }
- $result = @mssql_query($query, $this->connection);
- if (!$result) {
- return $this->mssqlRaiseError();
- }
- // Determine which queries that should return data, and which
- // should return an error code only.
- return $ismanip ? DB_OK : $result;
- }
-
- // }}}
- // {{{ nextResult()
-
- /**
- * Move the internal mssql result pointer to the next available result
- *
- * @param a valid fbsql result resource
- *
- * @access public
- *
- * @return true if a result is available otherwise return false
- */
- function nextResult($result)
- {
- return @mssql_next_result($result);
- }
-
- // }}}
- // {{{ fetchInto()
-
- /**
- * Fetch a row and insert the data into an existing array.
- *
- * Formating of the array and the data therein are configurable.
- * See DB_result::fetchInto() for more information.
- *
- * @param resource $result query result identifier
- * @param array $arr (reference) array where data from the row
- * should be placed
- * @param int $fetchmode how the resulting array should be indexed
- * @param int $rownum the row number to fetch
- *
- * @return mixed DB_OK on success, null when end of result set is
- * reached or on failure
- *
- * @see DB_result::fetchInto()
- * @access private
- */
- function fetchInto($result, &$arr, $fetchmode, $rownum=null)
- {
- if ($rownum !== null) {
- if (!@mssql_data_seek($result, $rownum)) {
- return null;
- }
- }
- if ($fetchmode & DB_FETCHMODE_ASSOC) {
- $arr = @mssql_fetch_array($result, MSSQL_ASSOC);
- if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE && $arr) {
- $arr = array_change_key_case($arr, CASE_LOWER);
- }
- } else {
- $arr = @mssql_fetch_row($result);
- }
- if (!$arr) {
- /* This throws informative error messages,
- don't use it for now
- if ($msg = @mssql_get_last_message()) {
- return $this->raiseError($msg);
- }
- */
- return null;
- }
- if ($this->options['portability'] & DB_PORTABILITY_RTRIM) {
- $this->_rtrimArrayValues($arr);
- }
- if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) {
- $this->_convertNullArrayValuesToEmpty($arr);
- }
- return DB_OK;
- }
-
- // }}}
- // {{{ freeResult()
-
- function freeResult($result)
- {
- return @mssql_free_result($result);
- }
-
- // }}}
- // {{{ numCols()
-
- function numCols($result)
- {
- $cols = @mssql_num_fields($result);
- if (!$cols) {
- return $this->mssqlRaiseError();
- }
- return $cols;
- }
-
- // }}}
- // {{{ numRows()
-
- function numRows($result)
- {
- $rows = @mssql_num_rows($result);
- if ($rows === false) {
- return $this->mssqlRaiseError();
- }
- return $rows;
- }
-
- // }}}
- // {{{ autoCommit()
-
- /**
- * Enable/disable automatic commits
- */
- function autoCommit($onoff = false)
- {
- // XXX if $this->transaction_opcount > 0, we should probably
- // issue a warning here.
- $this->autocommit = $onoff ? true : false;
- return DB_OK;
- }
-
- // }}}
- // {{{ commit()
-
- /**
- * Commit the current transaction.
- */
- function commit()
- {
- if ($this->transaction_opcount > 0) {
- if (!@mssql_select_db($this->_db, $this->connection)) {
- return $this->mssqlRaiseError(DB_ERROR_NODBSELECTED);
- }
- $result = @mssql_query('COMMIT TRAN', $this->connection);
- $this->transaction_opcount = 0;
- if (!$result) {
- return $this->mssqlRaiseError();
- }
- }
- return DB_OK;
- }
-
- // }}}
- // {{{ rollback()
-
- /**
- * Roll back (undo) the current transaction.
- */
- function rollback()
- {
- if ($this->transaction_opcount > 0) {
- if (!@mssql_select_db($this->_db, $this->connection)) {
- return $this->mssqlRaiseError(DB_ERROR_NODBSELECTED);
- }
- $result = @mssql_query('ROLLBACK TRAN', $this->connection);
- $this->transaction_opcount = 0;
- if (!$result) {
- return $this->mssqlRaiseError();
- }
- }
- return DB_OK;
- }
-
- // }}}
- // {{{ affectedRows()
-
- /**
- * Gets the number of rows affected by the last query.
- * if the last query was a select, returns 0.
- *
- * @return number of rows affected by the last query or DB_ERROR
- */
- function affectedRows()
- {
- if (DB::isManip($this->last_query)) {
- $res = @mssql_query('select @@rowcount', $this->connection);
- if (!$res) {
- return $this->mssqlRaiseError();
- }
- $ar = @mssql_fetch_row($res);
- if (!$ar) {
- $result = 0;
- } else {
- @mssql_free_result($res);
- $result = $ar[0];
- }
- } else {
- $result = 0;
- }
- return $result;
- }
-
- // }}}
- // {{{ nextId()
-
- /**
- * Returns the next free id in a sequence
- *
- * @param string $seq_name name of the sequence
- * @param boolean $ondemand when true, the seqence is automatically
- * created if it does not exist
- *
- * @return int the next id number in the sequence. DB_Error if problem.
- *
- * @internal
- * @see DB_common::nextID()
- * @access public
- */
- function nextId($seq_name, $ondemand = true)
- {
- $seqname = $this->getSequenceName($seq_name);
- if (!@mssql_select_db($this->_db, $this->connection)) {
- return $this->mssqlRaiseError(DB_ERROR_NODBSELECTED);
- }
- $repeat = 0;
- do {
- $this->pushErrorHandling(PEAR_ERROR_RETURN);
- $result = $this->query("INSERT INTO $seqname (vapor) VALUES (0)");
- $this->popErrorHandling();
- if ($ondemand && DB::isError($result) &&
- ($result->getCode() == DB_ERROR || $result->getCode() == DB_ERROR_NOSUCHTABLE))
- {
- $repeat = 1;
- $result = $this->createSequence($seq_name);
- if (DB::isError($result)) {
- return $this->raiseError($result);
- }
- } elseif (!DB::isError($result)) {
- $result =& $this->query("SELECT @@IDENTITY FROM $seqname");
- $repeat = 0;
- } else {
- $repeat = false;
- }
- } while ($repeat);
- if (DB::isError($result)) {
- return $this->raiseError($result);
- }
- $result = $result->fetchRow(DB_FETCHMODE_ORDERED);
- return $result[0];
- }
-
- /**
- * Creates a new sequence
- *
- * @param string $seq_name name of the new sequence
- *
- * @return int DB_OK on success. A DB_Error object is returned if
- * problems arise.
- *
- * @internal
- * @see DB_common::createSequence()
- * @access public
- */
- function createSequence($seq_name)
- {
- $seqname = $this->getSequenceName($seq_name);
- return $this->query("CREATE TABLE $seqname ".
- '([id] [int] IDENTITY (1, 1) NOT NULL ,' .
- '[vapor] [int] NULL)');
- }
-
- // }}}
- // {{{ dropSequence()
-
- /**
- * Deletes a sequence
- *
- * @param string $seq_name name of the sequence to be deleted
- *
- * @return int DB_OK on success. DB_Error if problems.
- *
- * @internal
- * @see DB_common::dropSequence()
- * @access public
- */
- function dropSequence($seq_name)
- {
- $seqname = $this->getSequenceName($seq_name);
- return $this->query("DROP TABLE $seqname");
- }
-
- // }}}
- // {{{ errorNative()
-
- /**
- * Determine MS SQL Server error code by querying @@ERROR.
- *
- * @return mixed mssql's native error code or DB_ERROR if unknown.
- */
- function errorNative()
- {
- $res = @mssql_query('select @@ERROR as ErrorCode', $this->connection);
- if (!$res) {
- return DB_ERROR;
- }
- $row = @mssql_fetch_row($res);
- return $row[0];
- }
-
- // }}}
- // {{{ errorCode()
-
- /**
- * Determine PEAR::DB error code from mssql's native codes.
- *
- * If <var>$nativecode</var> isn't known yet, it will be looked up.
- *
- * @param mixed $nativecode mssql error code, if known
- * @return integer an error number from a DB error constant
- * @see errorNative()
- */
- function errorCode($nativecode = null)
- {
- if (!$nativecode) {
- $nativecode = $this->errorNative();
- }
- if (isset($this->errorcode_map[$nativecode])) {
- return $this->errorcode_map[$nativecode];
- } else {
- return DB_ERROR;
- }
- }
-
- // }}}
- // {{{ mssqlRaiseError()
-
- /**
- * Gather information about an error, then use that info to create a
- * DB error object and finally return that object.
- *
- * @param integer $code PEAR error number (usually a DB constant) if
- * manually raising an error
- * @return object DB error object
- * @see errorCode()
- * @see errorNative()
- * @see DB_common::raiseError()
- */
- function mssqlRaiseError($code = null)
- {
- $message = @mssql_get_last_message();
- if (!$code) {
- $code = $this->errorNative();
- }
- return $this->raiseError($this->errorCode($code), null, null, null,
- "$code - $message");
- }
-
- // }}}
- // {{{ tableInfo()
-
- /**
- * Returns information about a table or a result set.
- *
- * NOTE: only supports 'table' and 'flags' if <var>$result</var>
- * is a table name.
- *
- * @param object|string $result DB_result object from a query or a
- * string containing the name of a table
- * @param int $mode a valid tableInfo mode
- * @return array an associative array with the information requested
- * or an error object if something is wrong
- * @access public
- * @internal
- * @see DB_common::tableInfo()
- */
- function tableInfo($result, $mode = null)
- {
- if (isset($result->result)) {
- /*
- * Probably received a result object.
- * Extract the result resource identifier.
- */
- $id = $result->result;
- $got_string = false;
- } elseif (is_string($result)) {
- /*
- * Probably received a table name.
- * Create a result resource identifier.
- */
- if (!@mssql_select_db($this->_db, $this->connection)) {
- return $this->mssqlRaiseError(DB_ERROR_NODBSELECTED);
- }
- $id = @mssql_query("SELECT * FROM $result WHERE 1=0",
- $this->connection);
- $got_string = true;
- } else {
- /*
- * Probably received a result resource identifier.
- * Copy it.
- * Depricated. Here for compatibility only.
- */
- $id = $result;
- $got_string = false;
- }
-
- if (!is_resource($id)) {
- return $this->mssqlRaiseError(DB_ERROR_NEED_MORE_DATA);
- }
-
- if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) {
- $case_func = 'strtolower';
- } else {
- $case_func = 'strval';
- }
-
- $count = @mssql_num_fields($id);
-
- // made this IF due to performance (one if is faster than $count if's)
- if (!$mode) {
- for ($i=0; $i<$count; $i++) {
- $res[$i]['table'] = $got_string ? $case_func($result) : '';
- $res[$i]['name'] = $case_func(@mssql_field_name($id, $i));
- $res[$i]['type'] = @mssql_field_type($id, $i);
- $res[$i]['len'] = @mssql_field_length($id, $i);
- // We only support flags for tables
- $res[$i]['flags'] = $got_string ? $this->_mssql_field_flags($result, $res[$i]['name']) : '';
- }
-
- } else { // full
- $res['num_fields']= $count;
-
- for ($i=0; $i<$count; $i++) {
- $res[$i]['table'] = $got_string ? $case_func($result) : '';
- $res[$i]['name'] = $case_func(@mssql_field_name($id, $i));
- $res[$i]['type'] = @mssql_field_type($id, $i);
- $res[$i]['len'] = @mssql_field_length($id, $i);
- // We only support flags for tables
- $res[$i]['flags'] = $got_string ? $this->_mssql_field_flags($result, $res[$i]['name']) : '';
-
- if ($mode & DB_TABLEINFO_ORDER) {
- $res['order'][$res[$i]['name']] = $i;
- }
- if ($mode & DB_TABLEINFO_ORDERTABLE) {
- $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
- }
- }
- }
-
- // free the result only if we were called on a table
- if ($got_string) {
- @mssql_free_result($id);
- }
- return $res;
- }
-
- // }}}
- // {{{ getSpecialQuery()
-
- /**
- * Returns the query needed to get some backend info
- * @param string $type What kind of info you want to retrieve
- * @return string The SQL query string
- */
- function getSpecialQuery($type)
- {
- switch ($type) {
- case 'tables':
- return "select name from sysobjects where type = 'U' order by name";
- case 'views':
- return "select name from sysobjects where type = 'V'";
- default:
- return null;
- }
- }
-
- // }}}
- // {{{ _mssql_field_flags()
-
- /**
- * Get the flags for a field, currently supports "not_null", "primary_key",
- * "auto_increment" (mssql identity), "timestamp" (mssql timestamp),
- * "unique_key" (mssql unique index, unique check or primary_key) and
- * "multiple_key" (multikey index)
- *
- * mssql timestamp is NOT similar to the mysql timestamp so this is maybe
- * not useful at all - is the behaviour of mysql_field_flags that primary
- * keys are alway unique? is the interpretation of multiple_key correct?
- *
- * @param string The table name
- * @param string The field
- * @author Joern Barthel <j_barthel@web.de>
- * @access private
- */
- function _mssql_field_flags($table, $column)
- {
- static $tableName = null;
- static $flags = array();
-
- if ($table != $tableName) {
-
- $flags = array();
- $tableName = $table;
-
- // get unique and primary keys
- $res = $this->getAll("EXEC SP_HELPINDEX[$table]", DB_FETCHMODE_ASSOC);
-
- foreach ($res as $val) {
- $keys = explode(', ', $val['index_keys']);
-
- if (sizeof($keys) > 1) {
- foreach ($keys as $key) {
- $this->_add_flag($flags[$key], 'multiple_key');
- }
- }
-
- if (strpos($val['index_description'], 'primary key')) {
- foreach ($keys as $key) {
- $this->_add_flag($flags[$key], 'primary_key');
- }
- } elseif (strpos($val['index_description'], 'unique')) {
- foreach ($keys as $key) {
- $this->_add_flag($flags[$key], 'unique_key');
- }
- }
- }
-
- // get auto_increment, not_null and timestamp
- $res = $this->getAll("EXEC SP_COLUMNS[$table]", DB_FETCHMODE_ASSOC);
-
- foreach ($res as $val) {
- $val = array_change_key_case($val, CASE_LOWER);
- if ($val['nullable'] == '0') {
- $this->_add_flag($flags[$val['column_name']], 'not_null');
- }
- if (strpos($val['type_name'], 'identity')) {
- $this->_add_flag($flags[$val['column_name']], 'auto_increment');
- }
- if (strpos($val['type_name'], 'timestamp')) {
- $this->_add_flag($flags[$val['column_name']], 'timestamp');
- }
- }
- }
-
- if (array_key_exists($column, $flags)) {
- return(implode(' ', $flags[$column]));
- }
- return '';
- }
-
- // }}}
- // {{{ _add_flag()
-
- /**
- * Adds a string to the flags array if the flag is not yet in there
- * - if there is no flag present the array is created.
- *
- * @param reference Reference to the flag-array
- * @param value The flag value
- * @access private
- * @author Joern Barthel <j_barthel@web.de>
- */
- function _add_flag(&$array, $value)
- {
- if (!is_array($array)) {
- $array = array($value);
- } elseif (!in_array($value, $array)) {
- array_push($array, $value);
- }
- }
-
- // }}}
- // {{{ quoteIdentifier()
-
- /**
- * Quote a string so it can be safely used as a table / column name
- *
- * Quoting style depends on which database driver is being used.
- *
- * @param string $str identifier name to be quoted
- *
- * @return string quoted identifier string
- *
- * @since 1.6.0
- * @access public
- */
- function quoteIdentifier($str)
- {
- return '[' . str_replace(']', ']]', $str) . ']';
- }
-
- // }}}
-}
-
-/*
- * Local variables:
- * tab-width: 4
- * c-basic-offset: 4
- * End:
- */
-
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 foldmethod=marker: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Stig Bakken <ssb@php.net> |
-// | Maintainer: Daniel Convissor <danielc@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: mysql.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
-
-
-// XXX legend:
-//
-// XXX ERRORMSG: The error message from the mysql function should
-// be registered here.
-//
-// TODO/wishlist:
-// longReadlen
-// binmode
-
-
-require_once 'DB/common.php';
-
-/**
- * Database independent query interface definition for PHP's MySQL
- * extension.
- *
- * This is for MySQL versions 4.0 and below.
- *
- * @package DB
- * @version $Id: mysql.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
- * @category Database
- * @author Stig Bakken <ssb@php.net>
- */
-class DB_mysql extends DB_common
-{
- // {{{ properties
-
- var $connection;
- var $phptype, $dbsyntax;
- var $prepare_tokens = array();
- var $prepare_types = array();
- var $num_rows = array();
- var $transaction_opcount = 0;
- var $autocommit = true;
- var $fetchmode = DB_FETCHMODE_ORDERED; /* Default fetch mode */
- var $_db = false;
-
- // }}}
- // {{{ constructor
-
- /**
- * DB_mysql constructor.
- *
- * @access public
- */
- function DB_mysql()
- {
- $this->DB_common();
- $this->phptype = 'mysql';
- $this->dbsyntax = 'mysql';
- $this->features = array(
- 'prepare' => false,
- 'pconnect' => true,
- 'transactions' => true,
- 'limit' => 'alter'
- );
- $this->errorcode_map = array(
- 1004 => DB_ERROR_CANNOT_CREATE,
- 1005 => DB_ERROR_CANNOT_CREATE,
- 1006 => DB_ERROR_CANNOT_CREATE,
- 1007 => DB_ERROR_ALREADY_EXISTS,
- 1008 => DB_ERROR_CANNOT_DROP,
- 1022 => DB_ERROR_ALREADY_EXISTS,
- 1046 => DB_ERROR_NODBSELECTED,
- 1050 => DB_ERROR_ALREADY_EXISTS,
- 1051 => DB_ERROR_NOSUCHTABLE,
- 1054 => DB_ERROR_NOSUCHFIELD,
- 1062 => DB_ERROR_ALREADY_EXISTS,
- 1064 => DB_ERROR_SYNTAX,
- 1100 => DB_ERROR_NOT_LOCKED,
- 1136 => DB_ERROR_VALUE_COUNT_ON_ROW,
- 1146 => DB_ERROR_NOSUCHTABLE,
- 1048 => DB_ERROR_CONSTRAINT,
- 1216 => DB_ERROR_CONSTRAINT
- );
- }
-
- // }}}
- // {{{ connect()
-
- /**
- * Connect to a database and log in as the specified user.
- *
- * @param $dsn the data source name (see DB::parseDSN for syntax)
- * @param $persistent (optional) whether the connection should
- * be persistent
- * @access public
- * @return int DB_OK on success, a DB error on failure
- */
- function connect($dsninfo, $persistent = false)
- {
- if (!DB::assertExtension('mysql')) {
- return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
- }
- $this->dsn = $dsninfo;
- if ($dsninfo['protocol'] && $dsninfo['protocol'] == 'unix') {
- $dbhost = ':' . $dsninfo['socket'];
- } else {
- $dbhost = $dsninfo['hostspec'] ? $dsninfo['hostspec'] : 'localhost';
- if ($dsninfo['port']) {
- $dbhost .= ':' . $dsninfo['port'];
- }
- }
-
- $connect_function = $persistent ? 'mysql_pconnect' : 'mysql_connect';
-
- if ($dbhost && $dsninfo['username'] && isset($dsninfo['password'])) {
- $conn = @$connect_function($dbhost, $dsninfo['username'],
- $dsninfo['password']);
- } elseif ($dbhost && $dsninfo['username']) {
- $conn = @$connect_function($dbhost, $dsninfo['username']);
- } elseif ($dbhost) {
- $conn = @$connect_function($dbhost);
- } else {
- $conn = false;
- }
- if (!$conn) {
- if (($err = @mysql_error()) != '') {
- return $this->raiseError(DB_ERROR_CONNECT_FAILED, null, null,
- null, $err);
- } elseif (empty($php_errormsg)) {
- return $this->raiseError(DB_ERROR_CONNECT_FAILED);
- } else {
- return $this->raiseError(DB_ERROR_CONNECT_FAILED, null, null,
- null, $php_errormsg);
- }
- }
-
- if ($dsninfo['database']) {
- if (!@mysql_select_db($dsninfo['database'], $conn)) {
- switch(mysql_errno($conn)) {
- case 1049:
- return $this->raiseError(DB_ERROR_NOSUCHDB, null, null,
- null, @mysql_error($conn));
- case 1044:
- return $this->raiseError(DB_ERROR_ACCESS_VIOLATION, null, null,
- null, @mysql_error($conn));
- default:
- return $this->raiseError(DB_ERROR, null, null,
- null, @mysql_error($conn));
- }
- }
- // fix to allow calls to different databases in the same script
- $this->_db = $dsninfo['database'];
- }
-
- $this->connection = $conn;
- return DB_OK;
- }
-
- // }}}
- // {{{ disconnect()
-
- /**
- * Log out and disconnect from the database.
- *
- * @access public
- *
- * @return bool true on success, false if not connected.
- */
- function disconnect()
- {
- $ret = @mysql_close($this->connection);
- $this->connection = null;
- return $ret;
- }
-
- // }}}
- // {{{ simpleQuery()
-
- /**
- * Send a query to MySQL and return the results as a MySQL resource
- * identifier.
- *
- * @param the SQL query
- *
- * @access public
- *
- * @return mixed returns a valid MySQL result for successful SELECT
- * queries, DB_OK for other successful queries. A DB error is
- * returned on failure.
- */
- function simpleQuery($query)
- {
- $ismanip = DB::isManip($query);
- $this->last_query = $query;
- $query = $this->modifyQuery($query);
- if ($this->_db) {
- if (!@mysql_select_db($this->_db, $this->connection)) {
- return $this->mysqlRaiseError(DB_ERROR_NODBSELECTED);
- }
- }
- if (!$this->autocommit && $ismanip) {
- if ($this->transaction_opcount == 0) {
- $result = @mysql_query('SET AUTOCOMMIT=0', $this->connection);
- $result = @mysql_query('BEGIN', $this->connection);
- if (!$result) {
- return $this->mysqlRaiseError();
- }
- }
- $this->transaction_opcount++;
- }
- $result = @mysql_query($query, $this->connection);
- if (!$result) {
- return $this->mysqlRaiseError();
- }
- if (is_resource($result)) {
- $numrows = $this->numrows($result);
- if (is_object($numrows)) {
- return $numrows;
- }
- $this->num_rows[(int)$result] = $numrows;
- return $result;
- }
- return DB_OK;
- }
-
- // }}}
- // {{{ nextResult()
-
- /**
- * Move the internal mysql result pointer to the next available result
- *
- * This method has not been implemented yet.
- *
- * @param a valid sql result resource
- *
- * @access public
- *
- * @return false
- */
- function nextResult($result)
- {
- return false;
- }
-
- // }}}
- // {{{ fetchInto()
-
- /**
- * Fetch a row and insert the data into an existing array.
- *
- * Formating of the array and the data therein are configurable.
- * See DB_result::fetchInto() for more information.
- *
- * @param resource $result query result identifier
- * @param array $arr (reference) array where data from the row
- * should be placed
- * @param int $fetchmode how the resulting array should be indexed
- * @param int $rownum the row number to fetch
- *
- * @return mixed DB_OK on success, null when end of result set is
- * reached or on failure
- *
- * @see DB_result::fetchInto()
- * @access private
- */
- function fetchInto($result, &$arr, $fetchmode, $rownum=null)
- {
- if ($rownum !== null) {
- if (!@mysql_data_seek($result, $rownum)) {
- return null;
- }
- }
- if ($fetchmode & DB_FETCHMODE_ASSOC) {
- $arr = @mysql_fetch_array($result, MYSQL_ASSOC);
- if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE && $arr) {
- $arr = array_change_key_case($arr, CASE_LOWER);
- }
- } else {
- $arr = @mysql_fetch_row($result);
- }
- if (!$arr) {
- // See: http://bugs.php.net/bug.php?id=22328
- // for why we can't check errors on fetching
- return null;
- /*
- $errno = @mysql_errno($this->connection);
- if (!$errno) {
- return null;
- }
- return $this->mysqlRaiseError($errno);
- */
- }
- if ($this->options['portability'] & DB_PORTABILITY_RTRIM) {
- /*
- * Even though this DBMS already trims output, we do this because
- * a field might have intentional whitespace at the end that
- * gets removed by DB_PORTABILITY_RTRIM under another driver.
- */
- $this->_rtrimArrayValues($arr);
- }
- if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) {
- $this->_convertNullArrayValuesToEmpty($arr);
- }
- return DB_OK;
- }
-
- // }}}
- // {{{ freeResult()
-
- /**
- * Free the internal resources associated with $result.
- *
- * @param $result MySQL result identifier
- *
- * @access public
- *
- * @return bool true on success, false if $result is invalid
- */
- function freeResult($result)
- {
- unset($this->num_rows[(int)$result]);
- return @mysql_free_result($result);
- }
-
- // }}}
- // {{{ numCols()
-
- /**
- * Get the number of columns in a result set.
- *
- * @param $result MySQL result identifier
- *
- * @access public
- *
- * @return int the number of columns per row in $result
- */
- function numCols($result)
- {
- $cols = @mysql_num_fields($result);
-
- if (!$cols) {
- return $this->mysqlRaiseError();
- }
-
- return $cols;
- }
-
- // }}}
- // {{{ numRows()
-
- /**
- * Get the number of rows in a result set.
- *
- * @param $result MySQL result identifier
- *
- * @access public
- *
- * @return int the number of rows in $result
- */
- function numRows($result)
- {
- $rows = @mysql_num_rows($result);
- if ($rows === null) {
- return $this->mysqlRaiseError();
- }
- return $rows;
- }
-
- // }}}
- // {{{ autoCommit()
-
- /**
- * Enable/disable automatic commits
- */
- function autoCommit($onoff = false)
- {
- // XXX if $this->transaction_opcount > 0, we should probably
- // issue a warning here.
- $this->autocommit = $onoff ? true : false;
- return DB_OK;
- }
-
- // }}}
- // {{{ commit()
-
- /**
- * Commit the current transaction.
- */
- function commit()
- {
- if ($this->transaction_opcount > 0) {
- if ($this->_db) {
- if (!@mysql_select_db($this->_db, $this->connection)) {
- return $this->mysqlRaiseError(DB_ERROR_NODBSELECTED);
- }
- }
- $result = @mysql_query('COMMIT', $this->connection);
- $result = @mysql_query('SET AUTOCOMMIT=1', $this->connection);
- $this->transaction_opcount = 0;
- if (!$result) {
- return $this->mysqlRaiseError();
- }
- }
- return DB_OK;
- }
-
- // }}}
- // {{{ rollback()
-
- /**
- * Roll back (undo) the current transaction.
- */
- function rollback()
- {
- if ($this->transaction_opcount > 0) {
- if ($this->_db) {
- if (!@mysql_select_db($this->_db, $this->connection)) {
- return $this->mysqlRaiseError(DB_ERROR_NODBSELECTED);
- }
- }
- $result = @mysql_query('ROLLBACK', $this->connection);
- $result = @mysql_query('SET AUTOCOMMIT=1', $this->connection);
- $this->transaction_opcount = 0;
- if (!$result) {
- return $this->mysqlRaiseError();
- }
- }
- return DB_OK;
- }
-
- // }}}
- // {{{ affectedRows()
-
- /**
- * Gets the number of rows affected by the data manipulation
- * query. For other queries, this function returns 0.
- *
- * @return number of rows affected by the last query
- */
- function affectedRows()
- {
- if (DB::isManip($this->last_query)) {
- return @mysql_affected_rows($this->connection);
- } else {
- return 0;
- }
- }
-
- // }}}
- // {{{ errorNative()
-
- /**
- * Get the native error code of the last error (if any) that
- * occured on the current connection.
- *
- * @access public
- *
- * @return int native MySQL error code
- */
- function errorNative()
- {
- return @mysql_errno($this->connection);
- }
-
- // }}}
- // {{{ nextId()
-
- /**
- * Returns the next free id in a sequence
- *
- * @param string $seq_name name of the sequence
- * @param boolean $ondemand when true, the seqence is automatically
- * created if it does not exist
- *
- * @return int the next id number in the sequence. DB_Error if problem.
- *
- * @internal
- * @see DB_common::nextID()
- * @access public
- */
- function nextId($seq_name, $ondemand = true)
- {
- $seqname = $this->getSequenceName($seq_name);
- do {
- $repeat = 0;
- $this->pushErrorHandling(PEAR_ERROR_RETURN);
- $result = $this->query("UPDATE ${seqname} ".
- 'SET id=LAST_INSERT_ID(id+1)');
- $this->popErrorHandling();
- if ($result === DB_OK) {
- /** COMMON CASE **/
- $id = @mysql_insert_id($this->connection);
- if ($id != 0) {
- return $id;
- }
- /** EMPTY SEQ TABLE **/
- // Sequence table must be empty for some reason, so fill it and return 1
- // Obtain a user-level lock
- $result = $this->getOne("SELECT GET_LOCK('${seqname}_lock',10)");
- if (DB::isError($result)) {
- return $this->raiseError($result);
- }
- if ($result == 0) {
- // Failed to get the lock, bail with a DB_ERROR_NOT_LOCKED error
- return $this->mysqlRaiseError(DB_ERROR_NOT_LOCKED);
- }
-
- // add the default value
- $result = $this->query("REPLACE INTO ${seqname} VALUES (0)");
- if (DB::isError($result)) {
- return $this->raiseError($result);
- }
-
- // Release the lock
- $result = $this->getOne("SELECT RELEASE_LOCK('${seqname}_lock')");
- if (DB::isError($result)) {
- return $this->raiseError($result);
- }
- // We know what the result will be, so no need to try again
- return 1;
-
- /** ONDEMAND TABLE CREATION **/
- } elseif ($ondemand && DB::isError($result) &&
- $result->getCode() == DB_ERROR_NOSUCHTABLE)
- {
- $result = $this->createSequence($seq_name);
- if (DB::isError($result)) {
- return $this->raiseError($result);
- } else {
- $repeat = 1;
- }
-
- /** BACKWARDS COMPAT **/
- } elseif (DB::isError($result) &&
- $result->getCode() == DB_ERROR_ALREADY_EXISTS)
- {
- // see _BCsequence() comment
- $result = $this->_BCsequence($seqname);
- if (DB::isError($result)) {
- return $this->raiseError($result);
- }
- $repeat = 1;
- }
- } while ($repeat);
-
- return $this->raiseError($result);
- }
-
- // }}}
- // {{{ createSequence()
-
- /**
- * Creates a new sequence
- *
- * @param string $seq_name name of the new sequence
- *
- * @return int DB_OK on success. A DB_Error object is returned if
- * problems arise.
- *
- * @internal
- * @see DB_common::createSequence()
- * @access public
- */
- function createSequence($seq_name)
- {
- $seqname = $this->getSequenceName($seq_name);
- $res = $this->query("CREATE TABLE ${seqname} ".
- '(id INTEGER UNSIGNED AUTO_INCREMENT NOT NULL,'.
- ' PRIMARY KEY(id))');
- if (DB::isError($res)) {
- return $res;
- }
- // insert yields value 1, nextId call will generate ID 2
- $res = $this->query("INSERT INTO ${seqname} VALUES(0)");
- if (DB::isError($res)) {
- return $res;
- }
- // so reset to zero
- return $this->query("UPDATE ${seqname} SET id = 0;");
- }
-
- // }}}
- // {{{ dropSequence()
-
- /**
- * Deletes a sequence
- *
- * @param string $seq_name name of the sequence to be deleted
- *
- * @return int DB_OK on success. DB_Error if problems.
- *
- * @internal
- * @see DB_common::dropSequence()
- * @access public
- */
- function dropSequence($seq_name)
- {
- return $this->query('DROP TABLE ' . $this->getSequenceName($seq_name));
- }
-
- // }}}
- // {{{ _BCsequence()
-
- /**
- * Backwards compatibility with old sequence emulation implementation
- * (clean up the dupes)
- *
- * @param string $seqname The sequence name to clean up
- * @return mixed DB_Error or true
- */
- function _BCsequence($seqname)
- {
- // Obtain a user-level lock... this will release any previous
- // application locks, but unlike LOCK TABLES, it does not abort
- // the current transaction and is much less frequently used.
- $result = $this->getOne("SELECT GET_LOCK('${seqname}_lock',10)");
- if (DB::isError($result)) {
- return $result;
- }
- if ($result == 0) {
- // Failed to get the lock, can't do the conversion, bail
- // with a DB_ERROR_NOT_LOCKED error
- return $this->mysqlRaiseError(DB_ERROR_NOT_LOCKED);
- }
-
- $highest_id = $this->getOne("SELECT MAX(id) FROM ${seqname}");
- if (DB::isError($highest_id)) {
- return $highest_id;
- }
- // This should kill all rows except the highest
- // We should probably do something if $highest_id isn't
- // numeric, but I'm at a loss as how to handle that...
- $result = $this->query("DELETE FROM ${seqname} WHERE id <> $highest_id");
- if (DB::isError($result)) {
- return $result;
- }
-
- // If another thread has been waiting for this lock,
- // it will go thru the above procedure, but will have no
- // real effect
- $result = $this->getOne("SELECT RELEASE_LOCK('${seqname}_lock')");
- if (DB::isError($result)) {
- return $result;
- }
- return true;
- }
-
- // }}}
- // {{{ quoteIdentifier()
-
- /**
- * Quote a string so it can be safely used as a table or column name
- *
- * Quoting style depends on which database driver is being used.
- *
- * MySQL can't handle the backtick character (<kbd>`</kbd>) in
- * table or column names.
- *
- * @param string $str identifier name to be quoted
- *
- * @return string quoted identifier string
- *
- * @since 1.6.0
- * @access public
- * @internal
- */
- function quoteIdentifier($str)
- {
- return '`' . $str . '`';
- }
-
- // }}}
- // {{{ quote()
-
- /**
- * @deprecated Deprecated in release 1.6.0
- * @internal
- */
- function quote($str) {
- return $this->quoteSmart($str);
- }
-
- // }}}
- // {{{ escapeSimple()
-
- /**
- * Escape a string according to the current DBMS's standards
- *
- * @param string $str the string to be escaped
- *
- * @return string the escaped string
- *
- * @internal
- */
- function escapeSimple($str) {
- if (function_exists('mysql_real_escape_string')) {
- return @mysql_real_escape_string($str, $this->connection);
- } else {
- return @mysql_escape_string($str);
- }
- }
-
- // }}}
- // {{{ modifyQuery()
-
- function modifyQuery($query)
- {
- if ($this->options['portability'] & DB_PORTABILITY_DELETE_COUNT) {
- // "DELETE FROM table" gives 0 affected rows in MySQL.
- // This little hack lets you know how many rows were deleted.
- if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $query)) {
- $query = preg_replace('/^\s*DELETE\s+FROM\s+(\S+)\s*$/',
- 'DELETE FROM \1 WHERE 1=1', $query);
- }
- }
- return $query;
- }
-
- // }}}
- // {{{ modifyLimitQuery()
-
- function modifyLimitQuery($query, $from, $count, $params = array())
- {
- if (DB::isManip($query)) {
- return $query . " LIMIT $count";
- } else {
- return $query . " LIMIT $from, $count";
- }
- }
-
- // }}}
- // {{{ mysqlRaiseError()
-
- /**
- * Gather information about an error, then use that info to create a
- * DB error object and finally return that object.
- *
- * @param integer $errno PEAR error number (usually a DB constant) if
- * manually raising an error
- * @return object DB error object
- * @see DB_common::errorCode()
- * @see DB_common::raiseError()
- */
- function mysqlRaiseError($errno = null)
- {
- if ($errno === null) {
- if ($this->options['portability'] & DB_PORTABILITY_ERRORS) {
- $this->errorcode_map[1022] = DB_ERROR_CONSTRAINT;
- $this->errorcode_map[1048] = DB_ERROR_CONSTRAINT_NOT_NULL;
- $this->errorcode_map[1062] = DB_ERROR_CONSTRAINT;
- } else {
- // Doing this in case mode changes during runtime.
- $this->errorcode_map[1022] = DB_ERROR_ALREADY_EXISTS;
- $this->errorcode_map[1048] = DB_ERROR_CONSTRAINT;
- $this->errorcode_map[1062] = DB_ERROR_ALREADY_EXISTS;
- }
- $errno = $this->errorCode(mysql_errno($this->connection));
- }
- return $this->raiseError($errno, null, null, null,
- @mysql_errno($this->connection) . ' ** ' .
- @mysql_error($this->connection));
- }
-
- // }}}
- // {{{ tableInfo()
-
- /**
- * Returns information about a table or a result set.
- *
- * @param object|string $result DB_result object from a query or a
- * string containing the name of a table
- * @param int $mode a valid tableInfo mode
- * @return array an associative array with the information requested
- * or an error object if something is wrong
- * @access public
- * @internal
- * @see DB_common::tableInfo()
- */
- function tableInfo($result, $mode = null) {
- if (isset($result->result)) {
- /*
- * Probably received a result object.
- * Extract the result resource identifier.
- */
- $id = $result->result;
- $got_string = false;
- } elseif (is_string($result)) {
- /*
- * Probably received a table name.
- * Create a result resource identifier.
- */
- $id = @mysql_list_fields($this->dsn['database'],
- $result, $this->connection);
- $got_string = true;
- } else {
- /*
- * Probably received a result resource identifier.
- * Copy it.
- * Deprecated. Here for compatibility only.
- */
- $id = $result;
- $got_string = false;
- }
-
- if (!is_resource($id)) {
- return $this->mysqlRaiseError(DB_ERROR_NEED_MORE_DATA);
- }
-
- if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) {
- $case_func = 'strtolower';
- } else {
- $case_func = 'strval';
- }
-
- $count = @mysql_num_fields($id);
-
- // made this IF due to performance (one if is faster than $count if's)
- if (!$mode) {
- for ($i=0; $i<$count; $i++) {
- $res[$i]['table'] = $case_func(@mysql_field_table($id, $i));
- $res[$i]['name'] = $case_func(@mysql_field_name($id, $i));
- $res[$i]['type'] = @mysql_field_type($id, $i);
- $res[$i]['len'] = @mysql_field_len($id, $i);
- $res[$i]['flags'] = @mysql_field_flags($id, $i);
- }
- } else { // full
- $res['num_fields']= $count;
-
- for ($i=0; $i<$count; $i++) {
- $res[$i]['table'] = $case_func(@mysql_field_table($id, $i));
- $res[$i]['name'] = $case_func(@mysql_field_name($id, $i));
- $res[$i]['type'] = @mysql_field_type($id, $i);
- $res[$i]['len'] = @mysql_field_len($id, $i);
- $res[$i]['flags'] = @mysql_field_flags($id, $i);
-
- if ($mode & DB_TABLEINFO_ORDER) {
- $res['order'][$res[$i]['name']] = $i;
- }
- if ($mode & DB_TABLEINFO_ORDERTABLE) {
- $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
- }
- }
- }
-
- // free the result only if we were called on a table
- if ($got_string) {
- @mysql_free_result($id);
- }
- return $res;
- }
-
- // }}}
- // {{{ getSpecialQuery()
-
- /**
- * Returns the query needed to get some backend info
- * @param string $type What kind of info you want to retrieve
- * @return string The SQL query string
- */
- function getSpecialQuery($type)
- {
- switch ($type) {
- case 'tables':
- return 'SHOW TABLES';
- case 'views':
- return DB_ERROR_NOT_CAPABLE;
- case 'users':
- $sql = 'select distinct User from user';
- if ($this->dsn['database'] != 'mysql') {
- $dsn = $this->dsn;
- $dsn['database'] = 'mysql';
- if (DB::isError($db = DB::connect($dsn))) {
- return $db;
- }
- $sql = $db->getCol($sql);
- $db->disconnect();
- // XXX Fixme the mysql driver should take care of this
- if (!@mysql_select_db($this->dsn['database'], $this->connection)) {
- return $this->mysqlRaiseError(DB_ERROR_NODBSELECTED);
- }
- }
- return $sql;
- case 'databases':
- return 'SHOW DATABASES';
- default:
- return null;
- }
- }
-
- // }}}
-
-}
-
-/*
- * Local variables:
- * tab-width: 4
- * c-basic-offset: 4
- * End:
- */
-
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 foldmethod=marker: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Chaillan Nicolas <nicos@php.net> |
-// | Based on mysql.php by Stig Bakken <ssb@php.net> |
-// | Maintainer: Daniel Convissor <danielc@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: mysqli.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
-
-
-// EXPERIMENTAL
-
-
-require_once 'DB/common.php';
-
-/**
- * Database independent query interface definition for PHP's mysqli
- * extension.
- *
- * This is for MySQL versions 4.1 and above. Requires PHP 5.
- *
- * Note that persistent connections no longer exist.
- *
- * @package DB
- * @version $Id: mysqli.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
- * @category Database
- * @author Chaillan Nicolas <nicos@php.net>
- */
-class DB_mysqli extends DB_common
-{
- // {{{ properties
-
- var $connection;
- var $phptype, $dbsyntax;
- var $prepare_tokens = array();
- var $prepare_types = array();
- var $num_rows = array();
- var $transaction_opcount = 0;
- var $autocommit = true;
- var $fetchmode = DB_FETCHMODE_ORDERED; /* Default fetch mode */
- var $_db = false;
-
- // }}}
- // {{{ constructor
-
- /**
- * DB_mysql constructor.
- *
- * @access public
- */
- function DB_mysqli()
- {
- $this->DB_common();
- $this->phptype = 'mysqli';
- $this->dbsyntax = 'mysqli';
- $this->features = array(
- 'prepare' => false,
- 'ssl' => true,
- 'transactions' => true,
- 'limit' => 'alter'
- );
- $this->errorcode_map = array(
- 1004 => DB_ERROR_CANNOT_CREATE,
- 1005 => DB_ERROR_CANNOT_CREATE,
- 1006 => DB_ERROR_CANNOT_CREATE,
- 1007 => DB_ERROR_ALREADY_EXISTS,
- 1008 => DB_ERROR_CANNOT_DROP,
- 1022 => DB_ERROR_ALREADY_EXISTS,
- 1046 => DB_ERROR_NODBSELECTED,
- 1050 => DB_ERROR_ALREADY_EXISTS,
- 1051 => DB_ERROR_NOSUCHTABLE,
- 1054 => DB_ERROR_NOSUCHFIELD,
- 1062 => DB_ERROR_ALREADY_EXISTS,
- 1064 => DB_ERROR_SYNTAX,
- 1100 => DB_ERROR_NOT_LOCKED,
- 1136 => DB_ERROR_VALUE_COUNT_ON_ROW,
- 1146 => DB_ERROR_NOSUCHTABLE,
- 1048 => DB_ERROR_CONSTRAINT,
- 1216 => DB_ERROR_CONSTRAINT,
- );
- }
-
- // }}}
- // {{{ connect()
-
- /**
- * Connect to a database and log in as the specified user.
- *
- * @param string $dsn the data source name (see DB::parseDSN for syntax)
- * @param boolean $persistent (optional) whether the connection should
- * be persistent
- * @return mixed DB_OK on success, a DB error on failure
- * @access public
- */
- function connect($dsninfo, $persistent = false)
- {
- if (!DB::assertExtension('mysqli')) {
- return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
- }
-
- $this->dsn = $dsninfo;
- if ($dsninfo['protocol'] && $dsninfo['protocol'] == 'unix') {
- $dbhost = ':' . $dsninfo['socket'];
- } else {
- $dbhost = $dsninfo['hostspec'] ? $dsninfo['hostspec'] : 'localhost';
- if ($dsninfo['port']) {
- $dbhost .= ':' . $dsninfo['port'];
- }
- }
-
- $ssl_mode = $this->getOption('ssl') === true ? 'CLIENT_SSL' : NULL;
-
- @ini_set('track_errors', true);
-
- if ($dbhost && $dsninfo['username'] && $dsninfo['password']) {
- // Need to verify if arguments are okay
- $conn = @mysqli_connect($dbhost, $dsninfo['username'],
- $dsninfo['password'], $ssl_mode);
- } elseif ($dbhost && isset($dsninfo['username'])) {
- $conn = @mysqli_connect($dbhost, $dsninfo['username'], null,
- $ssl_mode);
- } elseif ($dbhost) {
- $conn = @mysqli_connect($dbhost, null, null, $ssl_mode);
- } else {
- $conn = false;
- }
-
- @ini_restore('track_errors');
-
- if (!$conn) {
- if (($err = @mysqli_error()) != '') {
- return $this->raiseError(DB_ERROR_CONNECT_FAILED, null, null,
- null, $err);
- } elseif (empty($php_errormsg)) {
- return $this->raiseError(DB_ERROR_CONNECT_FAILED);
- } else {
- return $this->raiseError(DB_ERROR_CONNECT_FAILED, null, null,
- null, $php_errormsg);
- }
- }
-
- if ($dsninfo['database']) {
- if (!@mysqli_select_db($conn, $dsninfo['database'])) {
- switch(mysqli_errno($conn)) {
- case 1049:
- return $this->raiseError(DB_ERROR_NOSUCHDB, null, null,
- null, @mysqli_error($conn));
- case 1044:
- return $this->raiseError(DB_ERROR_ACCESS_VIOLATION, null, null,
- null, @mysqli_error($conn));
- default:
- return $this->raiseError(DB_ERROR, null, null,
- null, @mysqli_error($conn));
- }
- }
- // fix to allow calls to different databases in the same script
- $this->_db = $dsninfo['database'];
- }
-
- $this->connection = $conn;
- return DB_OK;
- }
-
- // }}}
- // {{{ disconnect()
-
- /**
- * Log out and disconnect from the database.
- *
- * @return boolean true on success, false if not connected
- * @access public
- */
- function disconnect()
- {
- $ret = @mysqli_close($this->connection);
- $this->connection = null;
- return $ret;
- }
-
- // }}}
- // {{{ simpleQuery()
-
- /**
- * Send a query to MySQL and return the results as a MySQL resource
- * identifier.
- *
- * @param string $query the SQL query
- * @return mixed a valid MySQL result for successful SELECT
- * queries, DB_OK for other successful queries.
- * A DB error is returned on failure.
- * @access public
- */
- function simpleQuery($query)
- {
- $ismanip = DB::isManip($query);
- $this->last_query = $query;
- $query = $this->modifyQuery($query);
- if ($this->_db) {
- if (!@mysqli_select_db($this->connection, $this->_db)) {
- return $this->mysqlRaiseError(DB_ERROR_NODBSELECTED);
- }
- }
- if (!$this->autocommit && $ismanip) {
- if ($this->transaction_opcount == 0) {
- $result = @mysqli_query($this->connection, 'SET AUTOCOMMIT=0');
- $result = @mysqli_query($this->connection, 'BEGIN');
- if (!$result) {
- return $this->mysqlRaiseError();
- }
- }
- $this->transaction_opcount++;
- }
- $result = @mysqli_query($this->connection, $query);
- if (!$result) {
- return $this->mysqlRaiseError();
- }
-# this next block is still sketchy..
- if (is_object($result)) {
- $numrows = $this->numrows($result);
- if (is_object($numrows)) {
- return $numrows;
- }
-# need to come up with different means for next line
-# since $result is object (int)$result won't fly...
- $this->num_rows[(int)$result] = $numrows;
- return $result;
- }
- return DB_OK;
- }
-
- // }}}
- // {{{ nextResult()
-
- /**
- * Move the internal mysql result pointer to the next available result.
- *
- * This method has not been implemented yet.
- *
- * @param resource $result a valid sql result resource
- * @return false
- * @access public
- */
- function nextResult($result)
- {
- return false;
- }
-
- // }}}
- // {{{ fetchInto()
-
- /**
- * Fetch a row and insert the data into an existing array.
- *
- * Formating of the array and the data therein are configurable.
- * See DB_result::fetchInto() for more information.
- *
- * @param resource $result query result identifier
- * @param array $arr (reference) array where data from the row
- * should be placed
- * @param int $fetchmode how the resulting array should be indexed
- * @param int $rownum the row number to fetch
- *
- * @return mixed DB_OK on success, null when end of result set is
- * reached or on failure
- *
- * @see DB_result::fetchInto()
- * @access private
- */
- function fetchInto($result, &$arr, $fetchmode, $rownum=null)
- {
- if ($rownum !== null) {
- if (!@mysqli_data_seek($result, $rownum)) {
- return null;
- }
- }
- if ($fetchmode & DB_FETCHMODE_ASSOC) {
- $arr = @mysqli_fetch_array($result, MYSQLI_ASSOC);
- if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE && $arr) {
- $arr = array_change_key_case($arr, CASE_LOWER);
- }
- } else {
- $arr = @mysqli_fetch_row($result);
- }
- if (!$arr) {
- $errno = @mysqli_errno($this->connection);
- if (!$errno) {
- return null;
- }
- return $this->mysqlRaiseError($errno);
- }
- if ($this->options['portability'] & DB_PORTABILITY_RTRIM) {
- /*
- * Even though this DBMS already trims output, we do this because
- * a field might have intentional whitespace at the end that
- * gets removed by DB_PORTABILITY_RTRIM under another driver.
- */
- $this->_rtrimArrayValues($arr);
- }
- if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) {
- $this->_convertNullArrayValuesToEmpty($arr);
- }
- return DB_OK;
- }
-
- // }}}
- // {{{ freeResult()
-
- /**
- * Free the internal resources associated with $result.
- *
- * @param resource $result MySQL result identifier
- * @return bool true on success, false if $result is invalid
- * @access public
- */
- function freeResult($result)
- {
-# need to come up with different means for next line
-# since $result is object (int)$result won't fly...
- unset($this->num_rows[(int)$result]);
- return @mysqli_free_result($result);
- }
-
- // }}}
- // {{{ numCols()
-
- /**
- * Get the number of columns in a result set.
- *
- * @param $result MySQL result identifier
- *
- * @access public
- *
- * @return int the number of columns per row in $result
- */
- function numCols($result)
- {
- $cols = @mysqli_num_fields($result);
-
- if (!$cols) {
- return $this->mysqlRaiseError();
- }
-
- return $cols;
- }
-
- // }}}
- // {{{ numRows()
-
- /**
- * Get the number of rows in a result set.
- *
- * @param resource $result MySQL result identifier
- * @return int the number of rows in $result
- * @access public
- */
- function numRows($result)
- {
- $rows = @mysqli_num_rows($result);
- if ($rows === null) {
- return $this->mysqlRaiseError();
- }
- return $rows;
- }
-
- // }}}
- // {{{ autoCommit()
-
- /**
- * Enable/disable automatic commits.
- */
- function autoCommit($onoff = false)
- {
- // XXX if $this->transaction_opcount > 0, we should probably
- // issue a warning here.
- $this->autocommit = $onoff ? true : false;
- return DB_OK;
- }
-
- // }}}
- // {{{ commit()
-
- /**
- * Commit the current transaction.
- */
- function commit()
- {
- if ($this->transaction_opcount > 0) {
- if ($this->_db) {
- if (!@mysqli_select_db($this->_db, $this->connection)) {
- return $this->mysqlRaiseError(DB_ERROR_NODBSELECTED);
- }
- }
- $result = @mysqli_query('COMMIT', $this->connection);
- $result = @mysqli_query('SET AUTOCOMMIT=1', $this->connection);
- $this->transaction_opcount = 0;
- if (!$result) {
- return $this->mysqlRaiseError();
- }
- }
- return DB_OK;
- }
-
- // }}}
- // {{{ rollback()
-
- /**
- * Roll back (undo) the current transaction.
- */
- function rollback()
- {
- if ($this->transaction_opcount > 0) {
- if ($this->_db) {
- if (!@mysqli_select_db($this->_db, $this->connection)) {
- return $this->mysqlRaiseError(DB_ERROR_NODBSELECTED);
- }
- }
- $result = @mysqli_query('ROLLBACK', $this->connection);
- $result = @mysqli_query('SET AUTOCOMMIT=1', $this->connection);
- $this->transaction_opcount = 0;
- if (!$result) {
- return $this->mysqlRaiseError();
- }
- }
- return DB_OK;
- }
-
- // }}}
- // {{{ affectedRows()
-
- /**
- * Gets the number of rows affected by the data manipulation
- * query. For other queries, this function returns 0.
- *
- * @return integer number of rows affected by the last query
- */
- function affectedRows()
- {
- if (DB::isManip($this->last_query)) {
- return @mysqli_affected_rows($this->connection);
- } else {
- return 0;
- }
- }
-
- // }}}
- // {{{ errorNative()
-
- /**
- * Get the native error code of the last error (if any) that
- * occured on the current connection.
- *
- * @return int native MySQL error code
- * @access public
- */
- function errorNative()
- {
- return @mysqli_errno($this->connection);
- }
-
- // }}}
- // {{{ nextId()
-
- /**
- * Returns the next free id in a sequence
- *
- * @param string $seq_name name of the sequence
- * @param boolean $ondemand when true, the seqence is automatically
- * created if it does not exist
- *
- * @return int the next id number in the sequence. DB_Error if problem.
- *
- * @internal
- * @see DB_common::nextID()
- * @access public
- */
- function nextId($seq_name, $ondemand = true)
- {
- $seqname = $this->getSequenceName($seq_name);
- do {
- $repeat = 0;
- $this->pushErrorHandling(PEAR_ERROR_RETURN);
- $result = $this->query("UPDATE ${seqname} ".
- 'SET id=LAST_INSERT_ID(id+1)');
- $this->popErrorHandling();
- if ($result === DB_OK) {
- /** COMMON CASE **/
- $id = @mysqli_insert_id($this->connection);
- if ($id != 0) {
- return $id;
- }
- /** EMPTY SEQ TABLE **/
- // Sequence table must be empty for some reason, so fill it and return 1
- // Obtain a user-level lock
- $result = $this->getOne("SELECT GET_LOCK('${seqname}_lock',10)");
- if (DB::isError($result)) {
- return $this->raiseError($result);
- }
- if ($result == 0) {
- // Failed to get the lock, bail with a DB_ERROR_NOT_LOCKED error
- return $this->mysqlRaiseError(DB_ERROR_NOT_LOCKED);
- }
-
- // add the default value
- $result = $this->query("REPLACE INTO ${seqname} VALUES (0)");
- if (DB::isError($result)) {
- return $this->raiseError($result);
- }
-
- // Release the lock
- $result = $this->getOne("SELECT RELEASE_LOCK('${seqname}_lock')");
- if (DB::isError($result)) {
- return $this->raiseError($result);
- }
- // We know what the result will be, so no need to try again
- return 1;
-
- /** ONDEMAND TABLE CREATION **/
- } elseif ($ondemand && DB::isError($result) &&
- $result->getCode() == DB_ERROR_NOSUCHTABLE)
- {
- $result = $this->createSequence($seq_name);
- // Since createSequence initializes the ID to be 1,
- // we do not need to retrieve the ID again (or we will get 2)
- if (DB::isError($result)) {
- return $this->raiseError($result);
- } else {
- // First ID of a newly created sequence is 1
- return 1;
- }
-
- /** BACKWARDS COMPAT **/
- } elseif (DB::isError($result) &&
- $result->getCode() == DB_ERROR_ALREADY_EXISTS)
- {
- // see _BCsequence() comment
- $result = $this->_BCsequence($seqname);
- if (DB::isError($result)) {
- return $this->raiseError($result);
- }
- $repeat = 1;
- }
- } while ($repeat);
-
- return $this->raiseError($result);
- }
-
- /**
- * Creates a new sequence
- *
- * @param string $seq_name name of the new sequence
- *
- * @return int DB_OK on success. A DB_Error object is returned if
- * problems arise.
- *
- * @internal
- * @see DB_common::createSequence()
- * @access public
- */
- function createSequence($seq_name)
- {
- $seqname = $this->getSequenceName($seq_name);
- $res = $this->query("CREATE TABLE ${seqname} ".
- '(id INTEGER UNSIGNED AUTO_INCREMENT NOT NULL,'.
- ' PRIMARY KEY(id))');
- if (DB::isError($res)) {
- return $res;
- }
- // insert yields value 1, nextId call will generate ID 2
- return $this->query("INSERT INTO ${seqname} VALUES(0)");
- }
-
- // }}}
- // {{{ dropSequence()
-
- /**
- * Deletes a sequence
- *
- * @param string $seq_name name of the sequence to be deleted
- *
- * @return int DB_OK on success. DB_Error if problems.
- *
- * @internal
- * @see DB_common::dropSequence()
- * @access public
- */
- function dropSequence($seq_name)
- {
- return $this->query('DROP TABLE ' . $this->getSequenceName($seq_name));
- }
-
- // }}}
- // {{{ _BCsequence()
-
- /**
- * Backwards compatibility with old sequence emulation implementation
- * (clean up the dupes).
- *
- * @param string $seqname The sequence name to clean up
- * @return mixed DB_Error or true
- */
- function _BCsequence($seqname)
- {
- // Obtain a user-level lock... this will release any previous
- // application locks, but unlike LOCK TABLES, it does not abort
- // the current transaction and is much less frequently used.
- $result = $this->getOne("SELECT GET_LOCK('${seqname}_lock',10)");
- if (DB::isError($result)) {
- return $result;
- }
- if ($result == 0) {
- // Failed to get the lock, can't do the conversion, bail
- // with a DB_ERROR_NOT_LOCKED error
- return $this->mysqlRaiseError(DB_ERROR_NOT_LOCKED);
- }
-
- $highest_id = $this->getOne("SELECT MAX(id) FROM ${seqname}");
- if (DB::isError($highest_id)) {
- return $highest_id;
- }
- // This should kill all rows except the highest
- // We should probably do something if $highest_id isn't
- // numeric, but I'm at a loss as how to handle that...
- $result = $this->query("DELETE FROM ${seqname} WHERE id <> $highest_id");
- if (DB::isError($result)) {
- return $result;
- }
-
- // If another thread has been waiting for this lock,
- // it will go thru the above procedure, but will have no
- // real effect
- $result = $this->getOne("SELECT RELEASE_LOCK('${seqname}_lock')");
- if (DB::isError($result)) {
- return $result;
- }
- return true;
- }
-
- // }}}
- // {{{ quoteIdentifier()
-
- /**
- * Quote a string so it can be safely used as a table or column name
- *
- * Quoting style depends on which database driver is being used.
- *
- * MySQL can't handle the backtick character (<kbd>`</kbd>) in
- * table or column names.
- *
- * @param string $str identifier name to be quoted
- *
- * @return string quoted identifier string
- *
- * @since 1.6.0
- * @access public
- * @internal
- */
- function quoteIdentifier($str)
- {
- return '`' . $str . '`';
- }
-
- // }}}
- // {{{ escapeSimple()
-
- /**
- * Escape a string according to the current DBMS's standards
- *
- * @param string $str the string to be escaped
- *
- * @return string the escaped string
- *
- * @internal
- */
- function escapeSimple($str) {
- return @mysqli_real_escape_string($str, $this->connection);
- }
-
- // }}}
- // {{{ modifyQuery()
-
- function modifyQuery($query)
- {
- if ($this->options['portability'] & DB_PORTABILITY_DELETE_COUNT) {
- // "DELETE FROM table" gives 0 affected rows in MySQL.
- // This little hack lets you know how many rows were deleted.
- if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $query)) {
- $query = preg_replace('/^\s*DELETE\s+FROM\s+(\S+)\s*$/',
- 'DELETE FROM \1 WHERE 1=1', $query);
- }
- }
- return $query;
- }
-
- // }}}
- // {{{ modifyLimitQuery()
-
- function modifyLimitQuery($query, $from, $count, $params = array())
- {
- if (DB::isManip($query)) {
- return $query . " LIMIT $count";
- } else {
- return $query . " LIMIT $from, $count";
- }
- }
-
- // }}}
- // {{{ mysqlRaiseError()
-
- /**
- * Gather information about an error, then use that info to create a
- * DB error object and finally return that object.
- *
- * @param integer $errno PEAR error number (usually a DB constant) if
- * manually raising an error
- * @return object DB error object
- * @see DB_common::errorCode()
- * @see DB_common::raiseError()
- */
- function mysqlRaiseError($errno = null)
- {
- if ($errno === null) {
- if ($this->options['portability'] & DB_PORTABILITY_ERRORS) {
- $this->errorcode_map[1022] = DB_ERROR_CONSTRAINT;
- $this->errorcode_map[1048] = DB_ERROR_CONSTRAINT_NOT_NULL;
- $this->errorcode_map[1062] = DB_ERROR_CONSTRAINT;
- } else {
- // Doing this in case mode changes during runtime.
- $this->errorcode_map[1022] = DB_ERROR_ALREADY_EXISTS;
- $this->errorcode_map[1048] = DB_ERROR_CONSTRAINT;
- $this->errorcode_map[1062] = DB_ERROR_ALREADY_EXISTS;
- }
- $errno = $this->errorCode(mysqli_errno($this->connection));
- }
- return $this->raiseError($errno, null, null, null,
- @mysqli_errno($this->connection) . ' ** ' .
- @mysqli_error($this->connection));
- }
-
- // }}}
- // {{{ tableInfo()
-
- /**
- * Returns information about a table or a result set.
- *
- * WARNING: this method will probably not work because the mysqli_*()
- * functions it relies upon may not exist.
- *
- * @param object|string $result DB_result object from a query or a
- * string containing the name of a table
- * @param int $mode a valid tableInfo mode
- * @return array an associative array with the information requested
- * or an error object if something is wrong
- * @access public
- * @internal
- * @see DB_common::tableInfo()
- */
- function tableInfo($result, $mode = null) {
- if (isset($result->result)) {
- /*
- * Probably received a result object.
- * Extract the result resource identifier.
- */
- $id = $result->result;
- $got_string = false;
- } elseif (is_string($result)) {
- /*
- * Probably received a table name.
- * Create a result resource identifier.
- */
- $id = @mysqli_list_fields($this->dsn['database'],
- $result, $this->connection);
- $got_string = true;
- } else {
- /*
- * Probably received a result resource identifier.
- * Copy it.
- * Depricated. Here for compatibility only.
- */
- $id = $result;
- $got_string = false;
- }
-
- if (!is_resource($id)) {
- return $this->mysqlRaiseError(DB_ERROR_NEED_MORE_DATA);
- }
-
- if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) {
- $case_func = 'strtolower';
- } else {
- $case_func = 'strval';
- }
-
- $count = @mysqli_num_fields($id);
-
- // made this IF due to performance (one if is faster than $count if's)
- if (!$mode) {
- for ($i=0; $i<$count; $i++) {
- $tmp = @mysqli_fetch_field($id);
- $res[$i]['table'] = $case_func($tmp->table);
- $res[$i]['name'] = $case_func($tmp->name);
- $res[$i]['type'] = $tmp->type;
- $res[$i]['len'] = $tmp->max_length;
-
- $res[$i]['flags'] = '';
- if ($tmp->flags & MYSQLI_NOT_NULL_FLAG) {
- $res[$i]['flags'] .= 'not_null ';
- }
- if ($tmp->flags & MYSQLI_PRI_KEY_FLAG) {
- $res[$i]['flags'] .= 'primary_key ';
- }
- if ($tmp->flags & MYSQLI_UNIQUE_KEY_FLAG) {
- $res[$i]['flags'] .= 'unique_key ';
- }
- if ($tmp->flags & MYSQLI_MULTIPLE_KEY_FLAG) {
- $res[$i]['flags'] .= 'multiple_key ';
- }
- if ($tmp->flags & MYSQLI_BLOB_FLAG) {
- $res[$i]['flags'] .= 'blob ';
- }
- if ($tmp->def) {
- $res[$i]['flags'] .= 'default_' . rawurlencode($tmp->def);
- }
- $res[$i]['flags'] = trim($res[$i]['flags']);
- }
- } else { // full
- $res['num_fields']= $count;
-
- for ($i=0; $i<$count; $i++) {
- $tmp = @mysqli_fetch_field($id);
- $res[$i]['table'] = $case_func($tmp->table);
- $res[$i]['name'] = $case_func($tmp->name);
- $res[$i]['type'] = $tmp->type;
- $res[$i]['len'] = $tmp->max_length;
-
- $res[$i]['flags'] = '';
- if ($tmp->flags & MYSQLI_NOT_NULL_FLAG) {
- $res[$i]['flags'] .= 'not_null ';
- }
- if ($tmp->flags & MYSQLI_PRI_KEY_FLAG) {
- $res[$i]['flags'] .= 'primary_key ';
- }
- if ($tmp->flags & MYSQLI_UNIQUE_KEY_FLAG) {
- $res[$i]['flags'] .= 'unique_key ';
- }
- if ($tmp->flags & MYSQLI_MULTIPLE_KEY_FLAG) {
- $res[$i]['flags'] .= 'multiple_key ';
- }
- if ($tmp->flags & MYSQLI_BLOB_FLAG) {
- $res[$i]['flags'] .= 'blob ';
- }
- if ($tmp->def) {
- $res[$i]['flags'] .= 'default_' . rawurlencode($tmp->def);
- }
- $res[$i]['flags'] = trim($res[$i]['flags']);
-
- if ($mode & DB_TABLEINFO_ORDER) {
- $res['order'][$res[$i]['name']] = $i;
- }
- if ($mode & DB_TABLEINFO_ORDERTABLE) {
- $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
- }
- }
- }
-
- // free the result only if we were called on a table
- if ($got_string) {
- @mysqli_free_result($id);
- }
- return $res;
- }
-
- // }}}
- // {{{ getSpecialQuery()
-
- /**
- * Returns the query needed to get some backend info.
- *
- * @param string $type What kind of info you want to retrieve
- * @return string The SQL query string
- */
- function getSpecialQuery($type)
- {
- switch ($type) {
- case 'tables':
- return 'SHOW TABLES';
- case 'views':
- return DB_ERROR_NOT_CAPABLE;
- case 'users':
- $sql = 'select distinct User from user';
- if ($this->dsn['database'] != 'mysql') {
- $dsn = $this->dsn;
- $dsn['database'] = 'mysql';
- if (DB::isError($db = DB::connect($dsn))) {
- return $db;
- }
- $sql = $db->getCol($sql);
- $db->disconnect();
- // XXX Fixme the mysql driver should take care of this
- if (!@mysqli_select_db($this->connection, $this->dsn['database'])) {
- return $this->mysqlRaiseError(DB_ERROR_NODBSELECTED);
- }
- }
- return $sql;
- case 'databases':
- return 'SHOW DATABASES';
- default:
- return null;
- }
- }
-
- // }}}
-
-}
-
-/*
- * Local variables:
- * tab-width: 4
- * c-basic-offset: 4
- * End:
- */
-
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 foldmethod=marker: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: James L. Pine <jlp@valinux.com> |
-// | Maintainer: Daniel Convissor <danielc@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: oci8.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
-
-
-// be aware... OCIError() only appears to return anything when given a
-// statement, so functions return the generic DB_ERROR instead of more
-// useful errors that have to do with feedback from the database.
-
-
-require_once 'DB/common.php';
-
-/**
- * Database independent query interface definition for PHP's Oracle 8
- * call-interface extension.
- *
- * Definitely works with versions 8 and 9 of Oracle.
- *
- * @package DB
- * @version $Id: oci8.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
- * @category Database
- * @author James L. Pine <jlp@valinux.com>
- */
-class DB_oci8 extends DB_common
-{
- // {{{ properties
-
- var $connection;
- var $phptype, $dbsyntax;
- var $manip_query = array();
- var $prepare_types = array();
- var $autoCommit = 1;
- var $last_stmt = false;
-
- /**
- * stores the $data passed to execute() in the oci8 driver
- *
- * Gets reset to array() when simpleQuery() is run.
- *
- * Needed in case user wants to call numRows() after prepare/execute
- * was used.
- *
- * @var array
- * @access private
- */
- var $_data = array();
-
- // }}}
- // {{{ constructor
-
- function DB_oci8()
- {
- $this->DB_common();
- $this->phptype = 'oci8';
- $this->dbsyntax = 'oci8';
- $this->features = array(
- 'prepare' => false,
- 'pconnect' => true,
- 'transactions' => true,
- 'limit' => 'alter'
- );
- $this->errorcode_map = array(
- 1 => DB_ERROR_CONSTRAINT,
- 900 => DB_ERROR_SYNTAX,
- 904 => DB_ERROR_NOSUCHFIELD,
- 921 => DB_ERROR_SYNTAX,
- 923 => DB_ERROR_SYNTAX,
- 942 => DB_ERROR_NOSUCHTABLE,
- 955 => DB_ERROR_ALREADY_EXISTS,
- 1400 => DB_ERROR_CONSTRAINT_NOT_NULL,
- 1407 => DB_ERROR_CONSTRAINT_NOT_NULL,
- 1476 => DB_ERROR_DIVZERO,
- 1722 => DB_ERROR_INVALID_NUMBER,
- 2289 => DB_ERROR_NOSUCHTABLE,
- 2291 => DB_ERROR_CONSTRAINT,
- 2449 => DB_ERROR_CONSTRAINT,
- );
- }
-
- // }}}
- // {{{ connect()
-
- /**
- * Connect to a database and log in as the specified user.
- *
- * @param $dsn the data source name (see DB::parseDSN for syntax)
- * @param $persistent (optional) whether the connection should
- * be persistent
- *
- * @return int DB_OK on success, a DB error code on failure
- */
- function connect($dsninfo, $persistent = false)
- {
- if (!DB::assertExtension('oci8')) {
- return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
- }
- $this->dsn = $dsninfo;
-
- $connect_function = $persistent ? 'OCIPLogon' : 'OCILogon';
-
- if ($dsninfo['hostspec']) {
- $conn = @$connect_function($dsninfo['username'],
- $dsninfo['password'],
- $dsninfo['hostspec']);
- } elseif ($dsninfo['username'] || $dsninfo['password']) {
- $conn = @$connect_function($dsninfo['username'],
- $dsninfo['password']);
- } else {
- $conn = false;
- }
- if ($conn == false) {
- $error = OCIError();
- $error = (is_array($error)) ? $error['message'] : null;
- return $this->raiseError(DB_ERROR_CONNECT_FAILED, null, null,
- null, $error);
- }
- $this->connection = $conn;
- return DB_OK;
- }
-
- // }}}
- // {{{ disconnect()
-
- /**
- * Log out and disconnect from the database.
- *
- * @return bool true on success, false if not connected.
- */
- function disconnect()
- {
- $ret = @OCILogOff($this->connection);
- $this->connection = null;
- return $ret;
- }
-
- // }}}
- // {{{ simpleQuery()
-
- /**
- * Send a query to oracle and return the results as an oci8 resource
- * identifier.
- *
- * @param $query the SQL query
- *
- * @return int returns a valid oci8 result for successful SELECT
- * queries, DB_OK for other successful queries. A DB error code
- * is returned on failure.
- */
- function simpleQuery($query)
- {
- $this->_data = array();
- $this->last_query = $query;
- $query = $this->modifyQuery($query);
- $result = @OCIParse($this->connection, $query);
- if (!$result) {
- return $this->oci8RaiseError();
- }
- if ($this->autoCommit) {
- $success = @OCIExecute($result,OCI_COMMIT_ON_SUCCESS);
- } else {
- $success = @OCIExecute($result,OCI_DEFAULT);
- }
- if (!$success) {
- return $this->oci8RaiseError($result);
- }
- $this->last_stmt=$result;
- // Determine which queries that should return data, and which
- // should return an error code only.
- return DB::isManip($query) ? DB_OK : $result;
- }
-
- // }}}
- // {{{ nextResult()
-
- /**
- * Move the internal oracle result pointer to the next available result
- *
- * @param a valid oci8 result resource
- *
- * @access public
- *
- * @return true if a result is available otherwise return false
- */
- function nextResult($result)
- {
- return false;
- }
-
- // }}}
- // {{{ fetchInto()
-
- /**
- * Fetch a row and insert the data into an existing array.
- *
- * Formating of the array and the data therein are configurable.
- * See DB_result::fetchInto() for more information.
- *
- * @param resource $result query result identifier
- * @param array $arr (reference) array where data from the row
- * should be placed
- * @param int $fetchmode how the resulting array should be indexed
- * @param int $rownum the row number to fetch
- *
- * @return mixed DB_OK on success, null when end of result set is
- * reached or on failure
- *
- * @see DB_result::fetchInto()
- * @access private
- */
- function fetchInto($result, &$arr, $fetchmode, $rownum=null)
- {
- if ($rownum !== null) {
- return $this->raiseError(DB_ERROR_NOT_CAPABLE);
- }
- if ($fetchmode & DB_FETCHMODE_ASSOC) {
- $moredata = @OCIFetchInto($result,$arr,OCI_ASSOC+OCI_RETURN_NULLS+OCI_RETURN_LOBS);
- if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE &&
- $moredata)
- {
- $arr = array_change_key_case($arr, CASE_LOWER);
- }
- } else {
- $moredata = OCIFetchInto($result,$arr,OCI_RETURN_NULLS+OCI_RETURN_LOBS);
- }
- if (!$moredata) {
- return null;
- }
- if ($this->options['portability'] & DB_PORTABILITY_RTRIM) {
- $this->_rtrimArrayValues($arr);
- }
- if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) {
- $this->_convertNullArrayValuesToEmpty($arr);
- }
- return DB_OK;
- }
-
- // }}}
- // {{{ freeResult()
-
- /**
- * Free the internal resources associated with $result.
- *
- * @param $result oci8 result identifier
- *
- * @return bool true on success, false if $result is invalid
- */
- function freeResult($result)
- {
- return @OCIFreeStatement($result);
- }
-
- /**
- * Free the internal resources associated with a prepared query.
- *
- * @param $stmt oci8 statement identifier
- *
- * @return bool true on success, false if $result is invalid
- */
- function freePrepared($stmt)
- {
- if (isset($this->prepare_types[(int)$stmt])) {
- unset($this->prepare_types[(int)$stmt]);
- unset($this->manip_query[(int)$stmt]);
- } else {
- return false;
- }
- return true;
- }
-
- // }}}
- // {{{ numRows()
-
- function numRows($result)
- {
- // emulate numRows for Oracle. yuck.
- if ($this->options['portability'] & DB_PORTABILITY_NUMROWS &&
- $result === $this->last_stmt)
- {
- $countquery = 'SELECT COUNT(*) FROM ('.$this->last_query.')';
- $save_query = $this->last_query;
- $save_stmt = $this->last_stmt;
-
- if (count($this->_data)) {
- $smt = $this->prepare('SELECT COUNT(*) FROM ('.$this->last_query.')');
- $count = $this->execute($smt, $this->_data);
- } else {
- $count =& $this->query($countquery);
- }
-
- if (DB::isError($count) ||
- DB::isError($row = $count->fetchRow(DB_FETCHMODE_ORDERED)))
- {
- $this->last_query = $save_query;
- $this->last_stmt = $save_stmt;
- return $this->raiseError(DB_ERROR_NOT_CAPABLE);
- }
- return $row[0];
- }
- return $this->raiseError(DB_ERROR_NOT_CAPABLE);
- }
-
- // }}}
- // {{{ numCols()
-
- /**
- * Get the number of columns in a result set.
- *
- * @param $result oci8 result identifier
- *
- * @return int the number of columns per row in $result
- */
- function numCols($result)
- {
- $cols = @OCINumCols($result);
- if (!$cols) {
- return $this->oci8RaiseError($result);
- }
- return $cols;
- }
-
- // }}}
- // {{{ errorNative()
-
- /**
- * Get the native error code of the last error (if any) that occured
- * on the current connection. This does not work, as OCIError does
- * not work unless given a statement. If OCIError does return
- * something, so will this.
- *
- * @return int native oci8 error code
- */
- function errorNative()
- {
- if (is_resource($this->last_stmt)) {
- $error = @OCIError($this->last_stmt);
- } else {
- $error = @OCIError($this->connection);
- }
- if (is_array($error)) {
- return $error['code'];
- }
- return false;
- }
-
- // }}}
- // {{{ prepare()
-
- /**
- * Prepares a query for multiple execution with execute().
- *
- * With oci8, this is emulated.
- *
- * prepare() requires a generic query as string like <code>
- * INSERT INTO numbers VALUES (?, ?, ?)
- * </code>. The <kbd>?</kbd> characters are placeholders.
- *
- * Three types of placeholders can be used:
- * + <kbd>?</kbd> a quoted scalar value, i.e. strings, integers
- * + <kbd>!</kbd> value is inserted 'as is'
- * + <kbd>&</kbd> requires a file name. The file's contents get
- * inserted into the query (i.e. saving binary
- * data in a db)
- *
- * Use backslashes to escape placeholder characters if you don't want
- * them to be interpreted as placeholders. Example: <code>
- * "UPDATE foo SET col=? WHERE col='over \& under'"
- * </code>
- *
- * @param string $query query to be prepared
- * @return mixed DB statement resource on success. DB_Error on failure.
- */
- function prepare($query)
- {
- $tokens = preg_split('/((?<!\\\)[&?!])/', $query, -1,
- PREG_SPLIT_DELIM_CAPTURE);
- $binds = count($tokens) - 1;
- $token = 0;
- $types = array();
- $newquery = '';
-
- foreach ($tokens as $key => $val) {
- switch ($val) {
- case '?':
- $types[$token++] = DB_PARAM_SCALAR;
- unset($tokens[$key]);
- break;
- case '&':
- $types[$token++] = DB_PARAM_OPAQUE;
- unset($tokens[$key]);
- break;
- case '!':
- $types[$token++] = DB_PARAM_MISC;
- unset($tokens[$key]);
- break;
- default:
- $tokens[$key] = preg_replace('/\\\([&?!])/', "\\1", $val);
- if ($key != $binds) {
- $newquery .= $tokens[$key] . ':bind' . $token;
- } else {
- $newquery .= $tokens[$key];
- }
- }
- }
-
- $this->last_query = $query;
- $newquery = $this->modifyQuery($newquery);
- if (!$stmt = @OCIParse($this->connection, $newquery)) {
- return $this->oci8RaiseError();
- }
- $this->prepare_types[$stmt] = $types;
- $this->manip_query[(int)$stmt] = DB::isManip($query);
- return $stmt;
- }
-
- // }}}
- // {{{ execute()
-
- /**
- * Executes a DB statement prepared with prepare().
- *
- * @param resource $stmt a DB statement resource returned from prepare()
- * @param mixed $data array, string or numeric data to be used in
- * execution of the statement. Quantity of items
- * passed must match quantity of placeholders in
- * query: meaning 1 for non-array items or the
- * quantity of elements in the array.
- * @return int returns an oci8 result resource for successful
- * SELECT queries, DB_OK for other successful queries. A DB error
- * code is returned on failure.
- * @see DB_oci::prepare()
- */
- function &execute($stmt, $data = array())
- {
- if (!is_array($data)) {
- $data = array($data);
- }
-
- $this->_data = $data;
-
- $types =& $this->prepare_types[$stmt];
- if (count($types) != count($data)) {
- $tmp =& $this->raiseError(DB_ERROR_MISMATCH);
- return $tmp;
- }
-
- $i = 0;
- foreach ($data as $key => $value) {
- if ($types[$i] == DB_PARAM_MISC) {
- /*
- * Oracle doesn't seem to have the ability to pass a
- * parameter along unchanged, so strip off quotes from start
- * and end, plus turn two single quotes to one single quote,
- * in order to avoid the quotes getting escaped by
- * Oracle and ending up in the database.
- */
- $data[$key] = preg_replace("/^'(.*)'$/", "\\1", $data[$key]);
- $data[$key] = str_replace("''", "'", $data[$key]);
- } elseif ($types[$i] == DB_PARAM_OPAQUE) {
- $fp = @fopen($data[$key], 'rb');
- if (!$fp) {
- $tmp =& $this->raiseError(DB_ERROR_ACCESS_VIOLATION);
- return $tmp;
- }
- $data[$key] = fread($fp, filesize($data[$key]));
- fclose($fp);
- }
- if (!@OCIBindByName($stmt, ':bind' . $i, $data[$key], -1)) {
- $tmp = $this->oci8RaiseError($stmt);
- return $tmp;
- }
- $i++;
- }
- if ($this->autoCommit) {
- $success = @OCIExecute($stmt, OCI_COMMIT_ON_SUCCESS);
- } else {
- $success = @OCIExecute($stmt, OCI_DEFAULT);
- }
- if (!$success) {
- $tmp = $this->oci8RaiseError($stmt);
- return $tmp;
- }
- $this->last_stmt = $stmt;
- if ($this->manip_query[(int)$stmt]) {
- $tmp = DB_OK;
- } else {
- $tmp =& new DB_result($this, $stmt);
- }
- return $tmp;
- }
-
- // }}}
- // {{{ autoCommit()
-
- /**
- * Enable/disable automatic commits
- *
- * @param $onoff true/false whether to autocommit
- */
- function autoCommit($onoff = false)
- {
- $this->autoCommit = (bool)$onoff;;
- return DB_OK;
- }
-
- // }}}
- // {{{ commit()
-
- /**
- * Commit transactions on the current connection
- *
- * @return DB_ERROR or DB_OK
- */
- function commit()
- {
- $result = @OCICommit($this->connection);
- if (!$result) {
- return $this->oci8RaiseError();
- }
- return DB_OK;
- }
-
- // }}}
- // {{{ rollback()
-
- /**
- * Roll back all uncommitted transactions on the current connection.
- *
- * @return DB_ERROR or DB_OK
- */
- function rollback()
- {
- $result = @OCIRollback($this->connection);
- if (!$result) {
- return $this->oci8RaiseError();
- }
- return DB_OK;
- }
-
- // }}}
- // {{{ affectedRows()
-
- /**
- * Gets the number of rows affected by the last query.
- * if the last query was a select, returns 0.
- *
- * @return number of rows affected by the last query or DB_ERROR
- */
- function affectedRows()
- {
- if ($this->last_stmt === false) {
- return $this->oci8RaiseError();
- }
- $result = @OCIRowCount($this->last_stmt);
- if ($result === false) {
- return $this->oci8RaiseError($this->last_stmt);
- }
- return $result;
- }
-
- // }}}
- // {{{ modifyQuery()
-
- function modifyQuery($query)
- {
- // "SELECT 2+2" must be "SELECT 2+2 FROM dual" in Oracle
- if (preg_match('/^\s*SELECT/i', $query) &&
- !preg_match('/\sFROM\s/i', $query)) {
- $query .= ' FROM dual';
- }
- return $query;
- }
-
- // }}}
- // {{{ modifyLimitQuery()
-
- /**
- * Emulate the row limit support altering the query
- *
- * @param string $query The query to treat
- * @param int $from The row to start to fetch from
- * @param int $count The offset
- * @return string The modified query
- *
- * @author Tomas V.V.Cox <cox@idecnet.com>
- */
- function modifyLimitQuery($query, $from, $count, $params = array())
- {
- // Let Oracle return the name of the columns instead of
- // coding a "home" SQL parser
-
- if (count($params)) {
- $result = $this->prepare("SELECT * FROM ($query) "
- . 'WHERE NULL = NULL');
- $tmp =& $this->execute($result, $params);
- } else {
- $q_fields = "SELECT * FROM ($query) WHERE NULL = NULL";
-
- if (!$result = @OCIParse($this->connection, $q_fields)) {
- $this->last_query = $q_fields;
- return $this->oci8RaiseError();
- }
- if (!@OCIExecute($result, OCI_DEFAULT)) {
- $this->last_query = $q_fields;
- return $this->oci8RaiseError($result);
- }
- }
-
- $ncols = OCINumCols($result);
- $cols = array();
- for ( $i = 1; $i <= $ncols; $i++ ) {
- $cols[] = '"' . OCIColumnName($result, $i) . '"';
- }
- $fields = implode(', ', $cols);
- // XXX Test that (tip by John Lim)
- //if (preg_match('/^\s*SELECT\s+/is', $query, $match)) {
- // // Introduce the FIRST_ROWS Oracle query optimizer
- // $query = substr($query, strlen($match[0]), strlen($query));
- // $query = "SELECT /* +FIRST_ROWS */ " . $query;
- //}
-
- // Construct the query
- // more at: http://marc.theaimsgroup.com/?l=php-db&m=99831958101212&w=2
- // Perhaps this could be optimized with the use of Unions
- $query = "SELECT $fields FROM".
- " (SELECT rownum as linenum, $fields FROM".
- " ($query)".
- ' WHERE rownum <= '. ($from + $count) .
- ') WHERE linenum >= ' . ++$from;
- return $query;
- }
-
- // }}}
- // {{{ nextId()
-
- /**
- * Returns the next free id in a sequence
- *
- * @param string $seq_name name of the sequence
- * @param boolean $ondemand when true, the seqence is automatically
- * created if it does not exist
- *
- * @return int the next id number in the sequence. DB_Error if problem.
- *
- * @internal
- * @see DB_common::nextID()
- * @access public
- */
- function nextId($seq_name, $ondemand = true)
- {
- $seqname = $this->getSequenceName($seq_name);
- $repeat = 0;
- do {
- $this->expectError(DB_ERROR_NOSUCHTABLE);
- $result =& $this->query("SELECT ${seqname}.nextval FROM dual");
- $this->popExpect();
- if ($ondemand && DB::isError($result) &&
- $result->getCode() == DB_ERROR_NOSUCHTABLE) {
- $repeat = 1;
- $result = $this->createSequence($seq_name);
- if (DB::isError($result)) {
- return $this->raiseError($result);
- }
- } else {
- $repeat = 0;
- }
- } while ($repeat);
- if (DB::isError($result)) {
- return $this->raiseError($result);
- }
- $arr = $result->fetchRow(DB_FETCHMODE_ORDERED);
- return $arr[0];
- }
-
- /**
- * Creates a new sequence
- *
- * @param string $seq_name name of the new sequence
- *
- * @return int DB_OK on success. A DB_Error object is returned if
- * problems arise.
- *
- * @internal
- * @see DB_common::createSequence()
- * @access public
- */
- function createSequence($seq_name)
- {
- $seqname = $this->getSequenceName($seq_name);
- return $this->query("CREATE SEQUENCE ${seqname}");
- }
-
- // }}}
- // {{{ dropSequence()
-
- /**
- * Deletes a sequence
- *
- * @param string $seq_name name of the sequence to be deleted
- *
- * @return int DB_OK on success. DB_Error if problems.
- *
- * @internal
- * @see DB_common::dropSequence()
- * @access public
- */
- function dropSequence($seq_name)
- {
- $seqname = $this->getSequenceName($seq_name);
- return $this->query("DROP SEQUENCE ${seqname}");
- }
-
- // }}}
- // {{{ oci8RaiseError()
-
- /**
- * Gather information about an error, then use that info to create a
- * DB error object and finally return that object.
- *
- * @param integer $errno PEAR error number (usually a DB constant) if
- * manually raising an error
- * @return object DB error object
- * @see DB_common::errorCode()
- * @see DB_common::raiseError()
- */
- function oci8RaiseError($errno = null)
- {
- if ($errno === null) {
- $error = @OCIError($this->connection);
- return $this->raiseError($this->errorCode($error['code']),
- null, null, null, $error['message']);
- } elseif (is_resource($errno)) {
- $error = @OCIError($errno);
- return $this->raiseError($this->errorCode($error['code']),
- null, null, null, $error['message']);
- }
- return $this->raiseError($this->errorCode($errno));
- }
-
- // }}}
- // {{{ getSpecialQuery()
-
- /**
- * Returns the query needed to get some backend info
- * @param string $type What kind of info you want to retrieve
- * @return string The SQL query string
- */
- function getSpecialQuery($type)
- {
- switch ($type) {
- case 'tables':
- return 'SELECT table_name FROM user_tables';
- default:
- return null;
- }
- }
-
- // }}}
- // {{{ tableInfo()
-
- /**
- * Returns information about a table or a result set.
- *
- * NOTE: only supports 'table' and 'flags' if <var>$result</var>
- * is a table name.
- *
- * NOTE: flags won't contain index information.
- *
- * @param object|string $result DB_result object from a query or a
- * string containing the name of a table
- * @param int $mode a valid tableInfo mode
- * @return array an associative array with the information requested
- * or an error object if something is wrong
- * @access public
- * @internal
- * @see DB_common::tableInfo()
- */
- function tableInfo($result, $mode = null)
- {
- if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) {
- $case_func = 'strtolower';
- } else {
- $case_func = 'strval';
- }
-
- if (is_string($result)) {
- /*
- * Probably received a table name.
- * Create a result resource identifier.
- */
- $result = strtoupper($result);
- $q_fields = 'SELECT column_name, data_type, data_length, '
- . 'nullable '
- . 'FROM user_tab_columns '
- . "WHERE table_name='$result' ORDER BY column_id";
-
- $this->last_query = $q_fields;
-
- if (!$stmt = @OCIParse($this->connection, $q_fields)) {
- return $this->oci8RaiseError(DB_ERROR_NEED_MORE_DATA);
- }
- if (!@OCIExecute($stmt, OCI_DEFAULT)) {
- return $this->oci8RaiseError($stmt);
- }
-
- $i = 0;
- while (@OCIFetch($stmt)) {
- $res[$i]['table'] = $case_func($result);
- $res[$i]['name'] = $case_func(@OCIResult($stmt, 1));
- $res[$i]['type'] = @OCIResult($stmt, 2);
- $res[$i]['len'] = @OCIResult($stmt, 3);
- $res[$i]['flags'] = (@OCIResult($stmt, 4) == 'N') ? 'not_null' : '';
-
- if ($mode & DB_TABLEINFO_ORDER) {
- $res['order'][$res[$i]['name']] = $i;
- }
- if ($mode & DB_TABLEINFO_ORDERTABLE) {
- $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
- }
- $i++;
- }
-
- if ($mode) {
- $res['num_fields'] = $i;
- }
- @OCIFreeStatement($stmt);
-
- } else {
- if (isset($result->result)) {
- /*
- * Probably received a result object.
- * Extract the result resource identifier.
- */
- $result = $result->result;
- } else {
- /*
- * ELSE, probably received a result resource identifier.
- * Depricated. Here for compatibility only.
- */
- }
-
- if ($result === $this->last_stmt) {
- $count = @OCINumCols($result);
-
- for ($i=0; $i<$count; $i++) {
- $res[$i]['table'] = '';
- $res[$i]['name'] = $case_func(@OCIColumnName($result, $i+1));
- $res[$i]['type'] = @OCIColumnType($result, $i+1);
- $res[$i]['len'] = @OCIColumnSize($result, $i+1);
- $res[$i]['flags'] = '';
-
- if ($mode & DB_TABLEINFO_ORDER) {
- $res['order'][$res[$i]['name']] = $i;
- }
- if ($mode & DB_TABLEINFO_ORDERTABLE) {
- $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
- }
- }
-
- if ($mode) {
- $res['num_fields'] = $count;
- }
-
- } else {
- return $this->raiseError(DB_ERROR_NOT_CAPABLE);
- }
- }
- return $res;
- }
-
- // }}}
-
-}
-
-/*
- * Local variables:
- * tab-width: 4
- * c-basic-offset: 4
- * End:
- */
-
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 foldmethod=marker: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Stig Bakken <ssb@php.net> |
-// | Maintainer: Daniel Convissor <danielc@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: odbc.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
-
-
-// XXX legend:
-// More info on ODBC errors could be found here:
-// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/trblsql/tr_err_odbc_5stz.asp
-//
-// XXX ERRORMSG: The error message from the odbc function should
-// be registered here.
-
-
-require_once 'DB/common.php';
-
-/**
- * Database independent query interface definition for PHP's ODBC
- * extension.
- *
- * @package DB
- * @version $Id: odbc.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
- * @category Database
- * @author Stig Bakken <ssb@php.net>
- */
-class DB_odbc extends DB_common
-{
- // {{{ properties
-
- var $connection;
- var $phptype, $dbsyntax;
- var $row = array();
-
- // }}}
- // {{{ constructor
-
- function DB_odbc()
- {
- $this->DB_common();
- $this->phptype = 'odbc';
- $this->dbsyntax = 'sql92';
- $this->features = array(
- 'prepare' => true,
- 'pconnect' => true,
- 'transactions' => false,
- 'limit' => 'emulate'
- );
- $this->errorcode_map = array(
- '01004' => DB_ERROR_TRUNCATED,
- '07001' => DB_ERROR_MISMATCH,
- '21S01' => DB_ERROR_MISMATCH,
- '21S02' => DB_ERROR_MISMATCH,
- '22003' => DB_ERROR_INVALID_NUMBER,
- '22005' => DB_ERROR_INVALID_NUMBER,
- '22008' => DB_ERROR_INVALID_DATE,
- '22012' => DB_ERROR_DIVZERO,
- '23000' => DB_ERROR_CONSTRAINT,
- '23502' => DB_ERROR_CONSTRAINT_NOT_NULL,
- '23503' => DB_ERROR_CONSTRAINT,
- '23505' => DB_ERROR_CONSTRAINT,
- '24000' => DB_ERROR_INVALID,
- '34000' => DB_ERROR_INVALID,
- '37000' => DB_ERROR_SYNTAX,
- '42000' => DB_ERROR_SYNTAX,
- '42601' => DB_ERROR_SYNTAX,
- 'IM001' => DB_ERROR_UNSUPPORTED,
- 'S0000' => DB_ERROR_NOSUCHTABLE,
- 'S0001' => DB_ERROR_ALREADY_EXISTS,
- 'S0002' => DB_ERROR_NOSUCHTABLE,
- 'S0011' => DB_ERROR_ALREADY_EXISTS,
- 'S0012' => DB_ERROR_NOT_FOUND,
- 'S0021' => DB_ERROR_ALREADY_EXISTS,
- 'S0022' => DB_ERROR_NOSUCHFIELD,
- 'S1000' => DB_ERROR_CONSTRAINT_NOT_NULL,
- 'S1009' => DB_ERROR_INVALID,
- 'S1090' => DB_ERROR_INVALID,
- 'S1C00' => DB_ERROR_NOT_CAPABLE
- );
- }
-
- // }}}
- // {{{ connect()
-
- /**
- * Connect to a database and log in as the specified user.
- *
- * @param $dsn the data source name (see DB::parseDSN for syntax)
- * @param $persistent (optional) whether the connection should
- * be persistent
- *
- * @return int DB_OK on success, a DB error code on failure
- */
- function connect($dsninfo, $persistent = false)
- {
- if (!DB::assertExtension('odbc')) {
- return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
- }
-
- $this->dsn = $dsninfo;
- if ($dsninfo['dbsyntax']) {
- $this->dbsyntax = $dsninfo['dbsyntax'];
- }
- switch ($this->dbsyntax) {
- case 'solid':
- $this->features = array(
- 'prepare' => true,
- 'pconnect' => true,
- 'transactions' => true
- );
- break;
- case 'navision':
- // the Navision driver doesn't support fetch row by number
- $this->features['limit'] = false;
- }
-
- /*
- * This is hear for backwards compatibility.
- * Should have been using 'database' all along, but used hostspec.
- */
- if ($dsninfo['database']) {
- $odbcdsn = $dsninfo['database'];
- } elseif ($dsninfo['hostspec']) {
- $odbcdsn = $dsninfo['hostspec'];
- } else {
- $odbcdsn = 'localhost';
- }
-
- if ($this->provides('pconnect')) {
- $connect_function = $persistent ? 'odbc_pconnect' : 'odbc_connect';
- } else {
- $connect_function = 'odbc_connect';
- }
- $conn = @$connect_function($odbcdsn, $dsninfo['username'],
- $dsninfo['password']);
- if (!is_resource($conn)) {
- return $this->raiseError(DB_ERROR_CONNECT_FAILED, null, null,
- null, $this->errorNative());
- }
- $this->connection = $conn;
- return DB_OK;
- }
-
- // }}}
- // {{{ disconnect()
-
- function disconnect()
- {
- $err = @odbc_close($this->connection);
- $this->connection = null;
- return $err;
- }
-
- // }}}
- // {{{ simpleQuery()
-
- /**
- * Send a query to ODBC and return the results as a ODBC resource
- * identifier.
- *
- * @param $query the SQL query
- *
- * @return int returns a valid ODBC result for successful SELECT
- * queries, DB_OK for other successful queries. A DB error code
- * is returned on failure.
- */
- function simpleQuery($query)
- {
- $this->last_query = $query;
- $query = $this->modifyQuery($query);
- $result = @odbc_exec($this->connection, $query);
- if (!$result) {
- return $this->odbcRaiseError(); // XXX ERRORMSG
- }
- // Determine which queries that should return data, and which
- // should return an error code only.
- if (DB::isManip($query)) {
- $this->manip_result = $result; // For affectedRows()
- return DB_OK;
- }
- $this->row[(int)$result] = 0;
- $this->manip_result = 0;
- return $result;
- }
-
- // }}}
- // {{{ nextResult()
-
- /**
- * Move the internal odbc result pointer to the next available result
- *
- * @param a valid fbsql result resource
- *
- * @access public
- *
- * @return true if a result is available otherwise return false
- */
- function nextResult($result)
- {
- return @odbc_next_result($result);
- }
-
- // }}}
- // {{{ fetchInto()
-
- /**
- * Fetch a row and insert the data into an existing array.
- *
- * Formating of the array and the data therein are configurable.
- * See DB_result::fetchInto() for more information.
- *
- * @param resource $result query result identifier
- * @param array $arr (reference) array where data from the row
- * should be placed
- * @param int $fetchmode how the resulting array should be indexed
- * @param int $rownum the row number to fetch
- *
- * @return mixed DB_OK on success, null when end of result set is
- * reached or on failure
- *
- * @see DB_result::fetchInto()
- * @access private
- */
- function fetchInto($result, &$arr, $fetchmode, $rownum=null)
- {
- $arr = array();
- if ($rownum !== null) {
- $rownum++; // ODBC first row is 1
- if (version_compare(phpversion(), '4.2.0', 'ge')) {
- $cols = @odbc_fetch_into($result, $arr, $rownum);
- } else {
- $cols = @odbc_fetch_into($result, $rownum, $arr);
- }
- } else {
- $cols = @odbc_fetch_into($result, $arr);
- }
-
- if (!$cols) {
- /* XXX FIXME: doesn't work with unixODBC and easysoft
- (get corrupted $errno values)
- if ($errno = @odbc_error($this->connection)) {
- return $this->RaiseError($errno);
- }*/
- return null;
- }
- if ($fetchmode !== DB_FETCHMODE_ORDERED) {
- for ($i = 0; $i < count($arr); $i++) {
- $colName = @odbc_field_name($result, $i+1);
- $a[$colName] = $arr[$i];
- }
- if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) {
- $a = array_change_key_case($a, CASE_LOWER);
- }
- $arr = $a;
- }
- if ($this->options['portability'] & DB_PORTABILITY_RTRIM) {
- $this->_rtrimArrayValues($arr);
- }
- if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) {
- $this->_convertNullArrayValuesToEmpty($arr);
- }
- return DB_OK;
- }
-
- // }}}
- // {{{ freeResult()
-
- function freeResult($result)
- {
- unset($this->row[(int)$result]);
- return @odbc_free_result($result);
- }
-
- // }}}
- // {{{ numCols()
-
- function numCols($result)
- {
- $cols = @odbc_num_fields($result);
- if (!$cols) {
- return $this->odbcRaiseError();
- }
- return $cols;
- }
-
- // }}}
- // {{{ affectedRows()
-
- /**
- * Returns the number of rows affected by a manipulative query
- * (INSERT, DELETE, UPDATE)
- * @return mixed int affected rows, 0 when non manip queries or
- * DB error on error
- */
- function affectedRows()
- {
- if (empty($this->manip_result)) { // In case of SELECT stms
- return 0;
- }
- $nrows = @odbc_num_rows($this->manip_result);
- if ($nrows == -1) {
- return $this->odbcRaiseError();
- }
- return $nrows;
- }
-
- // }}}
- // {{{ numRows()
-
- /**
- * ODBC may or may not support counting rows in the result set of
- * SELECTs.
- *
- * @param $result the odbc result resource
- * @return the number of rows, or 0
- */
- function numRows($result)
- {
- $nrows = @odbc_num_rows($result);
- if ($nrows == -1) {
- return $this->odbcRaiseError(DB_ERROR_UNSUPPORTED);
- }
- return $nrows;
- }
-
- // }}}
- // {{{ quoteIdentifier()
-
- /**
- * Quote a string so it can be safely used as a table / column name
- *
- * Quoting style depends on which dbsyntax was passed in the DSN.
- *
- * Use 'mssql' as the dbsyntax in the DB DSN only if you've unchecked
- * "Use ANSI quoted identifiers" when setting up the ODBC data source.
- *
- * @param string $str identifier name to be quoted
- *
- * @return string quoted identifier string
- *
- * @since 1.6.0
- * @access public
- */
- function quoteIdentifier($str)
- {
- switch ($this->dsn['dbsyntax']) {
- case 'access':
- return '[' . $str . ']';
- case 'mssql':
- case 'sybase':
- return '[' . str_replace(']', ']]', $str) . ']';
- case 'mysql':
- case 'mysqli':
- return '`' . $str . '`';
- default:
- return '"' . str_replace('"', '""', $str) . '"';
- }
- }
-
- // }}}
- // {{{ quote()
-
- /**
- * @deprecated Deprecated in release 1.6.0
- * @internal
- */
- function quote($str) {
- return $this->quoteSmart($str);
- }
-
- // }}}
- // {{{ errorNative()
-
- /**
- * Get the native error code of the last error (if any) that
- * occured on the current connection.
- *
- * @access public
- *
- * @return int ODBC error code
- */
- function errorNative()
- {
- if (!isset($this->connection) || !is_resource($this->connection)) {
- return @odbc_error() . ' ' . @odbc_errormsg();
- }
- return @odbc_error($this->connection) . ' ' . @odbc_errormsg($this->connection);
- }
-
- // }}}
- // {{{ nextId()
-
- /**
- * Returns the next free id in a sequence
- *
- * @param string $seq_name name of the sequence
- * @param boolean $ondemand when true, the seqence is automatically
- * created if it does not exist
- *
- * @return int the next id number in the sequence. DB_Error if problem.
- *
- * @internal
- * @see DB_common::nextID()
- * @access public
- */
- function nextId($seq_name, $ondemand = true)
- {
- $seqname = $this->getSequenceName($seq_name);
- $repeat = 0;
- do {
- $this->pushErrorHandling(PEAR_ERROR_RETURN);
- $result = $this->query("update ${seqname} set id = id + 1");
- $this->popErrorHandling();
- if ($ondemand && DB::isError($result) &&
- $result->getCode() == DB_ERROR_NOSUCHTABLE) {
- $repeat = 1;
- $this->pushErrorHandling(PEAR_ERROR_RETURN);
- $result = $this->createSequence($seq_name);
- $this->popErrorHandling();
- if (DB::isError($result)) {
- return $this->raiseError($result);
- }
- $result = $this->query("insert into ${seqname} (id) values(0)");
- } else {
- $repeat = 0;
- }
- } while ($repeat);
-
- if (DB::isError($result)) {
- return $this->raiseError($result);
- }
-
- $result = $this->query("select id from ${seqname}");
- if (DB::isError($result)) {
- return $result;
- }
-
- $row = $result->fetchRow(DB_FETCHMODE_ORDERED);
- if (DB::isError($row || !$row)) {
- return $row;
- }
-
- return $row[0];
- }
-
- /**
- * Creates a new sequence
- *
- * @param string $seq_name name of the new sequence
- *
- * @return int DB_OK on success. A DB_Error object is returned if
- * problems arise.
- *
- * @internal
- * @see DB_common::createSequence()
- * @access public
- */
- function createSequence($seq_name)
- {
- $seqname = $this->getSequenceName($seq_name);
- return $this->query("CREATE TABLE ${seqname} ".
- '(id integer NOT NULL,'.
- ' PRIMARY KEY(id))');
- }
-
- // }}}
- // {{{ dropSequence()
-
- /**
- * Deletes a sequence
- *
- * @param string $seq_name name of the sequence to be deleted
- *
- * @return int DB_OK on success. DB_Error if problems.
- *
- * @internal
- * @see DB_common::dropSequence()
- * @access public
- */
- function dropSequence($seq_name)
- {
- $seqname = $this->getSequenceName($seq_name);
- return $this->query("DROP TABLE ${seqname}");
- }
-
- // }}}
- // {{{ autoCommit()
-
- function autoCommit($onoff = false)
- {
- if (!@odbc_autocommit($this->connection, $onoff)) {
- return $this->odbcRaiseError();
- }
- return DB_OK;
- }
-
- // }}}
- // {{{ commit()
-
- function commit()
- {
- if (!@odbc_commit($this->connection)) {
- return $this->odbcRaiseError();
- }
- return DB_OK;
- }
-
- // }}}
- // {{{ rollback()
-
- function rollback()
- {
- if (!@odbc_rollback($this->connection)) {
- return $this->odbcRaiseError();
- }
- return DB_OK;
- }
-
- // }}}
- // {{{ odbcRaiseError()
-
- /**
- * Gather information about an error, then use that info to create a
- * DB error object and finally return that object.
- *
- * @param integer $errno PEAR error number (usually a DB constant) if
- * manually raising an error
- * @return object DB error object
- * @see errorNative()
- * @see DB_common::errorCode()
- * @see DB_common::raiseError()
- */
- function odbcRaiseError($errno = null)
- {
- if ($errno === null) {
- switch ($this->dbsyntax) {
- case 'access':
- if ($this->options['portability'] & DB_PORTABILITY_ERRORS) {
- $this->errorcode_map['07001'] = DB_ERROR_NOSUCHFIELD;
- } else {
- // Doing this in case mode changes during runtime.
- $this->errorcode_map['07001'] = DB_ERROR_MISMATCH;
- }
- }
- $errno = $this->errorCode(odbc_error($this->connection));
- }
- return $this->raiseError($errno, null, null, null,
- $this->errorNative());
- }
-
- // }}}
-
-}
-
-/*
- * Local variables:
- * tab-width: 4
- * c-basic-offset: 4
- * End:
- */
-
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 foldmethod=marker: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Rui Hirokawa <hirokawa@php.net> |
-// | Stig Bakken <ssb@php.net> |
-// | Maintainer: Daniel Convissor <danielc@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: pgsql.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
-
-require_once 'DB/common.php';
-
-/**
- * Database independent query interface definition for PHP's PostgreSQL
- * extension.
- *
- * @package DB
- * @version $Id: pgsql.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
- * @category Database
- * @author Rui Hirokawa <hirokawa@php.net>
- * @author Stig Bakken <ssb@php.net>
- */
-class DB_pgsql extends DB_common
-{
- // {{{ properties
-
- var $connection;
- var $phptype, $dbsyntax;
- var $prepare_tokens = array();
- var $prepare_types = array();
- var $transaction_opcount = 0;
- var $dsn = array();
- var $row = array();
- var $num_rows = array();
- var $affected = 0;
- var $autocommit = true;
- var $fetchmode = DB_FETCHMODE_ORDERED;
-
- // }}}
- // {{{ constructor
-
- function DB_pgsql()
- {
- $this->DB_common();
- $this->phptype = 'pgsql';
- $this->dbsyntax = 'pgsql';
- $this->features = array(
- 'prepare' => false,
- 'pconnect' => true,
- 'transactions' => true,
- 'limit' => 'alter'
- );
- $this->errorcode_map = array(
- );
- }
-
- // }}}
- // {{{ connect()
-
- /**
- * Connect to a database and log in as the specified user.
- *
- * @param $dsn the data source name (see DB::parseDSN for syntax)
- * @param $persistent (optional) whether the connection should
- * be persistent
- *
- * @return int DB_OK on success, a DB error code on failure.
- */
- function connect($dsninfo, $persistent = false)
- {
- if (!DB::assertExtension('pgsql')) {
- return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
- }
-
- $this->dsn = $dsninfo;
- $protocol = $dsninfo['protocol'] ? $dsninfo['protocol'] : 'tcp';
- $connstr = '';
-
- if ($protocol == 'tcp') {
- if ($dsninfo['hostspec']) {
- $connstr .= 'host=' . $dsninfo['hostspec'];
- }
- if ($dsninfo['port']) {
- $connstr .= ' port=' . $dsninfo['port'];
- }
- } elseif ($protocol == 'unix') {
- // Allow for pg socket in non-standard locations.
- if ($dsninfo['socket']) {
- $connstr .= 'host=' . $dsninfo['socket'];
- }
- }
-
- if ($dsninfo['database']) {
- $connstr .= ' dbname=\'' . addslashes($dsninfo['database']) . '\'';
- }
- if ($dsninfo['username']) {
- $connstr .= ' user=\'' . addslashes($dsninfo['username']) . '\'';
- }
- if ($dsninfo['password']) {
- $connstr .= ' password=\'' . addslashes($dsninfo['password']) . '\'';
- }
- if (!empty($dsninfo['options'])) {
- $connstr .= ' options=' . $dsninfo['options'];
- }
- if (!empty($dsninfo['tty'])) {
- $connstr .= ' tty=' . $dsninfo['tty'];
- }
-
- $connect_function = $persistent ? 'pg_pconnect' : 'pg_connect';
- // catch error
- ob_start();
- $conn = $connect_function($connstr);
- $error = ob_get_contents();
- ob_end_clean();
- if ($conn == false) {
- return $this->raiseError(DB_ERROR_CONNECT_FAILED, null,
- null, null, strip_tags($error));
- }
- $this->connection = $conn;
- return DB_OK;
- }
-
- // }}}
- // {{{ disconnect()
-
- /**
- * Log out and disconnect from the database.
- *
- * @return bool true on success, false if not connected.
- */
- function disconnect()
- {
- $ret = @pg_close($this->connection);
- $this->connection = null;
- return $ret;
- }
-
- // }}}
- // {{{ simpleQuery()
-
- /**
- * Send a query to PostgreSQL and return the results as a
- * PostgreSQL resource identifier.
- *
- * @param $query the SQL query
- *
- * @return int returns a valid PostgreSQL result for successful SELECT
- * queries, DB_OK for other successful queries. A DB error code
- * is returned on failure.
- */
- function simpleQuery($query)
- {
- $ismanip = DB::isManip($query);
- $this->last_query = $query;
- $query = $this->modifyQuery($query);
- if (!$this->autocommit && $ismanip) {
- if ($this->transaction_opcount == 0) {
- $result = @pg_exec($this->connection, 'begin;');
- if (!$result) {
- return $this->pgsqlRaiseError();
- }
- }
- $this->transaction_opcount++;
- }
- $result = @pg_exec($this->connection, $query);
- if (!$result) {
- return $this->pgsqlRaiseError();
- }
- // Determine which queries that should return data, and which
- // should return an error code only.
- if ($ismanip) {
- $this->affected = @pg_cmdtuples($result);
- return DB_OK;
- } elseif (preg_match('/^\s*\(?\s*(SELECT(?!\s+INTO)|EXPLAIN|SHOW)\s/si', $query)) {
- /* PostgreSQL commands:
- ABORT, ALTER, BEGIN, CLOSE, CLUSTER, COMMIT, COPY,
- CREATE, DECLARE, DELETE, DROP TABLE, EXPLAIN, FETCH,
- GRANT, INSERT, LISTEN, LOAD, LOCK, MOVE, NOTIFY, RESET,
- REVOKE, ROLLBACK, SELECT, SELECT INTO, SET, SHOW,
- UNLISTEN, UPDATE, VACUUM
- */
- $this->row[(int)$result] = 0; // reset the row counter.
- $numrows = $this->numrows($result);
- if (is_object($numrows)) {
- return $numrows;
- }
- $this->num_rows[(int)$result] = $numrows;
- $this->affected = 0;
- return $result;
- } else {
- $this->affected = 0;
- return DB_OK;
- }
- }
-
- // }}}
- // {{{ nextResult()
-
- /**
- * Move the internal pgsql result pointer to the next available result
- *
- * @param a valid fbsql result resource
- *
- * @access public
- *
- * @return true if a result is available otherwise return false
- */
- function nextResult($result)
- {
- return false;
- }
-
- // }}}
- // {{{ errorCode()
-
- /**
- * Determine PEAR::DB error code from the database's text error message.
- *
- * @param string $errormsg error message returned from the database
- * @return integer an error number from a DB error constant
- */
- function errorCode($errormsg)
- {
- static $error_regexps;
- if (!isset($error_regexps)) {
- $error_regexps = array(
- '/(([Rr]elation|[Ss]equence|[Tt]able)( [\"\'].*[\"\'])? does not exist|[Cc]lass ".+" not found)$/' => DB_ERROR_NOSUCHTABLE,
- '/[Cc]olumn [\"\'].*[\"\'] does not exist/' => DB_ERROR_NOSUCHFIELD,
- '/[Rr]elation [\"\'].*[\"\'] already exists|[Cc]annot insert a duplicate key into (a )?unique index.*/' => DB_ERROR_ALREADY_EXISTS,
- '/(divide|division) by zero$/' => DB_ERROR_DIVZERO,
- '/pg_atoi: error in .*: can\'t parse /' => DB_ERROR_INVALID_NUMBER,
- '/invalid input syntax for integer/' => DB_ERROR_INVALID_NUMBER,
- '/ttribute [\"\'].*[\"\'] not found$|[Rr]elation [\"\'].*[\"\'] does not have attribute [\"\'].*[\"\']/' => DB_ERROR_NOSUCHFIELD,
- '/parser: parse error at or near \"/' => DB_ERROR_SYNTAX,
- '/syntax error at/' => DB_ERROR_SYNTAX,
- '/violates not-null constraint/' => DB_ERROR_CONSTRAINT_NOT_NULL,
- '/violates [\w ]+ constraint/' => DB_ERROR_CONSTRAINT,
- '/referential integrity violation/' => DB_ERROR_CONSTRAINT
- );
- }
- foreach ($error_regexps as $regexp => $code) {
- if (preg_match($regexp, $errormsg)) {
- return $code;
- }
- }
- // Fall back to DB_ERROR if there was no mapping.
- return DB_ERROR;
- }
-
- // }}}
- // {{{ fetchInto()
-
- /**
- * Fetch a row and insert the data into an existing array.
- *
- * Formating of the array and the data therein are configurable.
- * See DB_result::fetchInto() for more information.
- *
- * @param resource $result query result identifier
- * @param array $arr (reference) array where data from the row
- * should be placed
- * @param int $fetchmode how the resulting array should be indexed
- * @param int $rownum the row number to fetch
- *
- * @return mixed DB_OK on success, null when end of result set is
- * reached or on failure
- *
- * @see DB_result::fetchInto()
- * @access private
- */
- function fetchInto($result, &$arr, $fetchmode, $rownum=null)
- {
- $rownum = ($rownum !== null) ? $rownum : $this->row[$result];
- if ($rownum >= $this->num_rows[$result]) {
- return null;
- }
- if ($fetchmode & DB_FETCHMODE_ASSOC) {
- $arr = @pg_fetch_array($result, $rownum, PGSQL_ASSOC);
- if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE && $arr) {
- $arr = array_change_key_case($arr, CASE_LOWER);
- }
- } else {
- $arr = @pg_fetch_row($result, $rownum);
- }
- if (!$arr) {
- $err = pg_errormessage($this->connection);
- if (!$err) {
- return null;
- }
- return $this->pgsqlRaiseError();
- }
- if ($this->options['portability'] & DB_PORTABILITY_RTRIM) {
- $this->_rtrimArrayValues($arr);
- }
- if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) {
- $this->_convertNullArrayValuesToEmpty($arr);
- }
- $this->row[$result] = ++$rownum;
- return DB_OK;
- }
-
- // }}}
- // {{{ freeResult()
-
- /**
- * Free the internal resources associated with $result.
- *
- * @param $result int PostgreSQL result identifier
- *
- * @return bool true on success, false if $result is invalid
- */
- function freeResult($result)
- {
- if (is_resource($result)) {
- unset($this->row[(int)$result]);
- unset($this->num_rows[(int)$result]);
- $this->affected = 0;
- return @pg_freeresult($result);
- }
- return false;
- }
-
- // }}}
- // {{{ quote()
-
- /**
- * @deprecated Deprecated in release 1.6.0
- * @internal
- */
- function quote($str) {
- return $this->quoteSmart($str);
- }
-
- // }}}
- // {{{ quoteSmart()
-
- /**
- * Format input so it can be safely used in a query
- *
- * @param mixed $in data to be quoted
- *
- * @return mixed Submitted variable's type = returned value:
- * + null = the string <samp>NULL</samp>
- * + boolean = string <samp>TRUE</samp> or <samp>FALSE</samp>
- * + integer or double = the unquoted number
- * + other (including strings and numeric strings) =
- * the data escaped according to MySQL's settings
- * then encapsulated between single quotes
- *
- * @internal
- */
- function quoteSmart($in)
- {
- if (is_int($in) || is_double($in)) {
- return $in;
- } elseif (is_bool($in)) {
- return $in ? 'TRUE' : 'FALSE';
- } elseif (is_null($in)) {
- return 'NULL';
- } else {
- return "'" . $this->escapeSimple($in) . "'";
- }
- }
-
- // }}}
- // {{{ escapeSimple()
-
- /**
- * Escape a string according to the current DBMS's standards
- *
- * PostgreSQL treats a backslash as an escape character, so they are
- * removed.
- *
- * Not using pg_escape_string() yet because it requires PostgreSQL
- * to be at version 7.2 or greater.
- *
- * @param string $str the string to be escaped
- *
- * @return string the escaped string
- *
- * @internal
- */
- function escapeSimple($str) {
- return str_replace("'", "''", str_replace('\\', '\\\\', $str));
- }
-
- // }}}
- // {{{ numCols()
-
- /**
- * Get the number of columns in a result set.
- *
- * @param $result resource PostgreSQL result identifier
- *
- * @return int the number of columns per row in $result
- */
- function numCols($result)
- {
- $cols = @pg_numfields($result);
- if (!$cols) {
- return $this->pgsqlRaiseError();
- }
- return $cols;
- }
-
- // }}}
- // {{{ numRows()
-
- /**
- * Get the number of rows in a result set.
- *
- * @param $result resource PostgreSQL result identifier
- *
- * @return int the number of rows in $result
- */
- function numRows($result)
- {
- $rows = @pg_numrows($result);
- if ($rows === null) {
- return $this->pgsqlRaiseError();
- }
- return $rows;
- }
-
- // }}}
- // {{{ errorNative()
-
- /**
- * Get the native error code of the last error (if any) that
- * occured on the current connection.
- *
- * @return int native PostgreSQL error code
- */
- function errorNative()
- {
- return pg_errormessage($this->connection);
- }
-
- // }}}
- // {{{ autoCommit()
-
- /**
- * Enable/disable automatic commits
- */
- function autoCommit($onoff = false)
- {
- // XXX if $this->transaction_opcount > 0, we should probably
- // issue a warning here.
- $this->autocommit = $onoff ? true : false;
- return DB_OK;
- }
-
- // }}}
- // {{{ commit()
-
- /**
- * Commit the current transaction.
- */
- function commit()
- {
- if ($this->transaction_opcount > 0) {
- // (disabled) hack to shut up error messages from libpq.a
- //@fclose(@fopen("php://stderr", "w"));
- $result = @pg_exec($this->connection, 'end;');
- $this->transaction_opcount = 0;
- if (!$result) {
- return $this->pgsqlRaiseError();
- }
- }
- return DB_OK;
- }
-
- // }}}
- // {{{ rollback()
-
- /**
- * Roll back (undo) the current transaction.
- */
- function rollback()
- {
- if ($this->transaction_opcount > 0) {
- $result = @pg_exec($this->connection, 'abort;');
- $this->transaction_opcount = 0;
- if (!$result) {
- return $this->pgsqlRaiseError();
- }
- }
- return DB_OK;
- }
-
- // }}}
- // {{{ affectedRows()
-
- /**
- * Gets the number of rows affected by the last query.
- * if the last query was a select, returns 0.
- *
- * @return int number of rows affected by the last query or DB_ERROR
- */
- function affectedRows()
- {
- return $this->affected;
- }
-
- // }}}
- // {{{ nextId()
-
- /**
- * Returns the next free id in a sequence
- *
- * @param string $seq_name name of the sequence
- * @param boolean $ondemand when true, the seqence is automatically
- * created if it does not exist
- *
- * @return int the next id number in the sequence. DB_Error if problem.
- *
- * @internal
- * @see DB_common::nextID()
- * @access public
- */
- function nextId($seq_name, $ondemand = true)
- {
- $seqname = $this->getSequenceName($seq_name);
- $repeat = false;
- do {
- $this->pushErrorHandling(PEAR_ERROR_RETURN);
- $result =& $this->query("SELECT NEXTVAL('${seqname}')");
- $this->popErrorHandling();
- if ($ondemand && DB::isError($result) &&
- $result->getCode() == DB_ERROR_NOSUCHTABLE) {
- $repeat = true;
- $this->pushErrorHandling(PEAR_ERROR_RETURN);
- $result = $this->createSequence($seq_name);
- $this->popErrorHandling();
- if (DB::isError($result)) {
- return $this->raiseError($result);
- }
- } else {
- $repeat = false;
- }
- } while ($repeat);
- if (DB::isError($result)) {
- return $this->raiseError($result);
- }
- $arr = $result->fetchRow(DB_FETCHMODE_ORDERED);
- $result->free();
- return $arr[0];
- }
-
- // }}}
- // {{{ createSequence()
-
- /**
- * Create the sequence
- *
- * @param string $seq_name the name of the sequence
- * @return mixed DB_OK on success or DB error on error
- * @access public
- */
- function createSequence($seq_name)
- {
- $seqname = $this->getSequenceName($seq_name);
- $result = $this->query("CREATE SEQUENCE ${seqname}");
- return $result;
- }
-
- // }}}
- // {{{ dropSequence()
-
- /**
- * Drop a sequence
- *
- * @param string $seq_name the name of the sequence
- * @return mixed DB_OK on success or DB error on error
- * @access public
- */
- function dropSequence($seq_name)
- {
- $seqname = $this->getSequenceName($seq_name);
- return $this->query("DROP SEQUENCE ${seqname}");
- }
-
- // }}}
- // {{{ modifyLimitQuery()
-
- function modifyLimitQuery($query, $from, $count, $params = array())
- {
- $query = $query . " LIMIT $count OFFSET $from";
- return $query;
- }
-
- // }}}
- // {{{ pgsqlRaiseError()
-
- /**
- * Gather information about an error, then use that info to create a
- * DB error object and finally return that object.
- *
- * @param integer $errno PEAR error number (usually a DB constant) if
- * manually raising an error
- * @return object DB error object
- * @see errorNative()
- * @see errorCode()
- * @see DB_common::raiseError()
- */
- function pgsqlRaiseError($errno = null)
- {
- $native = $this->errorNative();
- if ($errno === null) {
- $err = $this->errorCode($native);
- } else {
- $err = $errno;
- }
- return $this->raiseError($err, null, null, null, $native);
- }
-
- // }}}
- // {{{ _pgFieldFlags()
-
- /**
- * Flags of a Field
- *
- * @param int $resource PostgreSQL result identifier
- * @param int $num_field the field number
- *
- * @return string The flags of the field ("not_null", "default_value",
- * "primary_key", "unique_key" and "multiple_key"
- * are supported). The default value is passed
- * through rawurlencode() in case there are spaces in it.
- * @access private
- */
- function _pgFieldFlags($resource, $num_field, $table_name)
- {
- $field_name = @pg_fieldname($resource, $num_field);
-
- $result = @pg_exec($this->connection, "SELECT f.attnotnull, f.atthasdef
- FROM pg_attribute f, pg_class tab, pg_type typ
- WHERE tab.relname = typ.typname
- AND typ.typrelid = f.attrelid
- AND f.attname = '$field_name'
- AND tab.relname = '$table_name'");
- if (@pg_numrows($result) > 0) {
- $row = @pg_fetch_row($result, 0);
- $flags = ($row[0] == 't') ? 'not_null ' : '';
-
- if ($row[1] == 't') {
- $result = @pg_exec($this->connection, "SELECT a.adsrc
- FROM pg_attribute f, pg_class tab, pg_type typ, pg_attrdef a
- WHERE tab.relname = typ.typname AND typ.typrelid = f.attrelid
- AND f.attrelid = a.adrelid AND f.attname = '$field_name'
- AND tab.relname = '$table_name' AND f.attnum = a.adnum");
- $row = @pg_fetch_row($result, 0);
- $num = preg_replace("/'(.*)'::\w+/", "\\1", $row[0]);
- $flags .= 'default_' . rawurlencode($num) . ' ';
- }
- } else {
- $flags = '';
- }
- $result = @pg_exec($this->connection, "SELECT i.indisunique, i.indisprimary, i.indkey
- FROM pg_attribute f, pg_class tab, pg_type typ, pg_index i
- WHERE tab.relname = typ.typname
- AND typ.typrelid = f.attrelid
- AND f.attrelid = i.indrelid
- AND f.attname = '$field_name'
- AND tab.relname = '$table_name'");
- $count = @pg_numrows($result);
-
- for ($i = 0; $i < $count ; $i++) {
- $row = @pg_fetch_row($result, $i);
- $keys = explode(' ', $row[2]);
-
- if (in_array($num_field + 1, $keys)) {
- $flags .= ($row[0] == 't' && $row[1] == 'f') ? 'unique_key ' : '';
- $flags .= ($row[1] == 't') ? 'primary_key ' : '';
- if (count($keys) > 1)
- $flags .= 'multiple_key ';
- }
- }
-
- return trim($flags);
- }
-
- // }}}
- // {{{ tableInfo()
-
- /**
- * Returns information about a table or a result set.
- *
- * NOTE: only supports 'table' and 'flags' if <var>$result</var>
- * is a table name.
- *
- * @param object|string $result DB_result object from a query or a
- * string containing the name of a table
- * @param int $mode a valid tableInfo mode
- * @return array an associative array with the information requested
- * or an error object if something is wrong
- * @access public
- * @internal
- * @see DB_common::tableInfo()
- */
- function tableInfo($result, $mode = null)
- {
- if (isset($result->result)) {
- /*
- * Probably received a result object.
- * Extract the result resource identifier.
- */
- $id = $result->result;
- $got_string = false;
- } elseif (is_string($result)) {
- /*
- * Probably received a table name.
- * Create a result resource identifier.
- */
- $id = @pg_exec($this->connection, "SELECT * FROM $result LIMIT 0");
- $got_string = true;
- } else {
- /*
- * Probably received a result resource identifier.
- * Copy it.
- * Deprecated. Here for compatibility only.
- */
- $id = $result;
- $got_string = false;
- }
-
- if (!is_resource($id)) {
- return $this->pgsqlRaiseError(DB_ERROR_NEED_MORE_DATA);
- }
-
- if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) {
- $case_func = 'strtolower';
- } else {
- $case_func = 'strval';
- }
-
- $count = @pg_numfields($id);
-
- // made this IF due to performance (one if is faster than $count if's)
- if (!$mode) {
-
- for ($i=0; $i<$count; $i++) {
- $res[$i]['table'] = $got_string ? $case_func($result) : '';
- $res[$i]['name'] = $case_func(@pg_fieldname($id, $i));
- $res[$i]['type'] = @pg_fieldtype($id, $i);
- $res[$i]['len'] = @pg_fieldsize($id, $i);
- $res[$i]['flags'] = $got_string ? $this->_pgFieldflags($id, $i, $result) : '';
- }
-
- } else { // full
- $res['num_fields']= $count;
-
- for ($i=0; $i<$count; $i++) {
- $res[$i]['table'] = $got_string ? $case_func($result) : '';
- $res[$i]['name'] = $case_func(@pg_fieldname($id, $i));
- $res[$i]['type'] = @pg_fieldtype($id, $i);
- $res[$i]['len'] = @pg_fieldsize($id, $i);
- $res[$i]['flags'] = $got_string ? $this->_pgFieldFlags($id, $i, $result) : '';
-
- if ($mode & DB_TABLEINFO_ORDER) {
- $res['order'][$res[$i]['name']] = $i;
- }
- if ($mode & DB_TABLEINFO_ORDERTABLE) {
- $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
- }
- }
- }
-
- // free the result only if we were called on a table
- if ($got_string) {
- @pg_freeresult($id);
- }
- return $res;
- }
-
- // }}}
- // {{{ getTablesQuery()
-
- /**
- * Returns the query needed to get some backend info
- * @param string $type What kind of info you want to retrieve
- * @return string The SQL query string
- */
- function getSpecialQuery($type)
- {
- switch ($type) {
- case 'tables':
- return "SELECT c.relname as \"Name\"
- FROM pg_class c, pg_user u
- WHERE c.relowner = u.usesysid AND c.relkind = 'r'
- AND not exists (select 1 from pg_views where viewname = c.relname)
- AND c.relname !~ '^pg_'
- AND c.relname !~ '^sql_'
- UNION
- SELECT c.relname as \"Name\"
- FROM pg_class c
- WHERE c.relkind = 'r'
- AND not exists (select 1 from pg_views where viewname = c.relname)
- AND not exists (select 1 from pg_user where usesysid = c.relowner)
- AND c.relname !~ '^pg_'
- AND c.relname !~ '^sql_'";
- case 'views':
- // Table cols: viewname | viewowner | definition
- return 'SELECT viewname FROM pg_views';
- case 'users':
- // cols: usename |usesysid|usecreatedb|usetrace|usesuper|usecatupd|passwd |valuntil
- return 'SELECT usename FROM pg_user';
- case 'databases':
- return 'SELECT datname FROM pg_database';
- case 'functions':
- return 'SELECT proname FROM pg_proc';
- default:
- return null;
- }
- }
-
- // }}}
-
-}
-
-/*
- * Local variables:
- * tab-width: 4
- * c-basic-offset: 4
- * End:
- */
-
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 foldmethod=marker: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Urs Gehrig <urs@circle.ch> |
-// | Mika Tuupola <tuupola@appelsiini.net> |
-// | Maintainer: Daniel Convissor <danielc@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: sqlite.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
-
-require_once 'DB/common.php';
-
-/**
- * Database independent query interface definition for the SQLite
- * PECL extension.
- *
- * @package DB
- * @version $Id: sqlite.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
- * @category Database
- * @author Urs Gehrig <urs@circle.ch>
- * @author Mika Tuupola <tuupola@appelsiini.net>
- */
-class DB_sqlite extends DB_common
-{
- // {{{ properties
-
- var $connection;
- var $phptype, $dbsyntax;
- var $prepare_tokens = array();
- var $prepare_types = array();
- var $_lasterror = '';
-
- // }}}
- // {{{ constructor
-
- /**
- * Constructor for this class.
- *
- * Error codes according to sqlite_exec. Error Codes specification is
- * in the {@link http://sqlite.org/c_interface.html online manual}.
- *
- * This errorhandling based on sqlite_exec is not yet implemented.
- *
- * @access public
- */
- function DB_sqlite()
- {
-
- $this->DB_common();
- $this->phptype = 'sqlite';
- $this->dbsyntax = 'sqlite';
- $this->features = array (
- 'prepare' => false,
- 'pconnect' => true,
- 'transactions' => false,
- 'limit' => 'alter'
- );
-
- // SQLite data types, http://www.sqlite.org/datatypes.html
- $this->keywords = array (
- 'BLOB' => '',
- 'BOOLEAN' => '',
- 'CHARACTER' => '',
- 'CLOB' => '',
- 'FLOAT' => '',
- 'INTEGER' => '',
- 'KEY' => '',
- 'NATIONAL' => '',
- 'NUMERIC' => '',
- 'NVARCHAR' => '',
- 'PRIMARY' => '',
- 'TEXT' => '',
- 'TIMESTAMP' => '',
- 'UNIQUE' => '',
- 'VARCHAR' => '',
- 'VARYING' => ''
- );
- $this->errorcode_map = array(
- );
- }
-
- // }}}
- // {{{ connect()
-
- /**
- * Connect to a database represented by a file.
- *
- * @param $dsn the data source name; the file is taken as
- * database; "sqlite://root:@host/test.db?mode=0644"
- * @param $persistent (optional) whether the connection should
- * be persistent
- * @access public
- * @return int DB_OK on success, a DB error on failure
- */
- function connect($dsninfo, $persistent = false)
- {
- if (!DB::assertExtension('sqlite')) {
- return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
- }
-
- $this->dsn = $dsninfo;
-
- if ($dsninfo['database']) {
- if (!file_exists($dsninfo['database'])) {
- if (!touch($dsninfo['database'])) {
- return $this->sqliteRaiseError(DB_ERROR_NOT_FOUND);
- }
- if (!isset($dsninfo['mode']) ||
- !is_numeric($dsninfo['mode']))
- {
- $mode = 0644;
- } else {
- $mode = octdec($dsninfo['mode']);
- }
- if (!chmod($dsninfo['database'], $mode)) {
- return $this->sqliteRaiseError(DB_ERROR_NOT_FOUND);
- }
- if (!file_exists($dsninfo['database'])) {
- return $this->sqliteRaiseError(DB_ERROR_NOT_FOUND);
- }
- }
- if (!is_file($dsninfo['database'])) {
- return $this->sqliteRaiseError(DB_ERROR_INVALID);
- }
- if (!is_readable($dsninfo['database'])) {
- return $this->sqliteRaiseError(DB_ERROR_ACCESS_VIOLATION);
- }
- } else {
- return $this->sqliteRaiseError(DB_ERROR_ACCESS_VIOLATION);
- }
-
- $connect_function = $persistent ? 'sqlite_popen' : 'sqlite_open';
- if (!($conn = @$connect_function($dsninfo['database']))) {
- return $this->sqliteRaiseError(DB_ERROR_NODBSELECTED);
- }
- $this->connection = $conn;
-
- return DB_OK;
- }
-
- // }}}
- // {{{ disconnect()
-
- /**
- * Log out and disconnect from the database.
- *
- * @access public
- * @return bool true on success, false if not connected.
- * @todo fix return values
- */
- function disconnect()
- {
- $ret = @sqlite_close($this->connection);
- $this->connection = null;
- return $ret;
- }
-
- // }}}
- // {{{ simpleQuery()
-
- /**
- * Send a query to SQLite and returns the results as a SQLite resource
- * identifier.
- *
- * @param the SQL query
- * @access public
- * @return mixed returns a valid SQLite result for successful SELECT
- * queries, DB_OK for other successful queries. A DB error is
- * returned on failure.
- */
- function simpleQuery($query)
- {
- $ismanip = DB::isManip($query);
- $this->last_query = $query;
- $query = $this->_modifyQuery($query);
- ini_set('track_errors', true);
- $result = @sqlite_query($query, $this->connection);
- ini_restore('track_errors');
- $this->_lasterror = isset($php_errormsg) ? $php_errormsg : '';
- $this->result = $result;
- if (!$this->result) {
- return $this->sqliteRaiseError(null);
- }
-
- /* sqlite_query() seems to allways return a resource */
- /* so cant use that. Using $ismanip instead */
- if (!$ismanip) {
- $numRows = $this->numRows($result);
-
- /* if numRows() returned PEAR_Error */
- if (is_object($numRows)) {
- return $numRows;
- }
- return $result;
- }
- return DB_OK;
- }
-
- // }}}
- // {{{ nextResult()
-
- /**
- * Move the internal sqlite result pointer to the next available result.
- *
- * @param a valid sqlite result resource
- * @access public
- * @return true if a result is available otherwise return false
- */
- function nextResult($result)
- {
- return false;
- }
-
- // }}}
- // {{{ fetchInto()
-
- /**
- * Fetch a row and insert the data into an existing array.
- *
- * Formating of the array and the data therein are configurable.
- * See DB_result::fetchInto() for more information.
- *
- * @param resource $result query result identifier
- * @param array $arr (reference) array where data from the row
- * should be placed
- * @param int $fetchmode how the resulting array should be indexed
- * @param int $rownum the row number to fetch
- *
- * @return mixed DB_OK on success, null when end of result set is
- * reached or on failure
- *
- * @see DB_result::fetchInto()
- * @access private
- */
- function fetchInto($result, &$arr, $fetchmode, $rownum=null)
- {
- if ($rownum !== null) {
- if (!@sqlite_seek($this->result, $rownum)) {
- return null;
- }
- }
- if ($fetchmode & DB_FETCHMODE_ASSOC) {
- $arr = @sqlite_fetch_array($result, SQLITE_ASSOC);
- if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE && $arr) {
- $arr = array_change_key_case($arr, CASE_LOWER);
- }
- } else {
- $arr = @sqlite_fetch_array($result, SQLITE_NUM);
- }
- if (!$arr) {
- /* See: http://bugs.php.net/bug.php?id=22328 */
- return null;
- }
- if ($this->options['portability'] & DB_PORTABILITY_RTRIM) {
- /*
- * Even though this DBMS already trims output, we do this because
- * a field might have intentional whitespace at the end that
- * gets removed by DB_PORTABILITY_RTRIM under another driver.
- */
- $this->_rtrimArrayValues($arr);
- }
- if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) {
- $this->_convertNullArrayValuesToEmpty($arr);
- }
- return DB_OK;
- }
-
- // }}}
- // {{{ freeResult()
-
- /**
- * Free the internal resources associated with $result.
- *
- * @param $result SQLite result identifier
- * @access public
- * @return bool true on success, false if $result is invalid
- */
- function freeResult(&$result)
- {
- // XXX No native free?
- if (!is_resource($result)) {
- return false;
- }
- $result = null;
- return true;
- }
-
- // }}}
- // {{{ numCols()
-
- /**
- * Gets the number of columns in a result set.
- *
- * @return number of columns in a result set
- */
- function numCols($result)
- {
- $cols = @sqlite_num_fields($result);
- if (!$cols) {
- return $this->sqliteRaiseError();
- }
- return $cols;
- }
-
- // }}}
- // {{{ numRows()
-
- /**
- * Gets the number of rows affected by a query.
- *
- * @return number of rows affected by the last query
- */
- function numRows($result)
- {
- $rows = @sqlite_num_rows($result);
- if (!is_integer($rows)) {
- return $this->raiseError();
- }
- return $rows;
- }
-
- // }}}
- // {{{ affected()
-
- /**
- * Gets the number of rows affected by a query.
- *
- * @return number of rows affected by the last query
- */
- function affectedRows()
- {
- return @sqlite_changes($this->connection);
- }
-
- // }}}
- // {{{ errorNative()
-
- /**
- * Get the native error string of the last error (if any) that
- * occured on the current connection.
- *
- * This is used to retrieve more meaningfull error messages DB_pgsql
- * way since sqlite_last_error() does not provide adequate info.
- *
- * @return string native SQLite error message
- */
- function errorNative()
- {
- return($this->_lasterror);
- }
-
- // }}}
- // {{{ errorCode()
-
- /**
- * Determine PEAR::DB error code from the database's text error message.
- *
- * @param string $errormsg error message returned from the database
- * @return integer an error number from a DB error constant
- */
- function errorCode($errormsg)
- {
- static $error_regexps;
- if (!isset($error_regexps)) {
- $error_regexps = array(
- '/^no such table:/' => DB_ERROR_NOSUCHTABLE,
- '/^table .* already exists$/' => DB_ERROR_ALREADY_EXISTS,
- '/PRIMARY KEY must be unique/i' => DB_ERROR_CONSTRAINT,
- '/is not unique/' => DB_ERROR_CONSTRAINT,
- '/uniqueness constraint failed/' => DB_ERROR_CONSTRAINT,
- '/may not be NULL/' => DB_ERROR_CONSTRAINT_NOT_NULL,
- '/^no such column:/' => DB_ERROR_NOSUCHFIELD,
- '/^near ".*": syntax error$/' => DB_ERROR_SYNTAX
- );
- }
- foreach ($error_regexps as $regexp => $code) {
- if (preg_match($regexp, $errormsg)) {
- return $code;
- }
- }
- // Fall back to DB_ERROR if there was no mapping.
- return DB_ERROR;
- }
-
- // }}}
- // {{{ dropSequence()
-
- /**
- * Deletes a sequence
- *
- * @param string $seq_name name of the sequence to be deleted
- *
- * @return int DB_OK on success. DB_Error if problems.
- *
- * @internal
- * @see DB_common::dropSequence()
- * @access public
- */
- function dropSequence($seq_name)
- {
- $seqname = $this->getSequenceName($seq_name);
- return $this->query("DROP TABLE $seqname");
- }
-
- /**
- * Creates a new sequence
- *
- * @param string $seq_name name of the new sequence
- *
- * @return int DB_OK on success. A DB_Error object is returned if
- * problems arise.
- *
- * @internal
- * @see DB_common::createSequence()
- * @access public
- */
- function createSequence($seq_name)
- {
- $seqname = $this->getSequenceName($seq_name);
- $query = 'CREATE TABLE ' . $seqname .
- ' (id INTEGER UNSIGNED PRIMARY KEY) ';
- $result = $this->query($query);
- if (DB::isError($result)) {
- return($result);
- }
- $query = "CREATE TRIGGER ${seqname}_cleanup AFTER INSERT ON $seqname
- BEGIN
- DELETE FROM $seqname WHERE id<LAST_INSERT_ROWID();
- END ";
- $result = $this->query($query);
- if (DB::isError($result)) {
- return($result);
- }
- }
-
- // }}}
- // {{{ nextId()
-
- /**
- * Returns the next free id in a sequence
- *
- * @param string $seq_name name of the sequence
- * @param boolean $ondemand when true, the seqence is automatically
- * created if it does not exist
- *
- * @return int the next id number in the sequence. DB_Error if problem.
- *
- * @internal
- * @see DB_common::nextID()
- * @access public
- */
- function nextId($seq_name, $ondemand = true)
- {
- $seqname = $this->getSequenceName($seq_name);
-
- do {
- $repeat = 0;
- $this->pushErrorHandling(PEAR_ERROR_RETURN);
- $result = $this->query("INSERT INTO $seqname VALUES (NULL)");
- $this->popErrorHandling();
- if ($result === DB_OK) {
- $id = @sqlite_last_insert_rowid($this->connection);
- if ($id != 0) {
- return $id;
- }
- } elseif ($ondemand && DB::isError($result) &&
- $result->getCode() == DB_ERROR_NOSUCHTABLE)
- {
- $result = $this->createSequence($seq_name);
- if (DB::isError($result)) {
- return $this->raiseError($result);
- } else {
- $repeat = 1;
- }
- }
- } while ($repeat);
-
- return $this->raiseError($result);
- }
-
- // }}}
- // {{{ getSpecialQuery()
-
- /**
- * Returns the query needed to get some backend info.
- *
- * Refer to the online manual at http://sqlite.org/sqlite.html.
- *
- * @param string $type What kind of info you want to retrieve
- * @return string The SQL query string
- */
- function getSpecialQuery($type, $args=array())
- {
- if (!is_array($args))
- return $this->raiseError('no key specified', null, null, null,
- 'Argument has to be an array.');
- switch (strtolower($type)) {
- case 'master':
- return 'SELECT * FROM sqlite_master;';
- case 'tables':
- return "SELECT name FROM sqlite_master WHERE type='table' "
- . 'UNION ALL SELECT name FROM sqlite_temp_master '
- . "WHERE type='table' ORDER BY name;";
- case 'schema':
- return 'SELECT sql FROM (SELECT * FROM sqlite_master UNION ALL '
- . 'SELECT * FROM sqlite_temp_master) '
- . "WHERE type!='meta' ORDER BY tbl_name, type DESC, name;";
- case 'schemax':
- case 'schema_x':
- /*
- * Use like:
- * $res = $db->query($db->getSpecialQuery('schema_x', array('table' => 'table3')));
- */
- return 'SELECT sql FROM (SELECT * FROM sqlite_master UNION ALL '
- . 'SELECT * FROM sqlite_temp_master) '
- . "WHERE tbl_name LIKE '{$args['table']}' AND type!='meta' "
- . 'ORDER BY type DESC, name;';
- case 'alter':
- /*
- * SQLite does not support ALTER TABLE; this is a helper query
- * to handle this. 'table' represents the table name, 'rows'
- * the news rows to create, 'save' the row(s) to keep _with_
- * the data.
- *
- * Use like:
- * $args = array(
- * 'table' => $table,
- * 'rows' => "id INTEGER PRIMARY KEY, firstname TEXT, surname TEXT, datetime TEXT",
- * 'save' => "NULL, titel, content, datetime"
- * );
- * $res = $db->query( $db->getSpecialQuery('alter', $args));
- */
- $rows = strtr($args['rows'], $this->keywords);
-
- $q = array(
- 'BEGIN TRANSACTION',
- "CREATE TEMPORARY TABLE {$args['table']}_backup ({$args['rows']})",
- "INSERT INTO {$args['table']}_backup SELECT {$args['save']} FROM {$args['table']}",
- "DROP TABLE {$args['table']}",
- "CREATE TABLE {$args['table']} ({$args['rows']})",
- "INSERT INTO {$args['table']} SELECT {$rows} FROM {$args['table']}_backup",
- "DROP TABLE {$args['table']}_backup",
- 'COMMIT',
- );
-
- // This is a dirty hack, since the above query will no get executed with a single
- // query call; so here the query method will be called directly and return a select instead.
- foreach ($q as $query) {
- $this->query($query);
- }
- return "SELECT * FROM {$args['table']};";
- default:
- return null;
- }
- }
-
- // }}}
- // {{{ getDbFileStats()
-
- /**
- * Get the file stats for the current database.
- *
- * Possible arguments are dev, ino, mode, nlink, uid, gid, rdev, size,
- * atime, mtime, ctime, blksize, blocks or a numeric key between
- * 0 and 12.
- *
- * @param string $arg Array key for stats()
- * @return mixed array on an unspecified key, integer on a passed arg and
- * false at a stats error.
- */
- function getDbFileStats($arg = '')
- {
- $stats = stat($this->dsn['database']);
- if ($stats == false) {
- return false;
- }
- if (is_array($stats)) {
- if (is_numeric($arg)) {
- if (((int)$arg <= 12) & ((int)$arg >= 0)) {
- return false;
- }
- return $stats[$arg ];
- }
- if (array_key_exists(trim($arg), $stats)) {
- return $stats[$arg ];
- }
- }
- return $stats;
- }
-
- // }}}
- // {{{ escapeSimple()
-
- /**
- * Escape a string according to the current DBMS's standards
- *
- * In SQLite, this makes things safe for inserts/updates, but may
- * cause problems when performing text comparisons against columns
- * containing binary data. See the
- * {@link http://php.net/sqlite_escape_string PHP manual} for more info.
- *
- * @param string $str the string to be escaped
- *
- * @return string the escaped string
- *
- * @since 1.6.1
- * @see DB_common::escapeSimple()
- * @internal
- */
- function escapeSimple($str) {
- return @sqlite_escape_string($str);
- }
-
- // }}}
- // {{{ modifyLimitQuery()
-
- function modifyLimitQuery($query, $from, $count, $params = array())
- {
- $query = $query . " LIMIT $count OFFSET $from";
- return $query;
- }
-
- // }}}
- // {{{ modifyQuery()
-
- /**
- * "DELETE FROM table" gives 0 affected rows in SQLite.
- *
- * This little hack lets you know how many rows were deleted.
- *
- * @param string $query The SQL query string
- * @return string The SQL query string
- */
- function _modifyQuery($query)
- {
- if ($this->options['portability'] & DB_PORTABILITY_DELETE_COUNT) {
- if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $query)) {
- $query = preg_replace('/^\s*DELETE\s+FROM\s+(\S+)\s*$/',
- 'DELETE FROM \1 WHERE 1=1', $query);
- }
- }
- return $query;
- }
-
- // }}}
- // {{{ sqliteRaiseError()
-
- /**
- * Gather information about an error, then use that info to create a
- * DB error object and finally return that object.
- *
- * @param integer $errno PEAR error number (usually a DB constant) if
- * manually raising an error
- * @return object DB error object
- * @see errorNative()
- * @see errorCode()
- * @see DB_common::raiseError()
- */
- function sqliteRaiseError($errno = null)
- {
-
- $native = $this->errorNative();
- if ($errno === null) {
- $errno = $this->errorCode($native);
- }
-
- $errorcode = @sqlite_last_error($this->connection);
- $userinfo = "$errorcode ** $this->last_query";
-
- return $this->raiseError($errno, null, null, $userinfo, $native);
- }
-
- // }}}
-}
-
-/*
- * Local variables:
- * tab-width: 4
- * c-basic-offset: 4
- * End:
- */
-
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 foldmethod=marker: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Stig Bakken <stig@php.net> |
-// | Maintainer: Daniel Convissor <danielc@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: storage.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
-
-require_once 'DB.php';
-
-/**
- * Provides an object interface to a table row.
- *
- * It lets you add, delete and change rows using objects rather than SQL
- * statements.
- *
- * @package DB
- * @version $Id: storage.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
- * @category Database
- * @author Stig Bakken <stig@php.net>
- */
-class DB_storage extends PEAR
-{
- // {{{ properties
-
- /** the name of the table (or view, if the backend database supports
- updates in views) we hold data from */
- var $_table = null;
-
- /** which column(s) in the table contains primary keys, can be a
- string for single-column primary keys, or an array of strings
- for multiple-column primary keys */
- var $_keycolumn = null;
-
- /** DB connection handle used for all transactions */
- var $_dbh = null;
-
- /** an assoc with the names of database fields stored as properties
- in this object */
- var $_properties = array();
-
- /** an assoc with the names of the properties in this object that
- have been changed since they were fetched from the database */
- var $_changes = array();
-
- /** flag that decides if data in this object can be changed.
- objects that don't have their table's key column in their
- property lists will be flagged as read-only. */
- var $_readonly = false;
-
- /** function or method that implements a validator for fields that
- are set, this validator function returns true if the field is
- valid, false if not */
- var $_validator = null;
-
- // }}}
- // {{{ constructor
-
- /**
- * Constructor
- *
- * @param $table string the name of the database table
- *
- * @param $keycolumn mixed string with name of key column, or array of
- * strings if the table has a primary key of more than one column
- *
- * @param $dbh object database connection object
- *
- * @param $validator mixed function or method used to validate
- * each new value, called with three parameters: the name of the
- * field/column that is changing, a reference to the new value and
- * a reference to this object
- *
- */
- function DB_storage($table, $keycolumn, &$dbh, $validator = null)
- {
- $this->PEAR('DB_Error');
- $this->_table = $table;
- $this->_keycolumn = $keycolumn;
- $this->_dbh = $dbh;
- $this->_readonly = false;
- $this->_validator = $validator;
- }
-
- // }}}
- // {{{ _makeWhere()
-
- /**
- * Utility method to build a "WHERE" clause to locate ourselves in
- * the table.
- *
- * XXX future improvement: use rowids?
- *
- * @access private
- */
- function _makeWhere($keyval = null)
- {
- if (is_array($this->_keycolumn)) {
- if ($keyval === null) {
- for ($i = 0; $i < sizeof($this->_keycolumn); $i++) {
- $keyval[] = $this->{$this->_keycolumn[$i]};
- }
- }
- $whereclause = '';
- for ($i = 0; $i < sizeof($this->_keycolumn); $i++) {
- if ($i > 0) {
- $whereclause .= ' AND ';
- }
- $whereclause .= $this->_keycolumn[$i];
- if (is_null($keyval[$i])) {
- // there's not much point in having a NULL key,
- // but we support it anyway
- $whereclause .= ' IS NULL';
- } else {
- $whereclause .= ' = ' . $this->_dbh->quote($keyval[$i]);
- }
- }
- } else {
- if ($keyval === null) {
- $keyval = @$this->{$this->_keycolumn};
- }
- $whereclause = $this->_keycolumn;
- if (is_null($keyval)) {
- // there's not much point in having a NULL key,
- // but we support it anyway
- $whereclause .= ' IS NULL';
- } else {
- $whereclause .= ' = ' . $this->_dbh->quote($keyval);
- }
- }
- return $whereclause;
- }
-
- // }}}
- // {{{ setup()
-
- /**
- * Method used to initialize a DB_storage object from the
- * configured table.
- *
- * @param $keyval mixed the key[s] of the row to fetch (string or array)
- *
- * @return int DB_OK on success, a DB error if not
- */
- function setup($keyval)
- {
- $whereclause = $this->_makeWhere($keyval);
- $query = 'SELECT * FROM ' . $this->_table . ' WHERE ' . $whereclause;
- $sth = $this->_dbh->query($query);
- if (DB::isError($sth)) {
- return $sth;
- }
- $row = $sth->fetchRow(DB_FETCHMODE_ASSOC);
- if (DB::isError($row)) {
- return $row;
- }
- if (!$row) {
- return $this->raiseError(null, DB_ERROR_NOT_FOUND, null, null,
- $query, null, true);
- }
- foreach ($row as $key => $value) {
- $this->_properties[$key] = true;
- $this->$key = $value;
- }
- return DB_OK;
- }
-
- // }}}
- // {{{ insert()
-
- /**
- * Create a new (empty) row in the configured table for this
- * object.
- */
- function insert($newpk)
- {
- if (is_array($this->_keycolumn)) {
- $primarykey = $this->_keycolumn;
- } else {
- $primarykey = array($this->_keycolumn);
- }
- settype($newpk, "array");
- for ($i = 0; $i < sizeof($primarykey); $i++) {
- $pkvals[] = $this->_dbh->quote($newpk[$i]);
- }
-
- $sth = $this->_dbh->query("INSERT INTO $this->_table (" .
- implode(",", $primarykey) . ") VALUES(" .
- implode(",", $pkvals) . ")");
- if (DB::isError($sth)) {
- return $sth;
- }
- if (sizeof($newpk) == 1) {
- $newpk = $newpk[0];
- }
- $this->setup($newpk);
- }
-
- // }}}
- // {{{ toString()
-
- /**
- * Output a simple description of this DB_storage object.
- * @return string object description
- */
- function toString()
- {
- $info = strtolower(get_class($this));
- $info .= " (table=";
- $info .= $this->_table;
- $info .= ", keycolumn=";
- if (is_array($this->_keycolumn)) {
- $info .= "(" . implode(",", $this->_keycolumn) . ")";
- } else {
- $info .= $this->_keycolumn;
- }
- $info .= ", dbh=";
- if (is_object($this->_dbh)) {
- $info .= $this->_dbh->toString();
- } else {
- $info .= "null";
- }
- $info .= ")";
- if (sizeof($this->_properties)) {
- $info .= " [loaded, key=";
- $keyname = $this->_keycolumn;
- if (is_array($keyname)) {
- $info .= "(";
- for ($i = 0; $i < sizeof($keyname); $i++) {
- if ($i > 0) {
- $info .= ",";
- }
- $info .= $this->$keyname[$i];
- }
- $info .= ")";
- } else {
- $info .= $this->$keyname;
- }
- $info .= "]";
- }
- if (sizeof($this->_changes)) {
- $info .= " [modified]";
- }
- return $info;
- }
-
- // }}}
- // {{{ dump()
-
- /**
- * Dump the contents of this object to "standard output".
- */
- function dump()
- {
- foreach ($this->_properties as $prop => $foo) {
- print "$prop = ";
- print htmlentities($this->$prop);
- print "<br />\n";
- }
- }
-
- // }}}
- // {{{ &create()
-
- /**
- * Static method used to create new DB storage objects.
- * @param $data assoc. array where the keys are the names
- * of properties/columns
- * @return object a new instance of DB_storage or a subclass of it
- */
- function &create($table, &$data)
- {
- $classname = strtolower(get_class($this));
- $obj =& new $classname($table);
- foreach ($data as $name => $value) {
- $obj->_properties[$name] = true;
- $obj->$name = &$value;
- }
- return $obj;
- }
-
- // }}}
- // {{{ loadFromQuery()
-
- /**
- * Loads data into this object from the given query. If this
- * object already contains table data, changes will be saved and
- * the object re-initialized first.
- *
- * @param $query SQL query
- *
- * @param $params parameter list in case you want to use
- * prepare/execute mode
- *
- * @return int DB_OK on success, DB_WARNING_READ_ONLY if the
- * returned object is read-only (because the object's specified
- * key column was not found among the columns returned by $query),
- * or another DB error code in case of errors.
- */
-// XXX commented out for now
-/*
- function loadFromQuery($query, $params = null)
- {
- if (sizeof($this->_properties)) {
- if (sizeof($this->_changes)) {
- $this->store();
- $this->_changes = array();
- }
- $this->_properties = array();
- }
- $rowdata = $this->_dbh->getRow($query, DB_FETCHMODE_ASSOC, $params);
- if (DB::isError($rowdata)) {
- return $rowdata;
- }
- reset($rowdata);
- $found_keycolumn = false;
- while (list($key, $value) = each($rowdata)) {
- if ($key == $this->_keycolumn) {
- $found_keycolumn = true;
- }
- $this->_properties[$key] = true;
- $this->$key = &$value;
- unset($value); // have to unset, or all properties will
- // refer to the same value
- }
- if (!$found_keycolumn) {
- $this->_readonly = true;
- return DB_WARNING_READ_ONLY;
- }
- return DB_OK;
- }
- */
-
- // }}}
- // {{{ set()
-
- /**
- * Modify an attriute value.
- */
- function set($property, $newvalue)
- {
- // only change if $property is known and object is not
- // read-only
- if ($this->_readonly) {
- return $this->raiseError(null, DB_WARNING_READ_ONLY, null,
- null, null, null, true);
- }
- if (@isset($this->_properties[$property])) {
- if (empty($this->_validator)) {
- $valid = true;
- } else {
- $valid = @call_user_func($this->_validator,
- $this->_table,
- $property,
- $newvalue,
- $this->$property,
- $this);
- }
- if ($valid) {
- $this->$property = $newvalue;
- if (empty($this->_changes[$property])) {
- $this->_changes[$property] = 0;
- } else {
- $this->_changes[$property]++;
- }
- } else {
- return $this->raiseError(null, DB_ERROR_INVALID, null,
- null, "invalid field: $property",
- null, true);
- }
- return true;
- }
- return $this->raiseError(null, DB_ERROR_NOSUCHFIELD, null,
- null, "unknown field: $property",
- null, true);
- }
-
- // }}}
- // {{{ &get()
-
- /**
- * Fetch an attribute value.
- *
- * @param string attribute name
- *
- * @return attribute contents, or null if the attribute name is
- * unknown
- */
- function &get($property)
- {
- // only return if $property is known
- if (isset($this->_properties[$property])) {
- return $this->$property;
- }
- $tmp = null;
- return $tmp;
- }
-
- // }}}
- // {{{ _DB_storage()
-
- /**
- * Destructor, calls DB_storage::store() if there are changes
- * that are to be kept.
- */
- function _DB_storage()
- {
- if (sizeof($this->_changes)) {
- $this->store();
- }
- $this->_properties = array();
- $this->_changes = array();
- $this->_table = null;
- }
-
- // }}}
- // {{{ store()
-
- /**
- * Stores changes to this object in the database.
- *
- * @return DB_OK or a DB error
- */
- function store()
- {
- foreach ($this->_changes as $name => $foo) {
- $params[] = &$this->$name;
- $vars[] = $name . ' = ?';
- }
- if ($vars) {
- $query = 'UPDATE ' . $this->_table . ' SET ' .
- implode(', ', $vars) . ' WHERE ' .
- $this->_makeWhere();
- $stmt = $this->_dbh->prepare($query);
- $res = $this->_dbh->execute($stmt, $params);
- if (DB::isError($res)) {
- return $res;
- }
- $this->_changes = array();
- }
- return DB_OK;
- }
-
- // }}}
- // {{{ remove()
-
- /**
- * Remove the row represented by this object from the database.
- *
- * @return mixed DB_OK or a DB error
- */
- function remove()
- {
- if ($this->_readonly) {
- return $this->raiseError(null, DB_WARNING_READ_ONLY, null,
- null, null, null, true);
- }
- $query = 'DELETE FROM ' . $this->_table .' WHERE '.
- $this->_makeWhere();
- $res = $this->_dbh->query($query);
- if (DB::isError($res)) {
- return $res;
- }
- foreach ($this->_properties as $prop => $foo) {
- unset($this->$prop);
- }
- $this->_properties = array();
- $this->_changes = array();
- return DB_OK;
- }
-
- // }}}
-}
-
-/*
- * Local variables:
- * tab-width: 4
- * c-basic-offset: 4
- * End:
- */
-
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 foldmethod=marker: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Sterling Hughes <sterling@php.net> |
-// | Antônio Carlos Venâncio Júnior <floripa@php.net> |
-// | Maintainer: Daniel Convissor <danielc@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: sybase.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
-
-
-// TODO
-// - This driver may fail with multiple connections under the same
-// user/pass/host and different databases
-
-
-require_once 'DB/common.php';
-
-/**
- * Database independent query interface definition for PHP's Sybase
- * extension.
- *
- * @package DB
- * @version $Id: sybase.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
- * @category Database
- * @author Sterling Hughes <sterling@php.net>
- * @author Antônio Carlos Venâncio Júnior <floripa@php.net>
- */
-class DB_sybase extends DB_common
-{
- // {{{ properties
-
- var $connection;
- var $phptype, $dbsyntax;
- var $prepare_tokens = array();
- var $prepare_types = array();
- var $transaction_opcount = 0;
- var $autocommit = true;
-
- // }}}
- // {{{ constructor
-
- /**
- * DB_sybase constructor.
- *
- * @access public
- */
- function DB_sybase()
- {
- $this->DB_common();
- $this->phptype = 'sybase';
- $this->dbsyntax = 'sybase';
- $this->features = array(
- 'prepare' => false,
- 'pconnect' => true,
- 'transactions' => false,
- 'limit' => 'emulate'
- );
- $this->errorcode_map = array(
- );
- }
-
- // }}}
- // {{{ connect()
-
- /**
- * Connect to a database and log in as the specified user.
- *
- * @param $dsn the data source name (see DB::parseDSN for syntax)
- * @param $persistent (optional) whether the connection should
- * be persistent
- * @access public
- * @return int DB_OK on success, a DB error on failure
- */
- function connect($dsninfo, $persistent = false)
- {
- if (!DB::assertExtension('sybase') &&
- !DB::assertExtension('sybase_ct'))
- {
- return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
- }
-
- $this->dsn = $dsninfo;
-
- $interface = $dsninfo['hostspec'] ? $dsninfo['hostspec'] : 'localhost';
- $connect_function = $persistent ? 'sybase_pconnect' : 'sybase_connect';
-
- if ($interface && $dsninfo['username'] && $dsninfo['password']) {
- $conn = @$connect_function($interface, $dsninfo['username'],
- $dsninfo['password']);
- } elseif ($interface && $dsninfo['username']) {
- /*
- * Using false for pw as a workaround to avoid segfault.
- * See PEAR bug 631
- */
- $conn = @$connect_function($interface, $dsninfo['username'],
- false);
- } else {
- $conn = false;
- }
-
- if (!$conn) {
- return $this->raiseError(DB_ERROR_CONNECT_FAILED);
- }
-
- if ($dsninfo['database']) {
- if (!@sybase_select_db($dsninfo['database'], $conn)) {
- return $this->raiseError(DB_ERROR_NODBSELECTED, null,
- null, null, @sybase_get_last_message());
- }
- $this->_db = $dsninfo['database'];
- }
-
- $this->connection = $conn;
- return DB_OK;
- }
-
- // }}}
- // {{{ disconnect()
-
- /**
- * Log out and disconnect from the database.
- *
- * @access public
- *
- * @return bool true on success, false if not connected.
- */
- function disconnect()
- {
- $ret = @sybase_close($this->connection);
- $this->connection = null;
- return $ret;
- }
-
- // }}}
- // {{{ errorNative()
-
- /**
- * Get the last server error messge (if any)
- *
- * @return string sybase last error message
- */
- function errorNative()
- {
- return @sybase_get_last_message();
- }
-
- // }}}
- // {{{ errorCode()
-
- /**
- * Determine PEAR::DB error code from the database's text error message.
- *
- * @param string $errormsg error message returned from the database
- * @return integer an error number from a DB error constant
- */
- function errorCode($errormsg)
- {
- static $error_regexps;
- if (!isset($error_regexps)) {
- $error_regexps = array(
- '/Incorrect syntax near/'
- => DB_ERROR_SYNTAX,
- '/^Unclosed quote before the character string [\"\'].*[\"\']\./'
- => DB_ERROR_SYNTAX,
- '/Implicit conversion from datatype [\"\'].+[\"\'] to [\"\'].+[\"\'] is not allowed\./'
- => DB_ERROR_INVALID_NUMBER,
- '/Cannot drop the table [\"\'].+[\"\'], because it doesn\'t exist in the system catalogs\./'
- => DB_ERROR_NOSUCHTABLE,
- '/Only the owner of object [\"\'].+[\"\'] or a user with System Administrator \(SA\) role can run this command\./'
- => DB_ERROR_ACCESS_VIOLATION,
- '/^.+ permission denied on object .+, database .+, owner .+/'
- => DB_ERROR_ACCESS_VIOLATION,
- '/^.* permission denied, database .+, owner .+/'
- => DB_ERROR_ACCESS_VIOLATION,
- '/[^.*] not found\./'
- => DB_ERROR_NOSUCHTABLE,
- '/There is already an object named/'
- => DB_ERROR_ALREADY_EXISTS,
- '/Invalid column name/'
- => DB_ERROR_NOSUCHFIELD,
- '/does not allow null values/'
- => DB_ERROR_CONSTRAINT_NOT_NULL,
- '/Command has been aborted/'
- => DB_ERROR_CONSTRAINT,
- );
- }
-
- foreach ($error_regexps as $regexp => $code) {
- if (preg_match($regexp, $errormsg)) {
- return $code;
- }
- }
- return DB_ERROR;
- }
-
- // }}}
- // {{{ sybaseRaiseError()
-
- /**
- * Gather information about an error, then use that info to create a
- * DB error object and finally return that object.
- *
- * @param integer $errno PEAR error number (usually a DB constant) if
- * manually raising an error
- * @return object DB error object
- * @see errorNative()
- * @see errorCode()
- * @see DB_common::raiseError()
- */
- function sybaseRaiseError($errno = null)
- {
- $native = $this->errorNative();
- if ($errno === null) {
- $errno = $this->errorCode($native);
- }
- return $this->raiseError($errno, null, null, null, $native);
- }
-
- // }}}
- // {{{ simpleQuery()
-
- /**
- * Send a query to Sybase and return the results as a Sybase resource
- * identifier.
- *
- * @param the SQL query
- *
- * @access public
- *
- * @return mixed returns a valid Sybase result for successful SELECT
- * queries, DB_OK for other successful queries. A DB error is
- * returned on failure.
- */
- function simpleQuery($query)
- {
- $ismanip = DB::isManip($query);
- $this->last_query = $query;
- if (!@sybase_select_db($this->_db, $this->connection)) {
- return $this->sybaseRaiseError(DB_ERROR_NODBSELECTED);
- }
- $query = $this->modifyQuery($query);
- if (!$this->autocommit && $ismanip) {
- if ($this->transaction_opcount == 0) {
- $result = @sybase_query('BEGIN TRANSACTION', $this->connection);
- if (!$result) {
- return $this->sybaseRaiseError();
- }
- }
- $this->transaction_opcount++;
- }
- $result = @sybase_query($query, $this->connection);
- if (!$result) {
- return $this->sybaseRaiseError();
- }
- if (is_resource($result)) {
- $numrows = $this->numRows($result);
- if (is_object($numrows)) {
- return $numrows;
- }
- $this->num_rows[(int)$result] = $numrows;
- return $result;
- }
- // Determine which queries that should return data, and which
- // should return an error code only.
- return $ismanip ? DB_OK : $result;
- }
-
- // }}}
- // {{{ nextResult()
-
- /**
- * Move the internal sybase result pointer to the next available result
- *
- * @param a valid sybase result resource
- *
- * @access public
- *
- * @return true if a result is available otherwise return false
- */
- function nextResult($result)
- {
- return false;
- }
-
- // }}}
- // {{{ fetchInto()
-
- /**
- * Fetch a row and insert the data into an existing array.
- *
- * Formating of the array and the data therein are configurable.
- * See DB_result::fetchInto() for more information.
- *
- * @param resource $result query result identifier
- * @param array $arr (reference) array where data from the row
- * should be placed
- * @param int $fetchmode how the resulting array should be indexed
- * @param int $rownum the row number to fetch
- *
- * @return mixed DB_OK on success, null when end of result set is
- * reached or on failure
- *
- * @see DB_result::fetchInto()
- * @access private
- */
- function fetchInto($result, &$arr, $fetchmode, $rownum=null)
- {
- if ($rownum !== null) {
- if (!@sybase_data_seek($result, $rownum)) {
- return null;
- }
- }
- if ($fetchmode & DB_FETCHMODE_ASSOC) {
- if (function_exists('sybase_fetch_assoc')) {
- $arr = @sybase_fetch_assoc($result);
- } else {
- if ($arr = @sybase_fetch_array($result)) {
- foreach ($arr as $key => $value) {
- if (is_int($key)) {
- unset($arr[$key]);
- }
- }
- }
- }
- if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE && $arr) {
- $arr = array_change_key_case($arr, CASE_LOWER);
- }
- } else {
- $arr = @sybase_fetch_row($result);
- }
- if (!$arr) {
- // reported not work as seems that sybase_get_last_message()
- // always return a message here
- //if ($errmsg = @sybase_get_last_message()) {
- // return $this->sybaseRaiseError($errmsg);
- //} else {
- return null;
- //}
- }
- if ($this->options['portability'] & DB_PORTABILITY_RTRIM) {
- $this->_rtrimArrayValues($arr);
- }
- if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) {
- $this->_convertNullArrayValuesToEmpty($arr);
- }
- return DB_OK;
- }
-
- // }}}
- // {{{ freeResult()
-
- /**
- * Free the internal resources associated with $result.
- *
- * @param $result Sybase result identifier
- *
- * @access public
- *
- * @return bool true on success, false if $result is invalid
- */
- function freeResult($result)
- {
- unset($this->num_rows[(int)$result]);
- return @sybase_free_result($result);
- }
-
- // }}}
- // {{{ numCols()
-
- /**
- * Get the number of columns in a result set.
- *
- * @param $result Sybase result identifier
- *
- * @access public
- *
- * @return int the number of columns per row in $result
- */
- function numCols($result)
- {
- $cols = @sybase_num_fields($result);
- if (!$cols) {
- return $this->sybaseRaiseError();
- }
- return $cols;
- }
-
- // }}}
- // {{{ numRows()
-
- /**
- * Get the number of rows in a result set.
- *
- * @param $result Sybase result identifier
- *
- * @access public
- *
- * @return int the number of rows in $result
- */
- function numRows($result)
- {
- $rows = @sybase_num_rows($result);
- if ($rows === false) {
- return $this->sybaseRaiseError();
- }
- return $rows;
- }
-
- // }}}
- // {{{ affectedRows()
-
- /**
- * Gets the number of rows affected by the data manipulation
- * query. For other queries, this function returns 0.
- *
- * @return number of rows affected by the last query
- */
- function affectedRows()
- {
- if (DB::isManip($this->last_query)) {
- $result = @sybase_affected_rows($this->connection);
- } else {
- $result = 0;
- }
- return $result;
- }
-
- // }}}
- // {{{ nextId()
-
- /**
- * Returns the next free id in a sequence
- *
- * @param string $seq_name name of the sequence
- * @param boolean $ondemand when true, the seqence is automatically
- * created if it does not exist
- *
- * @return int the next id number in the sequence. DB_Error if problem.
- *
- * @internal
- * @see DB_common::nextID()
- * @access public
- */
- function nextId($seq_name, $ondemand = true)
- {
- $seqname = $this->getSequenceName($seq_name);
- if (!@sybase_select_db($this->_db, $this->connection)) {
- return $this->sybaseRaiseError(DB_ERROR_NODBSELECTED);
- }
- $repeat = 0;
- do {
- $this->pushErrorHandling(PEAR_ERROR_RETURN);
- $result = $this->query("INSERT INTO $seqname (vapor) VALUES (0)");
- $this->popErrorHandling();
- if ($ondemand && DB::isError($result) &&
- ($result->getCode() == DB_ERROR || $result->getCode() == DB_ERROR_NOSUCHTABLE))
- {
- $repeat = 1;
- $result = $this->createSequence($seq_name);
- if (DB::isError($result)) {
- return $this->raiseError($result);
- }
- } elseif (!DB::isError($result)) {
- $result =& $this->query("SELECT @@IDENTITY FROM $seqname");
- $repeat = 0;
- } else {
- $repeat = false;
- }
- } while ($repeat);
- if (DB::isError($result)) {
- return $this->raiseError($result);
- }
- $result = $result->fetchRow(DB_FETCHMODE_ORDERED);
- return $result[0];
- }
-
- /**
- * Creates a new sequence
- *
- * @param string $seq_name name of the new sequence
- *
- * @return int DB_OK on success. A DB_Error object is returned if
- * problems arise.
- *
- * @internal
- * @see DB_common::createSequence()
- * @access public
- */
- function createSequence($seq_name)
- {
- $seqname = $this->getSequenceName($seq_name);
- return $this->query("CREATE TABLE $seqname ".
- '(id numeric(10,0) IDENTITY NOT NULL ,' .
- 'vapor int NULL)');
- }
-
- // }}}
- // {{{ dropSequence()
-
- /**
- * Deletes a sequence
- *
- * @param string $seq_name name of the sequence to be deleted
- *
- * @return int DB_OK on success. DB_Error if problems.
- *
- * @internal
- * @see DB_common::dropSequence()
- * @access public
- */
- function dropSequence($seq_name)
- {
- $seqname = $this->getSequenceName($seq_name);
- return $this->query("DROP TABLE $seqname");
- }
-
- // }}}
- // {{{ getSpecialQuery()
-
- /**
- * Returns the query needed to get some backend info
- * @param string $type What kind of info you want to retrieve
- * @return string The SQL query string
- */
- function getSpecialQuery($type)
- {
- switch ($type) {
- case 'tables':
- return "select name from sysobjects where type = 'U' order by name";
- case 'views':
- return "select name from sysobjects where type = 'V'";
- default:
- return null;
- }
- }
-
- // }}}
- // {{{ autoCommit()
-
- /**
- * Enable/disable automatic commits
- */
- function autoCommit($onoff = false)
- {
- // XXX if $this->transaction_opcount > 0, we should probably
- // issue a warning here.
- $this->autocommit = $onoff ? true : false;
- return DB_OK;
- }
-
- // }}}
- // {{{ commit()
-
- /**
- * Commit the current transaction.
- */
- function commit()
- {
- if ($this->transaction_opcount > 0) {
- if (!@sybase_select_db($this->_db, $this->connection)) {
- return $this->sybaseRaiseError(DB_ERROR_NODBSELECTED);
- }
- $result = @sybase_query('COMMIT', $this->connection);
- $this->transaction_opcount = 0;
- if (!$result) {
- return $this->sybaseRaiseError();
- }
- }
- return DB_OK;
- }
-
- // }}}
- // {{{ rollback()
-
- /**
- * Roll back (undo) the current transaction.
- */
- function rollback()
- {
- if ($this->transaction_opcount > 0) {
- if (!@sybase_select_db($this->_db, $this->connection)) {
- return $this->sybaseRaiseError(DB_ERROR_NODBSELECTED);
- }
- $result = @sybase_query('ROLLBACK', $this->connection);
- $this->transaction_opcount = 0;
- if (!$result) {
- return $this->sybaseRaiseError();
- }
- }
- return DB_OK;
- }
-
- // }}}
- // {{{ tableInfo()
-
- /**
- * Returns information about a table or a result set.
- *
- * NOTE: only supports 'table' and 'flags' if <var>$result</var>
- * is a table name.
- *
- * @param object|string $result DB_result object from a query or a
- * string containing the name of a table
- * @param int $mode a valid tableInfo mode
- * @return array an associative array with the information requested
- * or an error object if something is wrong
- * @access public
- * @internal
- * @since 1.6.0
- * @see DB_common::tableInfo()
- */
- function tableInfo($result, $mode = null)
- {
- if (isset($result->result)) {
- /*
- * Probably received a result object.
- * Extract the result resource identifier.
- */
- $id = $result->result;
- $got_string = false;
- } elseif (is_string($result)) {
- /*
- * Probably received a table name.
- * Create a result resource identifier.
- */
- if (!@sybase_select_db($this->_db, $this->connection)) {
- return $this->sybaseRaiseError(DB_ERROR_NODBSELECTED);
- }
- $id = @sybase_query("SELECT * FROM $result WHERE 1=0",
- $this->connection);
- $got_string = true;
- } else {
- /*
- * Probably received a result resource identifier.
- * Copy it.
- * Depricated. Here for compatibility only.
- */
- $id = $result;
- $got_string = false;
- }
-
- if (!is_resource($id)) {
- return $this->sybaseRaiseError(DB_ERROR_NEED_MORE_DATA);
- }
-
- if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) {
- $case_func = 'strtolower';
- } else {
- $case_func = 'strval';
- }
-
- $count = @sybase_num_fields($id);
-
- // made this IF due to performance (one if is faster than $count if's)
- if (!$mode) {
-
- for ($i=0; $i<$count; $i++) {
- $f = @sybase_fetch_field($id, $i);
-
- // column_source is often blank
- if ($got_string) {
- $res[$i]['table'] = $case_func($result);
- } else {
- $res[$i]['table'] = $case_func($f->column_source);
- }
- $res[$i]['name'] = $case_func($f->name);
- $res[$i]['type'] = $f->type;
- $res[$i]['len'] = $f->max_length;
- if ($res[$i]['table']) {
- $res[$i]['flags'] = $this->_sybase_field_flags(
- $res[$i]['table'], $res[$i]['name']);
- } else {
- $res[$i]['flags'] = '';
- }
- }
-
- } else {
- // get full info
-
- $res['num_fields'] = $count;
-
- for ($i=0; $i<$count; $i++) {
- $f = @sybase_fetch_field($id, $i);
-
- // column_source is often blank
- if ($got_string) {
- $res[$i]['table'] = $case_func($result);
- } else {
- $res[$i]['table'] = $case_func($f->column_source);
- }
- $res[$i]['name'] = $case_func($f->name);
- $res[$i]['type'] = $f->type;
- $res[$i]['len'] = $f->max_length;
- if ($res[$i]['table']) {
- $res[$i]['flags'] = $this->_sybase_field_flags(
- $res[$i]['table'], $res[$i]['name']);
- } else {
- $res[$i]['flags'] = '';
- }
-
- if ($mode & DB_TABLEINFO_ORDER) {
- $res['order'][$res[$i]['name']] = $i;
- }
- if ($mode & DB_TABLEINFO_ORDERTABLE) {
- $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
- }
- }
- }
-
- // free the result only if we were called on a table
- if ($got_string) {
- @sybase_free_result($id);
- }
- return $res;
- }
-
- // }}}
- // {{{ _sybase_field_flags()
-
- /**
- * Get the flags for a field.
- *
- * Currently supports:
- * + <samp>unique_key</samp> (unique index, unique check or primary_key)
- * + <samp>multiple_key</samp> (multi-key index)
- *
- * @param string $table table name
- * @param string $column field name
- * @return string space delimited string of flags. Empty string if none.
- * @access private
- */
- function _sybase_field_flags($table, $column)
- {
- static $tableName = null;
- static $flags = array();
-
- if ($table != $tableName) {
- $flags = array();
- $tableName = $table;
-
- // get unique/primary keys
- $res = $this->getAll("sp_helpindex $table", DB_FETCHMODE_ASSOC);
-
- if (!isset($res[0]['index_description'])) {
- return '';
- }
-
- foreach ($res as $val) {
- $keys = explode(', ', trim($val['index_keys']));
-
- if (sizeof($keys) > 1) {
- foreach ($keys as $key) {
- $this->_add_flag($flags[$key], 'multiple_key');
- }
- }
-
- if (strpos($val['index_description'], 'unique')) {
- foreach ($keys as $key) {
- $this->_add_flag($flags[$key], 'unique_key');
- }
- }
- }
-
- }
-
- if (array_key_exists($column, $flags)) {
- return(implode(' ', $flags[$column]));
- }
-
- return '';
- }
-
- // }}}
- // {{{ _add_flag()
-
- /**
- * Adds a string to the flags array if the flag is not yet in there
- * - if there is no flag present the array is created.
- *
- * @param array $array reference of flags array to add a value to
- * @param mixed $value value to add to the flag array
- * @access private
- */
- function _add_flag(&$array, $value)
- {
- if (!is_array($array)) {
- $array = array($value);
- } elseif (!in_array($value, $array)) {
- array_push($array, $value);
- }
- }
-
- // }}}
- // {{{ quoteIdentifier()
-
- /**
- * Quote a string so it can be safely used as a table / column name
- *
- * Quoting style depends on which database driver is being used.
- *
- * @param string $str identifier name to be quoted
- *
- * @return string quoted identifier string
- *
- * @since 1.6.0
- * @access public
- */
- function quoteIdentifier($str)
- {
- return '[' . str_replace(']', ']]', $str) . ']';
- }
-
- // }}}
-
-}
-
-/*
- * Local variables:
- * tab-width: 4
- * c-basic-offset: 4
- * End:
- */
-
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */
-
-// {{{ Header
-
-/**
- * Generic date handling class for PEAR
- *
- * Handles time zones and changes from local standard to local Summer
- * time (daylight-saving time) through the Date_TimeZone class.
- * Supports several operations from Date_Calc on Date objects.
- *
- * PHP versions 4 and 5
- *
- * LICENSE:
- *
- * Copyright (c) 1997-2007 Baba Buehler, Pierre-Alain Joye, Firman
- * Wandayandi, C.A. Woodcock
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted under the terms of the BSD License.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
- * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
- * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- *
- * @category Date and Time
- * @package Date
- * @author Baba Buehler <baba@babaz.com>
- * @author Pierre-Alain Joye <pajoye@php.net>
- * @author Firman Wandayandi <firman@php.net>
- * @author C.A. Woodcock <c01234@netcomuk.co.uk>
- * @copyright 1997-2007 Baba Buehler, Pierre-Alain Joye, Firman Wandayandi, C.A. Woodcock
- * @license http://www.opensource.org/licenses/bsd-license.php
- * BSD License
- * @version CVS: $Id: Date.php,v 1.1.1.1 2008/04/28 15:20:46 jamie Exp $
- * @link http://pear.php.net/package/Date
- */
-
-
-// }}}
-// {{{ Error constants
-
-define('DATE_ERROR_INVALIDDATE', 1);
-define('DATE_ERROR_INVALIDTIME', 2);
-define('DATE_ERROR_INVALIDTIMEZONE', 3);
-define('DATE_ERROR_INVALIDDATEFORMAT', 4);
-define('DATE_ERROR_INVALIDFORMATSTRING', 5);
-
-
-// }}}
-// {{{ Includes
-
-require_once 'PEAR.php';
-
-/**
- * Load Date_TimeZone
- */
-require_once 'Date/TimeZone.php';
-
-/**
- * Load Date_Calc
- */
-require_once 'Date/Calc.php';
-
-/**
- * Load Date_Span
- */
-require_once 'Date/Span.php';
-
-
-// }}}
-// {{{ General constants
-
-/**
- * Whether to capture the micro-time (in microseconds) by default
- * in calls to 'Date::setNow()'. Note that this makes a call to
- * 'gettimeofday()', which may not work on all systems.
- *
- * @since Constant available since Release 1.5.0
- */
-define('DATE_CAPTURE_MICROTIME_BY_DEFAULT', false);
-
-/**
- * Whether to correct, by adding the local Summer time offset, the
- * specified time if it falls in the 'skipped hour' (encountered
- * when the clocks go forward).
- *
- * N.B. if specified as 'false', and if a time zone that adjusts
- * for Summer time is specified, then an object of this class will
- * be set to a semi-invalid state if an invalid time is set. That
- * is, an error will not be returned, unless the user then calls
- * a function, directly or indirectly, that accesses the time
- * part of the object. So, for example, if the user calls:
- *
- * <code>$date_object->format2('HH.MI.SS')</code> or:
- * <code>$date->object->addSeconds(30)</code>,
- *
- * an error will be returned if the time is invalid. However,
- * if the user calls:
- *
- * <code>$date->object->addDays(1)</code>,
- *
- * for example, such that the time is no longer invalid, then the
- * object will no longer be in this invalid state. This behaviour
- * is intended to minimize unexpected errors when a user uses the
- * class to do addition with days only, and does not intend to
- * access the time.
- *
- * Of course, this constant will be unused if the user chooses to
- * work in UTC or a time zone without Summer time, in which case
- * this situation will never arise.
- *
- * This constant is set to 'true' by default for backwards-compatibility
- * reasons, however, you are recommended to set it to 'false'. Note that the
- * behaviour is not intended to match that of previous versions of the class
- * in terms of ignoring the Summer time offset when making calculations which
- * involve dates in both standard and Summer time - this was recognized as a
- * bug - but in terms of returning a PEAR error object when the user sets the
- * object to an invalid date (i.e. a time in the hour which is skipped when
- * the clocks go forwards, which in Europe would be a time such as 01.30).
- * Backwards compatibility here means that the behaviour is the same as it
- * used to be, less the bug.
- *
- * Note that this problem is not an issue for the user if:
- *
- * (a) the user uses a time zone that does not observe Summer time, e.g. UTC
- * (b) the user never accesses the time, that is, he never makes a call to
- * Date::getHour() or Date::format("%H"), for example, even if he sets
- * the time to something invalid
- * (c) the user sets DATE_CORRECTINVALIDTIME_DEFAULT to true
- *
- * @since Constant available since Release 1.5.0
- */
-define('DATE_CORRECTINVALIDTIME_DEFAULT', true);
-
-/**
- * Whether to validate dates (i.e. day-month-year, ignoring the time) by
- * disallowing invalid dates (e.g. 31st February) being set by the following
- * functions:
- *
- * Date::setYear()
- * Date::setMonth()
- * Date::setDay()
- *
- * If the constant is set to 'true', then the date will be checked (by
- * default), and if invalid, an error will be returned with the Date object
- * left unmodified.
- *
- * This constant is set to 'false' by default for backwards-compatibility
- * reasons, however, you are recommended to set it to 'true'.
- *
- * Note that setHour(), setMinute(), setSecond() and setPartSecond()
- * allow an invalid date/time to be set regardless of the value of this
- * constant.
- *
- * @since Constant available since Release 1.5.0
- */
-define('DATE_VALIDATE_DATE_BY_DEFAULT', false);
-
-/**
- * Whether, by default, to accept times including leap seconds (i.e. '23.59.60')
- * when setting the date/time, and whether to count leap seconds in the
- * following functions:
- *
- * Date::addSeconds()
- * Date::subtractSeconds()
- * Date_Calc::addSeconds()
- * Date::round()
- * Date::roundSeconds()
- *
- * This constant is set to 'false' by default for backwards-compatibility
- * reasons, however, you are recommended to set it to 'true'.
- *
- * Note that this constant does not affect Date::addSpan() and
- * Date::subtractSpan() which will not count leap seconds in any case.
- *
- * @since Constant available since Release 1.5.0
- */
-define('DATE_COUNT_LEAP_SECONDS', false);
-
-
-// }}}
-// {{{ Output format constants (used in 'Date::getDate()')
-
-/**
- * "YYYY-MM-DD HH:MM:SS"
- */
-define('DATE_FORMAT_ISO', 1);
-
-/**
- * "YYYYMMSSTHHMMSS(Z|(+/-)HHMM)?"
- */
-define('DATE_FORMAT_ISO_BASIC', 2);
-
-/**
- * "YYYY-MM-SSTHH:MM:SS(Z|(+/-)HH:MM)?"
- */
-define('DATE_FORMAT_ISO_EXTENDED', 3);
-
-/**
- * "YYYY-MM-SSTHH:MM:SS(.S*)?(Z|(+/-)HH:MM)?"
- */
-define('DATE_FORMAT_ISO_EXTENDED_MICROTIME', 6);
-
-/**
- * "YYYYMMDDHHMMSS"
- */
-define('DATE_FORMAT_TIMESTAMP', 4);
-
-/**
- * long int, seconds since the unix epoch
- */
-define('DATE_FORMAT_UNIXTIME', 5);
-
-
-// }}}
-// {{{ Class: Date
-
-/**
- * Generic date handling class for PEAR
- *
- * Supports time zones with the Date_TimeZone class. Supports several
- * operations from Date_Calc on Date objects.
- *
- * Note to developers: the class stores the local time and date in the
- * local standard time. That is, it does not store the time as the
- * local Summer time when and if the time zone is in Summer time. It
- * is much easier to store local standard time and remember to offset
- * it when the user requests it.
- *
- * @category Date and Time
- * @package Date
- * @author Baba Buehler <baba@babaz.com>
- * @author Pierre-Alain Joye <pajoye@php.net>
- * @author Firman Wandayandi <firman@php.net>
- * @author C.A. Woodcock <c01234@netcomuk.co.uk>
- * @copyright 1997-2007 Baba Buehler, Pierre-Alain Joye, Firman Wandayandi, C.A. Woodcock
- * @license http://www.opensource.org/licenses/bsd-license.php
- * BSD License
- * @version Release: 1.5.0a1
- * @link http://pear.php.net/package/Date
- */
-class Date
-{
-
- // {{{ Properties
-
- /**
- * The year
- *
- * @var int
- * @access private
- * @since Property available since Release 1.0
- */
- var $year;
-
- /**
- * The month
- *
- * @var int
- * @access private
- * @since Property available since Release 1.0
- */
- var $month;
-
- /**
- * The day
- *
- * @var int
- * @access private
- * @since Property available since Release 1.0
- */
- var $day;
-
- /**
- * The hour
- *
- * @var int
- * @access private
- * @since Property available since Release 1.0
- */
- var $hour;
-
- /**
- * The minute
- *
- * @var int
- * @access private
- * @since Property available since Release 1.0
- */
- var $minute;
-
- /**
- * The second
- *
- * @var int
- * @access private
- * @since Property available since Release 1.0
- */
- var $second;
-
- /**
- * The parts of a second
- *
- * @var float
- * @access private
- * @since Property available since Release 1.4.3
- */
- var $partsecond;
-
- /**
- * The year in local standard time
- *
- * @var int
- * @access private
- * @since Property available since Release 1.5.0
- */
- var $on_standardyear;
-
- /**
- * The month in local standard time
- *
- * @var int
- * @access private
- * @since Property available since Release 1.5.0
- */
- var $on_standardmonth;
-
- /**
- * The day in local standard time
- *
- * @var int
- * @access private
- * @since Property available since Release 1.5.0
- */
- var $on_standardday;
-
- /**
- * The hour in local standard time
- *
- * @var int
- * @access private
- * @since Property available since Release 1.5.0
- */
- var $on_standardhour;
-
- /**
- * The minute in local standard time
- *
- * @var int
- * @access private
- * @since Property available since Release 1.5.0
- */
- var $on_standardminute;
-
- /**
- * The second in local standard time
- *
- * @var int
- * @access private
- * @since Property available since Release 1.5.0
- */
- var $on_standardsecond;
-
- /**
- * The part-second in local standard time
- *
- * @var float
- * @access private
- * @since Property available since Release 1.5.0
- */
- var $on_standardpartsecond;
-
- /**
- * Whether the object should accept and count leap seconds
- *
- * @var bool
- * @access private
- * @since Property available since Release 1.5.0
- */
- var $ob_countleapseconds;
-
- /**
- * Whether the time is valid as a local time (an invalid time
- * is one that lies in the 'skipped hour' at the point that
- * the clocks go forward)
- *
- * @var bool
- * @access private
- * @see Date::isTimeValid()
- * @since Property available since Release 1.5.0
- */
- var $ob_invalidtime = null;
-
- /**
- * Date_TimeZone object for this date
- *
- * @var object Date_TimeZone object
- * @access private
- * @since Property available since Release 1.0
- */
- var $tz;
-
- /**
- * Defines the default weekday abbreviation length
- *
- * Formerly used by Date::format(), but now redundant - the abbreviation
- * for the current locale of the machine is used.
- *
- * @var int
- * @access private
- * @since Property available since Release 1.4.4
- */
- var $getWeekdayAbbrnameLength = 3;
-
-
- // }}}
- // {{{ Constructor
-
- /**
- * Constructor
- *
- * Creates a new Date Object initialized to the current date/time in the
- * system-default timezone by default. A date optionally
- * passed in may be in the ISO 8601, TIMESTAMP or UNIXTIME format,
- * or another Date object. If no date is passed, the current date/time
- * is used.
- *
- * If a date is passed and an exception is returned by 'setDate()'
- * there is nothing that this function can do, so for this reason, it
- * is advisable to pass no parameter and to make a separate call to
- * 'setDate()'. A date/time should only be passed if known to be a
- * valid ISO 8601 string or a valid Unix timestamp.
- *
- * @param mixed $date optional ISO 8601 date/time to initialize;
- * or, a Unix time stamp
- * @param bool $pb_countleapseconds whether to count leap seconds
- * (defaults to DATE_COUNT_LEAP_SECONDS)
- *
- * @return void
- * @access public
- * @see Date::setDate()
- */
- function Date($date = null,
- $pb_countleapseconds = DATE_COUNT_LEAP_SECONDS)
- {
- $this->ob_countleapseconds = $pb_countleapseconds;
-
- if (is_a($date, 'Date')) {
- $this->copy($date);
- } else {
- if (!is_null($date)) {
- // 'setDate()' expects a time zone to be already set:
- //
- $this->_setTZToDefault();
- $this->setDate($date);
- } else {
- $this->setNow();
- }
- }
- }
-
-
- // }}}
- // {{{ copy()
-
- /**
- * Copy values from another Date object
- *
- * Makes this Date a copy of another Date object. This is a
- * PHP4-compatible implementation of '__clone()' in PHP5.
- *
- * @param object $date Date object to copy
- *
- * @return void
- * @access public
- */
- function copy($date)
- {
- $this->year = $date->year;
- $this->month = $date->month;
- $this->day = $date->day;
- $this->hour = $date->hour;
- $this->minute = $date->minute;
- $this->second = $date->second;
- $this->partsecond = $date->partsecond;
-
- $this->on_standardyear = $date->on_standardyear;
- $this->on_standardmonth = $date->on_standardmonth;
- $this->on_standardday = $date->on_standardday;
- $this->on_standardhour = $date->on_standardhour;
- $this->on_standardminute = $date->on_standardminute;
- $this->on_standardsecond = $date->on_standardsecond;
- $this->on_standardpartsecond = $date->on_standardpartsecond;
-
- $this->ob_countleapseconds = $date->ob_countleapseconds;
- $this->ob_invalidtime = $date->ob_invalidtime;
-
- $this->tz = new Date_TimeZone($date->getTZID());
-
- $this->getWeekdayAbbrnameLength = $date->getWeekdayAbbrnameLength;
- }
-
-
- // }}}
- // {{{ __clone()
-
- /**
- * Copy values from another Date object
- *
- * Makes this Date a copy of another Date object. For PHP5
- * only.
- *
- * @return void
- * @access public
- * @see Date::copy()
- */
- function __clone()
- {
- // This line of code would be preferable, but will only
- // compile in PHP5:
- //
- // $this->tz = clone $this->tz;
-
- $this->tz = new Date_TimeZone($this->getTZID());
- }
-
-
- // }}}
- // {{{ setDate()
-
- /**
- * Sets the fields of a Date object based on the input date and format
- *
- * Format parameter should be one of the specified DATE_FORMAT_* constants:
- *
- * <code>DATE_FORMAT_ISO</code>
- * - 'YYYY-MM-DD HH:MI:SS'
- * <code>DATE_FORMAT_ISO_BASIC</code>
- * - 'YYYYMMSSTHHMMSS(Z|(+/-)HHMM)?'
- * <code>DATE_FORMAT_ISO_EXTENDED</code>
- * - 'YYYY-MM-SSTHH:MM:SS(Z|(+/-)HH:MM)?'
- * <code>DATE_FORMAT_ISO_EXTENDED_MICROTIME</code>
- * - 'YYYY-MM-SSTHH:MM:SS(.S*)?(Z|(+/-)HH:MM)?'
- * <code>DATE_FORMAT_TIMESTAMP</code>
- * - 'YYYYMMDDHHMMSS'
- * <code>DATE_FORMAT_UNIXTIME'</code>
- * - long integer of the no of seconds since
- * the Unix Epoch
- * (1st January 1970 00.00.00 GMT)
- *
- * @param string $date input date
- * @param int $format optional format constant
- * (DATE_FORMAT_*) of the input date.
- * This parameter is not needed,
- * except to force the setting of the
- * date from a Unix time-stamp
- * (DATE_FORMAT_UNIXTIME).
- * @param bool $pb_repeatedhourdefault value to return if repeated
- * hour is specified (defaults
- * to false)
- *
- * @return void
- * @access public
- */
- function setDate($date,
- $format = DATE_FORMAT_ISO,
- $pb_repeatedhourdefault = false)
- {
-
- if (preg_match('/^([0-9]{4,4})-?(0[1-9]|1[0-2])-?(0[1-9]|[12][0-9]|3[01])' .
- '([T\s]?([01][0-9]|2[0-3]):?' . // [hh]
- '([0-5][0-9]):?([0-5][0-9]|60)(\.\d+)?' . // [mi]:[ss]
- '(Z|[+\-][0-9]{2,2}(:?[0-5][0-9])?)?)?$/i', // offset
- $date, $regs) &&
- $format != DATE_FORMAT_UNIXTIME
- ) {
- // DATE_FORMAT_ISO, ISO_BASIC, ISO_EXTENDED, and TIMESTAMP
- // These formats are extremely close to each other. This regex
- // is very loose and accepts almost any butchered format you could
- // throw at it. e.g. 2003-10-07 19:45:15 and 2003-10071945:15
- // are the same thing in the eyes of this regex, even though the
- // latter is not a valid ISO 8601 date.
-
- if (!Date_Calc::isValidDate($regs[3], $regs[2], $regs[1])) {
- return PEAR::raiseError("'" .
- Date_Calc::dateFormat($regs[1],
- $regs[2],
- $regs[3],
- "%Y-%m-%d") .
- "' is invalid calendar date",
- DATE_ERROR_INVALIDDATE);
- }
-
- if (isset($regs[9])) {
- if ($regs[9] == "Z") {
- $this->tz = new Date_TimeZone("UTC");
- } else {
- $this->tz = new Date_TimeZone("UTC" . $regs[9]);
- }
- }
-
- $this->setLocalTime($regs[3],
- $regs[2],
- $regs[1],
- isset($regs[5]) ? $regs[5] : 0,
- isset($regs[6]) ? $regs[6] : 0,
- isset($regs[7]) ? $regs[7] : 0,
- isset($regs[8]) ? $regs[8] : 0.0,
- $pb_repeatedhourdefault);
-
- } else if (is_numeric($date)) {
- // Unix Time; N.B. Unix Time is defined relative to GMT,
- // so it needs to be adjusted for the current time zone;
- // however we do not know if it is in Summer time until
- // we have converted it from Unix time:
- //
-
- // Get current time zone details:
- //
- $hs_id = $this->getTZID();
-
- // Input Unix time as UTC:
- //
- $this->tz = new Date_TimeZone("UTC");
- $this->setDate(gmdate("Y-m-d H:i:s", $date));
-
- // Convert back to correct time zone:
- //
- $this->convertTZByID($hs_id);
- } else {
- return PEAR::raiseError("Date not in ISO 8601 format",
- DATE_ERROR_INVALIDDATEFORMAT);
- }
- }
-
-
- // }}}
- // {{{ setNow()
-
- /**
- * Sets to local current time and time zone
- *
- * @param bool $pb_setmicrotime whether to set micro-time (defaults to the
- * value of the constant
- * DATE_CAPTURE_MICROTIME_BY_DEFAULT)
- *
- * @return void
- * @access public
- * @since Method available since Release 1.5.0
- */
- function setNow($pb_setmicrotime = DATE_CAPTURE_MICROTIME_BY_DEFAULT)
- {
- $this->_setTZToDefault();
-
- if ($pb_setmicrotime) {
- $ha_unixtime = gettimeofday();
- } else {
- $ha_unixtime = array("sec" => time());
- }
-
- $this->setDate(date("Y-m-d H:i:s", $ha_unixtime["sec"]) .
- (isset($ha_unixtime["usec"]) ?
- "." . sprintf("%06d", $ha_unixtime["usec"]) :
- ""));
- }
-
-
- // }}}
- // {{{ round()
-
- /**
- * Rounds the date according to the specified precision (defaults
- * to nearest day)
- *
- * The precision parameter must be one of the following constants:
- *
- * <code>DATE_PRECISION_YEAR</code>
- * <code>DATE_PRECISION_MONTH</code>
- * <code>DATE_PRECISION_DAY</code>
- * <code>DATE_PRECISION_HOUR</code>
- * <code>DATE_PRECISION_10MINUTES</code>
- * <code>DATE_PRECISION_MINUTE</code>
- * <code>DATE_PRECISION_10SECONDS</code>
- * <code>DATE_PRECISION_SECOND</code>
- *
- * N.B. the default is DATE_PRECISION_DAY
- *
- * The precision can also be specified as an integral offset from
- * one of these constants, where the offset reflects a precision
- * of 10 to the power of the offset greater than the constant.
- * For example:
- *
- * <code>DATE_PRECISION_YEAR - 1</code> rounds the date to the nearest 10
- * years
- * <code>DATE_PRECISION_YEAR - 3</code> rounds the date to the nearest 1000
- * years
- * <code>DATE_PRECISION_SECOND + 1</code> rounds the date to 1 decimal
- * point of a second
- * <code>DATE_PRECISION_SECOND + 3</code> rounds the date to 3 decimal
- * points of a second
- * <code>DATE_PRECISION_SECOND - 1</code> rounds the date to the nearest 10
- * seconds (thus it is equivalent to
- * DATE_PRECISION_10SECONDS)
- *
- * @param int $pn_precision a 'DATE_PRECISION_*' constant
- * @param bool $pb_correctinvalidtime whether to correct, by adding the
- * local Summer time offset, the rounded
- * time if it falls in the skipped hour
- * (defaults to
- * DATE_CORRECTINVALIDTIME_DEFAULT)
- *
- * @return void
- * @access public
- * @since Method available since Release 1.5.0
- */
- function round($pn_precision = DATE_PRECISION_DAY,
- $pb_correctinvalidtime = DATE_CORRECTINVALIDTIME_DEFAULT)
- {
- if ($pn_precision <= DATE_PRECISION_DAY) {
- list($hn_year,
- $hn_month,
- $hn_day,
- $hn_hour,
- $hn_minute,
- $hn_secondraw) =
- Date_Calc::round($pn_precision,
- $this->day,
- $this->month,
- $this->year,
- $this->hour,
- $this->minute,
- $this->partsecond == 0.0 ?
- $this->second :
- $this->second + $this->partsecond,
- $this->ob_countleapseconds);
- if (is_float($hn_secondraw)) {
- $hn_second = intval($hn_secondraw);
- $hn_partsecond = $hn_secondraw - $hn_second;
- } else {
- $hn_second = $hn_secondraw;
- $hn_partsecond = 0.0;
- }
-
- $this->setLocalTime($hn_day,
- $hn_month,
- $hn_year,
- $hn_hour,
- $hn_minute,
- $hn_second,
- $hn_partsecond,
- true, // This is unlikely anyway, but the
- // day starts with the repeated hour
- // the first time around
- $pb_correctinvalidtime);
- return;
- }
-
- // ($pn_precision >= DATE_PRECISION_HOUR)
- //
- if ($this->tz->getDSTSavings() % 3600000 == 0 ||
- ($this->tz->getDSTSavings() % 60000 == 0 &&
- $pn_precision >= DATE_PRECISION_MINUTE)
- ) {
- list($hn_year,
- $hn_month,
- $hn_day,
- $hn_hour,
- $hn_minute,
- $hn_secondraw) =
- Date_Calc::round($pn_precision,
- $this->on_standardday,
- $this->on_standardmonth,
- $this->on_standardyear,
- $this->on_standardhour,
- $this->on_standardminute,
- $this->on_standardpartsecond == 0.0 ?
- $this->on_standardsecond :
- $this->on_standardsecond +
- $this->on_standardpartsecond,
- $this->ob_countleapseconds);
- if (is_float($hn_secondraw)) {
- $hn_second = intval($hn_secondraw);
- $hn_partsecond = $hn_secondraw - $hn_second;
- } else {
- $hn_second = $hn_secondraw;
- $hn_partsecond = 0.0;
- }
-
- $this->setStandardTime($hn_day,
- $hn_month,
- $hn_year,
- $hn_hour,
- $hn_minute,
- $hn_second,
- $hn_partsecond);
- return;
- }
-
- // Very unlikely anyway (as I write, the only time zone like this
- // is Lord Howe Island in Australia (offset of half an hour)):
- //
- // (This algorithm could be better)
- //
- list($hn_year,
- $hn_month,
- $hn_day,
- $hn_hour,
- $hn_minute,
- $hn_secondraw) =
- Date_Calc::round($pn_precision,
- $this->day,
- $this->month,
- $this->year,
- $this->hour,
- $this->minute,
- $this->partsecond == 0.0 ?
- $this->second :
- $this->second + $this->partsecond,
- $this->ob_countleapseconds);
- if (is_float($hn_secondraw)) {
- $hn_second = intval($hn_secondraw);
- $hn_partsecond = $hn_secondraw - $hn_second;
- } else {
- $hn_second = $hn_secondraw;
- $hn_partsecond = 0.0;
- }
-
- $this->setLocalTime($hn_day,
- $hn_month,
- $hn_year,
- $hn_hour,
- $hn_minute,
- $hn_second,
- $hn_partsecond,
- false, // This will be right half the time
- $pb_correctinvalidtime); // This will be right
- // some of the time
- // (depends on Summer
- // time offset)
- }
-
-
- // }}}
- // {{{ roundSeconds()
-
- /**
- * Rounds seconds up or down to the nearest specified unit
- *
- * N.B. this function is equivalent to calling:
- * <code>'round(DATE_PRECISION_SECOND + $pn_precision)'</code>
- *
- * @param int $pn_precision number of digits after the decimal point
- * @param bool $pb_correctinvalidtime whether to correct, by adding the
- * local Summer time offset, the rounded
- * time if it falls in the skipped hour
- * (defaults to
- * DATE_CORRECTINVALIDTIME_DEFAULT)
- *
- * @return void
- * @access public
- * @since Method available since Release 1.5.0
- */
- function roundSeconds($pn_precision = 0,
- $pb_correctinvalidtime = DATE_CORRECTINVALIDTIME_DEFAULT)
- {
- $this->round(DATE_PRECISION_SECOND + $pn_precision,
- $pb_correctinvalidtime);
- }
-
-
- // }}}
- // {{{ trunc()
-
- /**
- * Truncates the date according to the specified precision (by
- * default, it truncates the time part of the date)
- *
- * The precision parameter must be one of the following constants:
- *
- * <code>DATE_PRECISION_YEAR</code>
- * <code>DATE_PRECISION_MONTH</code>
- * <code>DATE_PRECISION_DAY</code>
- * <code>DATE_PRECISION_HOUR</code>
- * <code>DATE_PRECISION_10MINUTES</code>
- * <code>DATE_PRECISION_MINUTE</code>
- * <code>DATE_PRECISION_10SECONDS</code>
- * <code>DATE_PRECISION_SECOND</code>
- *
- * N.B. the default is DATE_PRECISION_DAY
- *
- * The precision can also be specified as an integral offset from
- * one of these constants, where the offset reflects a precision
- * of 10 to the power of the offset greater than the constant.
- * For example:
- *
- * <code>DATE_PRECISION_YEAR</code> truncates the month, day and time
- * part of the year
- * <code>DATE_PRECISION_YEAR - 1</code> truncates the unit part of the
- * year, e.g. 1987 becomes 1980
- * <code>DATE_PRECISION_YEAR - 3</code> truncates the hundreds part of the
- * year, e.g. 1987 becomes 1000
- * <code>DATE_PRECISION_SECOND + 1</code> truncates the part of the second
- * less than 0.1 of a second, e.g.
- * 3.26301 becomes 3.2 seconds
- * <code>DATE_PRECISION_SECOND + 3</code> truncates the part of the second
- * less than 0.001 of a second, e.g.
- * 3.26301 becomes 3.263 seconds
- * <code>DATE_PRECISION_SECOND - 1</code> truncates the unit part of the
- * seconds (thus it is equivalent to
- * DATE_PRECISION_10SECONDS)
- *
- * @param int $pn_precision a 'DATE_PRECISION_*' constant
- * @param bool $pb_correctinvalidtime whether to correct, by adding the
- * local Summer time offset, the
- * truncated time if it falls in the
- * skipped hour (defaults to
- * DATE_CORRECTINVALIDTIME_DEFAULT)
- *
- * @return void
- * @access public
- * @since Method available since Release 1.5.0
- */
- function trunc($pn_precision = DATE_PRECISION_DAY,
- $pb_correctinvalidtime = DATE_CORRECTINVALIDTIME_DEFAULT)
- {
- if ($pn_precision <= DATE_PRECISION_DAY) {
- if ($pn_precision <= DATE_PRECISION_YEAR) {
- $hn_month = 0;
- $hn_day = 0;
- $hn_hour = 0;
- $hn_minute = 0;
- $hn_second = 0;
- $hn_partsecond = 0.0;
-
- $hn_invprecision = DATE_PRECISION_YEAR - $pn_precision;
- if ($hn_invprecision > 0) {
- $hn_year = intval($this->year / pow(10, $hn_invprecision)) *
- pow(10, $hn_invprecision);
- //
- // (Conversion to int necessary for PHP <= 4.0.6)
- } else {
- $hn_year = $this->year;
- }
- } else if ($pn_precision == DATE_PRECISION_MONTH) {
- $hn_year = $this->year;
- $hn_month = $this->month;
- $hn_day = 0;
- $hn_hour = 0;
- $hn_minute = 0;
- $hn_second = 0;
- $hn_partsecond = 0.0;
- } else if ($pn_precision == DATE_PRECISION_DAY) {
- $hn_year = $this->year;
- $hn_month = $this->month;
- $hn_day = $this->day;
- $hn_hour = 0;
- $hn_minute = 0;
- $hn_second = 0;
- $hn_partsecond = 0.0;
- }
-
- $this->setLocalTime($hn_day,
- $hn_month,
- $hn_year,
- $hn_hour,
- $hn_minute,
- $hn_second,
- $hn_partsecond,
- true, // This is unlikely anyway, but the
- // day starts with the repeated
- // hour the first time around
- $pb_correctinvalidtime);
- return;
- }
-
- // Precision is at least equal to DATE_PRECISION_HOUR
- //
- if ($pn_precision == DATE_PRECISION_HOUR) {
- $this->addSeconds($this->partsecond == 0.0 ?
- -$this->second :
- -$this->second - $this->partsecond);
- //
- // (leap seconds irrelevant)
-
- $this->addMinutes(-$this->minute);
- } else if ($pn_precision <= DATE_PRECISION_MINUTE) {
- if ($pn_precision == DATE_PRECISION_10MINUTES) {
- $this->addMinutes(-$this->minute % 10);
- }
-
- $this->addSeconds($this->partsecond == 0.0 ?
- -$this->second :
- -$this->second - $this->partsecond);
- //
- // (leap seconds irrelevant)
-
- } else if ($pn_precision == DATE_PRECISION_10SECONDS) {
- $this->addSeconds($this->partsecond == 0.0 ?
- -$this->second % 10 :
- (-$this->second % 10) - $this->partsecond);
- //
- // (leap seconds irrelevant)
-
- } else {
- // Assume Summer time offset cannot be composed of part-seconds:
- //
- $hn_precision = $pn_precision - DATE_PRECISION_SECOND;
- $hn_partsecond = intval($this->on_standardpartsecond *
- pow(10, $hn_precision)) /
- pow(10, $hn_precision);
- $this->setStandardTime($this->on_standardday,
- $this->on_standardmonth,
- $this->on_standardyear,
- $this->on_standardhour,
- $this->on_standardminute,
- $this->on_standardsecond,
- $hn_partsecond);
- }
- }
-
-
- // }}}
- // {{{ truncSeconds()
-
- /**
- * Truncates seconds according to the specified precision
- *
- * N.B. this function is equivalent to calling:
- * <code>'Date::trunc(DATE_PRECISION_SECOND + $pn_precision)'</code>
- *
- * @param int $pn_precision number of digits after the decimal point
- * @param bool $pb_correctinvalidtime whether to correct, by adding the
- * local Summer time offset, the
- * truncated time if it falls in the
- * skipped hour (defaults to
- * DATE_CORRECTINVALIDTIME_DEFAULT)
- *
- * @return void
- * @access public
- * @since Method available since Release 1.5.0
- */
- function truncSeconds($pn_precision = 0,
- $pb_correctinvalidtime = DATE_CORRECTINVALIDTIME_DEFAULT)
- {
- $this->trunc(DATE_PRECISION_SECOND + $pn_precision,
- $pb_correctinvalidtime);
- }
-
-
- // }}}
- // {{{ getDate()
-
- /**
- * Gets a string (or other) representation of this date
- *
- * Returns a date in the format specified by the DATE_FORMAT_* constants.
- *
- * @param int $format format constant (DATE_FORMAT_*) of the output date
- *
- * @return string the date in the requested format
- * @access public
- */
- function getDate($format = DATE_FORMAT_ISO)
- {
- switch ($format) {
- case DATE_FORMAT_ISO:
- return $this->format("%Y-%m-%d %T");
- break;
- case DATE_FORMAT_ISO_BASIC:
- $format = "%Y%m%dT%H%M%S";
- if ($this->getTZID() == 'UTC') {
- $format .= "Z";
- }
- return $this->format($format);
- break;
- case DATE_FORMAT_ISO_EXTENDED:
- $format = "%Y-%m-%dT%H:%M:%S";
- if ($this->getTZID() == 'UTC') {
- $format .= "Z";
- }
- return $this->format($format);
- break;
- case DATE_FORMAT_ISO_EXTENDED_MICROTIME:
- $format = "%Y-%m-%dT%H:%M:%s";
- if ($this->getTZID() == 'UTC') {
- $format .= "Z";
- }
- return $this->format($format);
- break;
- case DATE_FORMAT_TIMESTAMP:
- return $this->format("%Y%m%d%H%M%S");
- break;
- case DATE_FORMAT_UNIXTIME:
- // Enter a time in UTC, so use 'gmmktime()' (the alternative
- // is to offset additionally by the local time, but the object
- // is not necessarily using local time):
- //
- if ($this->ob_invalidtime)
- return $this->_getErrorInvalidTime();
-
- return gmmktime($this->on_standardhour,
- $this->on_standardminute,
- $this->on_standardsecond,
- $this->on_standardmonth,
- $this->on_standardday,
- $this->on_standardyear) -
- $this->tz->getRawOffset() / 1000; // N.B. Unix-time excludes
- // leap seconds by
- // definition
- break;
- }
- }
-
-
- // }}}
- // {{{ format()
-
- /**
- * Date pretty printing, similar to strftime()
- *
- * Formats the date in the given format, much like
- * strftime(). Most strftime() options are supported.<br><br>
- *
- * Formatting options:<br><br>
- *
- * <code>%a </code> abbreviated weekday name (Sun, Mon, Tue) <br>
- * <code>%A </code> full weekday name (Sunday, Monday, Tuesday) <br>
- * <code>%b </code> abbreviated month name (Jan, Feb, Mar) <br>
- * <code>%B </code> full month name (January, February, March) <br>
- * <code>%C </code> century number (the year divided by 100 and truncated
- * to an integer, range 00 to 99) <br>
- * <code>%d </code> day of month (range 00 to 31) <br>
- * <code>%D </code> equivalent to "%m/%d/%y" <br>
- * <code>%e </code> day of month without leading noughts (range 0 to 31) <br>
- * <code>%E </code> Julian day - no of days since Monday, 24th November,
- * 4714 B.C. (in the proleptic Gregorian calendar) <br>
- * <code>%g </code> like %G, but without the century <br>
- * <code>%G </code> the 4-digit year corresponding to the ISO week
- * number (see %V). This has the same format and value
- * as %Y, except that if the ISO week number belongs
- * to the previous or next year, that year is used
- * instead. <br>
- * <code>%h </code> hour as decimal number without leading noughts (0
- * to 23) <br>
- * <code>%H </code> hour as decimal number (00 to 23) <br>
- * <code>%i </code> hour as decimal number on 12-hour clock without
- * leading noughts (1 to 12) <br>
- * <code>%I </code> hour as decimal number on 12-hour clock (01 to 12) <br>
- * <code>%j </code> day of year (range 001 to 366) <br>
- * <code>%m </code> month as decimal number (range 01 to 12) <br>
- * <code>%M </code> minute as a decimal number (00 to 59) <br>
- * <code>%n </code> newline character ("\n") <br>
- * <code>%o </code> raw timezone offset expressed as '+/-HH:MM' <br>
- * <code>%O </code> dst-corrected timezone offset expressed as '+/-HH:MM' <br>
- * <code>%p </code> either 'am' or 'pm' depending on the time <br>
- * <code>%P </code> either 'AM' or 'PM' depending on the time <br>
- * <code>%r </code> time in am/pm notation; equivalent to "%I:%M:%S %p" <br>
- * <code>%R </code> time in 24-hour notation; equivalent to "%H:%M" <br>
- * <code>%s </code> seconds including the micro-time (the decimal
- * representation less than one second to six decimal
- * places<br>
- * <code>%S </code> seconds as a decimal number (00 to 59) <br>
- * <code>%t </code> tab character ("\t") <br>
- * <code>%T </code> current time; equivalent to "%H:%M:%S" <br>
- * <code>%u </code> day of week as decimal (1 to 7; where 1 = Monday) <br>
- * <code>%U </code> week number of the current year as a decimal
- * number, starting with the first Sunday as the first
- * day of the first week (i.e. the first full week of
- * the year, and the week that contains 7th January)
- * (00 to 53) <br>
- * <code>%V </code> the ISO 8601:1988 week number of the current year
- * as a decimal number, range 01 to 53, where week 1
- * is the first week that has at least 4 days in the
- * current year, and with Monday as the first day of
- * the week. (Use %G or %g for the year component
- * that corresponds to the week number for the
- * specified timestamp.)
- * <code>%w </code> day of week as decimal (0 to 6; where 0 = Sunday) <br>
- * <code>%W </code> week number of the current year as a decimal
- * number, starting with the first Monday as the first
- * day of the first week (i.e. the first full week of
- * the year, and the week that contains 7th January)
- * (00 to 53) <br>
- * <code>%y </code> year as decimal (range 00 to 99) <br>
- * <code>%Y </code> year as decimal including century (range 0000 to
- * 9999) <br>
- * <code>%Z </code> Abbreviated form of time zone name, e.g. 'GMT', or
- * the abbreviation for Summer time if the date falls
- * in Summer time, e.g. 'BST'. <br>
- * <code>%% </code> literal '%' <br>
- * <br>
- *
- * The following codes render a different output to that of 'strftime()':
- *
- * <code>%e</code> in 'strftime()' a single digit is preceded by a space
- * <code>%h</code> in 'strftime()' is equivalent to '%b'
- * <code>%U</code> '%U' and '%W' are different in 'strftime()' in that
- * if week 1 does not start on 1st January, '00' is
- * returned, whereas this function returns '53', that is,
- * the week is counted as the last of the previous year.
- * <code>%W</code>
- *
- * @param string $format the format string for returned date/time
- *
- * @return string date/time in given format
- * @access public
- */
- function format($format)
- {
- $output = "";
-
- $hn_isoyear = null;
- $hn_isoweek = null;
- $hn_isoday = null;
-
- for ($strpos = 0; $strpos < strlen($format); $strpos++) {
- $char = substr($format, $strpos, 1);
- if ($char == "%") {
- $nextchar = substr($format, $strpos + 1, 1);
- switch ($nextchar) {
- case "a":
- $output .= Date_Calc::getWeekdayAbbrname($this->day,
- $this->month, $this->year,
- $this->getWeekdayAbbrnameLength);
- break;
- case "A":
- $output .= Date_Calc::getWeekdayFullname($this->day,
- $this->month, $this->year);
- break;
- case "b":
- $output .= Date_Calc::getMonthAbbrname($this->month);
- break;
- case "B":
- $output .= Date_Calc::getMonthFullname($this->month);
- break;
- case "C":
- $output .= sprintf("%02d", intval($this->year / 100));
- break;
- case "d":
- $output .= sprintf("%02d", $this->day);
- break;
- case "D":
- $output .= sprintf("%02d/%02d/%02d", $this->month,
- $this->day, $this->year);
- break;
- case "e":
- $output .= $this->day;
- break;
- case "E":
- $output .= Date_Calc::dateToDays($this->day, $this->month,
- $this->year);
- break;
- case "g":
- if (is_null($hn_isoyear))
- list($hn_isoyear, $hn_isoweek, $hn_isoday) =
- Date_Calc::isoWeekDate($this->day,
- $this->month,
- $this->year);
-
- $output .= sprintf("%02d", $hn_isoyear % 100);
- break;
- case "G":
- if (is_null($hn_isoyear))
- list($hn_isoyear, $hn_isoweek, $hn_isoday) =
- Date_Calc::isoWeekDate($this->day,
- $this->month,
- $this->year);
-
- $output .= sprintf("%04d", $hn_isoyear);
- break;
- case 'h':
- if ($this->ob_invalidtime)
- return $this->_getErrorInvalidTime();
- $output .= sprintf("%d", $this->hour);
- break;
- case "H":
- if ($this->ob_invalidtime)
- return $this->_getErrorInvalidTime();
- $output .= sprintf("%02d", $this->hour);
- break;
- case "i":
- case "I":
- if ($this->ob_invalidtime)
- return $this->_getErrorInvalidTime();
- $hour = $this->hour + 1 > 12 ?
- $this->hour - 12 :
- $this->hour;
- $output .= $hour == 0 ?
- 12 :
- ($nextchar == "i" ?
- $hour :
- sprintf('%02d', $hour));
- break;
- case "j":
- $output .= sprintf("%03d",
- Date_Calc::dayOfYear($this->day,
- $this->month,
- $this->year));
- break;
- case "m":
- $output .= sprintf("%02d", $this->month);
- break;
- case "M":
- $output .= sprintf("%02d", $this->minute);
- break;
- case "n":
- $output .= "\n";
- break;
- case "O":
- if ($this->ob_invalidtime)
- return $this->_getErrorInvalidTime();
- $offms = $this->getTZOffset();
- $direction = $offms >= 0 ? "+" : "-";
- $offmins = abs($offms) / 1000 / 60;
- $hours = $offmins / 60;
- $minutes = $offmins % 60;
-
- $output .= sprintf("%s%02d:%02d", $direction, $hours, $minutes);
- break;
- case "o":
- $offms = $this->tz->getRawOffset($this);
- $direction = $offms >= 0 ? "+" : "-";
- $offmins = abs($offms) / 1000 / 60;
- $hours = $offmins / 60;
- $minutes = $offmins % 60;
-
- $output .= sprintf("%s%02d:%02d", $direction, $hours, $minutes);
- break;
- case "p":
- if ($this->ob_invalidtime)
- return $this->_getErrorInvalidTime();
- $output .= $this->hour >= 12 ? "pm" : "am";
- break;
- case "P":
- if ($this->ob_invalidtime)
- return $this->_getErrorInvalidTime();
- $output .= $this->hour >= 12 ? "PM" : "AM";
- break;
- case "r":
- if ($this->ob_invalidtime)
- return $this->_getErrorInvalidTime();
- $hour = $this->hour + 1 > 12 ?
- $this->hour - 12 :
- $this->hour;
- $output .= sprintf("%02d:%02d:%02d %s",
- $hour == 0 ? 12 : $hour,
- $this->minute,
- $this->second,
- $this->hour >= 12 ? "PM" : "AM");
- break;
- case "R":
- if ($this->ob_invalidtime)
- return $this->_getErrorInvalidTime();
- $output .= sprintf("%02d:%02d", $this->hour, $this->minute);
- break;
- case "s":
- $output .= str_replace(',',
- '.',
- sprintf("%09f",
- (float)((float) $this->second +
- $this->partsecond)));
- break;
- case "S":
- $output .= sprintf("%02d", $this->second);
- break;
- case "t":
- $output .= "\t";
- break;
- case "T":
- if ($this->ob_invalidtime)
- return $this->_getErrorInvalidTime();
- $output .= sprintf("%02d:%02d:%02d",
- $this->hour,
- $this->minute,
- $this->second);
- break;
- case "u":
- $hn_dayofweek = $this->getDayOfWeek();
- $output .= $hn_dayofweek == 0 ? 7 : $hn_dayofweek;
- break;
- case "U":
- $ha_week = Date_Calc::weekOfYear7th($this->day,
- $this->month,
- $this->year,
- 0);
- $output .= sprintf("%02d", $ha_week[1]);
- break;
- case "V":
- if (is_null($hn_isoyear))
- list($hn_isoyear, $hn_isoweek, $hn_isoday) =
- Date_Calc::isoWeekDate($this->day,
- $this->month,
- $this->year);
-
- $output .= $hn_isoweek;
- break;
- case "w":
- $output .= $this->getDayOfWeek();
- break;
- case "W":
- $ha_week = Date_Calc::weekOfYear7th($this->day,
- $this->month,
- $this->year,
- 1);
- $output .= sprintf("%02d", $ha_week[1]);
- break;
- case 'y':
- $output .= sprintf('%0' .
- ($this->year < 0 ? '3' : '2') .
- 'd',
- $this->year % 100);
- break;
- case "Y":
- $output .= sprintf('%0' .
- ($this->year < 0 ? '5' : '4') .
- 'd',
- $this->year);
- break;
- case "Z":
- if ($this->ob_invalidtime)
- return $this->_getErrorInvalidTime();
- $output .= $this->getTZShortName();
- break;
- case "%":
- $output .= "%";
- break;
- default:
- $output .= $char.$nextchar;
- }
- $strpos++;
- } else {
- $output .= $char;
- }
- }
- return $output;
-
- }
-
-
- // }}}
- // {{{ _getOrdinalSuffix()
-
- /**
- * Returns appropriate ordinal suffix (i.e. 'th', 'st', 'nd' or 'rd')
- *
- * @param int $pn_num number with which to determine suffix
- * @param bool $pb_uppercase boolean specifying if the suffix should be
- * capitalized
- *
- * @return string
- * @access private
- * @since Method available since Release 1.5.0
- */
- function _getOrdinalSuffix($pn_num, $pb_uppercase = true)
- {
- switch (($pn_numabs = abs($pn_num)) % 100) {
- case 11:
- case 12:
- case 13:
- $hs_suffix = "th";
- break;
- default:
- switch ($pn_numabs % 10) {
- case 1:
- $hs_suffix = "st";
- break;
- case 2:
- $hs_suffix = "nd";
- break;
- case 3:
- $hs_suffix = "rd";
- break;
- default:
- $hs_suffix = "th";
- }
- }
-
- return $pb_uppercase ? strtoupper($hs_suffix) : $hs_suffix;
- }
-
-
- // }}}
- // {{{ _spellNumber()
-
- /**
- * Converts a number to its word representation
- *
- * Private helper function, particularly for 'format2()'. N.B. The
- * second argument is the 'SP' code which can be specified in the
- * format string for 'format2()' and is interpreted as follows:
- * 'SP' - returns upper-case spelling, e.g. 'FOUR HUNDRED'
- * 'Sp' - returns spelling with first character of each word
- * capitalized, e.g. 'Four Hundred'
- * 'sp' - returns lower-case spelling, e.g. 'four hundred'
- *
- * @param int $pn_num number to be converted to words
- * @param bool $pb_ordinal boolean specifying if the number should
- * be ordinal
- * @param string $ps_capitalization string for specifying capitalization
- * options
- * @param string $ps_locale language name abbreviation used for
- * formatting numbers as spelled-out words
- *
- * @return string
- * @access private
- * @since Method available since Release 1.5.0
- */
- function _spellNumber($pn_num,
- $pb_ordinal = false,
- $ps_capitalization = "SP",
- $ps_locale = "en_GB")
- {
- include_once "Numbers/Words.php";
- $hs_words = Numbers_Words::toWords($pn_num, $ps_locale);
- if (Pear::isError($hs_words)) {
- return $hs_words;
- }
-
- if ($pb_ordinal && substr($ps_locale, 0, 2) == "en") {
- if (($pn_rem = ($pn_numabs = abs($pn_num)) % 100) == 12) {
- $hs_words = substr($hs_words, 0, -2) . "fth";
- } else if ($pn_rem >= 11 && $pn_rem <= 15) {
- $hs_words .= "th";
- } else {
- switch ($pn_numabs % 10) {
- case 1:
- $hs_words = substr($hs_words, 0, -3) . "first";
- break;
- case 2:
- $hs_words = substr($hs_words, 0, -3) . "second";
- break;
- case 3:
- $hs_words = substr($hs_words, 0, -3) . "ird";
- break;
- case 5:
- $hs_words = substr($hs_words, 0, -2) . "fth";
- break;
- default:
- switch (substr($hs_words, -1)) {
- case "e":
- $hs_words = substr($hs_words, 0, -1) . "th";
- break;
- case "t":
- $hs_words .= "h";
- break;
- case "y":
- $hs_words = substr($hs_words, 0, -1) . "ieth";
- break;
- default:
- $hs_words .= "th";
- }
- }
- }
- }
-
- if (($hs_char = substr($ps_capitalization, 0, 1)) ==
- strtolower($hs_char)) {
- $hb_upper = false;
- $hs_words = strtolower($hs_words);
- } else if (($hs_char = substr($ps_capitalization, 1, 1)) ==
- strtolower($hs_char)) {
- $hb_upper = false;
- $hs_words = ucwords($hs_words);
- } else {
- $hb_upper = true;
- $hs_words = strtoupper($hs_words);
- }
-
- return $hs_words;
- }
-
-
- // }}}
- // {{{ _formatNumber()
-
- /**
- * Formats a number according to the specified format string
- *
- * Private helper function, for 'format2()', which interprets the
- * codes 'SP' and 'TH' and the combination of the two as follows:
- *
- * <code>TH</code> Ordinal number
- * <code>SP</code> Spelled cardinal number
- * <code>SPTH</code> Spelled ordinal number (combination of 'SP' and 'TH'
- * in any order)
- * <code>THSP</code>
- *
- * Code 'SP' can have the following three variations (which can also be used
- * in combination with 'TH'):
- *
- * <code>SP</code> returns upper-case spelling, e.g. 'FOUR HUNDRED'
- * <code>Sp</code> returns spelling with first character of each word
- * capitalized, e.g. 'Four Hundred'
- * <code>sp</code> returns lower-case spelling, e.g. 'four hundred'
- *
- * Code 'TH' can have the following two variations (although in combination
- * with code 'SP', the case specification of 'SP' takes precedence):
- *
- * <code>TH</code> returns upper-case ordinal suffix, e.g. 400TH
- * <code>th</code> returns lower-case ordinal suffix, e.g. 400th
- *
- * N.B. The format string is passed by reference, in order to pass back
- * the part of the format string that matches the valid codes 'SP' and
- * 'TH'. If none of these are found, then it is set to an empty string;
- * If both codes are found then a string is returned with code 'SP'
- * preceding code 'TH' (i.e. 'SPTH', 'Spth' or 'spth').
- *
- * @param int $pn_num integer to be converted to words
- * @param string &$ps_format string of formatting codes (max. length 4)
- * @param int $pn_numofdigits no of digits to display if displayed as
- * numeral (i.e. not spelled out), not
- * including the sign (if negative); to
- * allow all digits specify 0
- * @param bool $pb_nopad boolean specifying whether to suppress
- * padding with leading noughts (if displayed
- * as numeral)
- * @param bool $pb_nosign boolean specifying whether to suppress the
- * display of the sign (if negative)
- * @param string $ps_locale language name abbreviation used for
- * formatting
- * @param string $ps_thousandsep optional thousand-separator (e.g. a comma)
- * numbers as spelled-out words
- * @param int $pn_padtype optional integer to specify padding (if
- * displayed as numeral) - can be
- * STR_PAD_LEFT or STR_PAD_RIGHT
- *
- * @return string
- * @access private
- * @since Method available since Release 1.5.0
- */
- function _formatNumber($pn_num,
- &$ps_format,
- $pn_numofdigits,
- $pb_nopad = false,
- $pb_nosign = false,
- $ps_locale = "en_GB",
- $ps_thousandsep = null,
- $pn_padtype = STR_PAD_LEFT)
- {
- $hs_code1 = substr($ps_format, 0, 2);
- $hs_code2 = substr($ps_format, 2, 2);
-
- $hs_sp = null;
- $hs_th = null;
- if (strtoupper($hs_code1) == "SP") {
- $hs_sp = $hs_code1;
- if (strtoupper($hs_code2) == "TH") {
- $hs_th = $hs_code2;
- }
- } else if (strtoupper($hs_code1) == "TH") {
- $hs_th = $hs_code1;
- if (strtoupper($hs_code2) == "SP") {
- $hs_sp = $hs_code2;
- }
- }
-
- $hn_absnum = abs($pn_num);
- if ($pn_numofdigits > 0 && strlen($hn_absnum) > $pn_numofdigits) {
- $hn_absnum = intval(substr($hn_absnum, -$pn_numofdigits));
- }
- $hs_num = $hn_absnum;
-
- if (!is_null($hs_sp)) {
- // Spell out number:
- //
- $ps_format = $hs_sp .
- (is_null($hs_th) ? "" : ($hs_sp == "SP" ? "TH" : "th"));
- return $this->_spellNumber(!$pb_nosign && $pn_num < 0 ?
- $hn_absnum * -1 :
- $hn_absnum,
- !is_null($hs_th),
- $hs_sp,
- $ps_locale);
- } else {
- // Display number as Arabic numeral:
- //
- if (!$pb_nopad) {
- $hs_num = str_pad($hs_num, $pn_numofdigits, "0", $pn_padtype);
- }
-
- if (!is_null($ps_thousandsep)) {
- for ($i = strlen($hs_num) - 3; $i > 0; $i -= 3) {
- $hs_num = substr($hs_num, 0, $i) .
- $ps_thousandsep .
- substr($hs_num, $i);
- }
- }
-
- if (!$pb_nosign) {
- if ($pn_num < 0)
- $hs_num = "-" . $hs_num;
- else if (!$pb_nopad)
- $hs_num = " " . $hs_num;
- }
-
- if (!is_null($hs_th)) {
- $ps_format = $hs_th;
- return $hs_num .
- $this->_getOrdinalSuffix($pn_num,
- substr($hs_th, 0, 1) == "T");
- } else {
- $ps_format = "";
- return $hs_num;
- }
- }
- }
-
-
- // }}}
- // {{{ format2()
-
- /**
- * Extended version of 'format()' with variable-length formatting codes
- *
- * Most codes reproduce the no of digits equal to the length of the code,
- * for example, 'YYY' will return the last 3 digits of the year, and so
- * the year 2007 will produce '007', and the year 89 will produce '089',
- * unless the no-padding code is used as in 'NPYYY', which will return
- * '89'.
- *
- * For negative values, the sign will be discarded, unless the 'S' code
- * is used in combination, but note that for positive values the value
- * will be padded with a leading space unless it is suppressed with
- * the no-padding modifier, for example for 2007:
- *
- * <code>YYYY</code> returns '2007'
- * <code>SYYYY</code> returns ' 2007'
- * <code>NPSYYYY</code> returns '2007'
- *
- * The no-padding modifier 'NP' can be used with numeric codes to
- * suppress leading (or trailing in the case of code 'F') noughts, and
- * with character-returning codes such as 'DAY' to suppress trailing
- * spaces, which will otherwise be padded to the maximum possible length
- * of the return-value of the code; for example, for Monday:
- *
- * <code>Day</code> returns 'Monday ' because the maximum length of
- * this code is 'Wednesday';
- * <code>NPDay</code> returns 'Monday'
- *
- * N.B. this code affects the code immediately following only, and
- * without this code the default is always to apply padding.
- *
- * Most character-returning codes, such as 'MONTH', will
- * set the capitalization according to the code, so for example:
- *
- * <code>MONTH</code> returns upper-case spelling, e.g. 'JANUARY'
- * <code>Month</code> returns spelling with first character of each word
- * capitalized, e.g. 'January'
- * <code>month</code> returns lower-case spelling, e.g. 'january'
- *
- * Where it makes sense, numeric codes can be combined with a following
- * 'SP' code which spells out the number, or with a 'TH' code, which
- * renders the code as an ordinal ('TH' only works in English), for
- * example, for 31st December:
- *
- * <code>DD</code> returns '31'
- * <code>DDTH</code> returns '31ST'
- * <code>DDth</code> returns '31st'
- * <code>DDSP</code> returns 'THIRTY-ONE'
- * <code>DDSp</code> returns 'Thirty-one'
- * <code>DDsp</code> returns 'thirty-one'
- * <code>DDSPTH</code> returns 'THIRTY-FIRST'
- * <code>DDSpth</code> returns 'Thirty-first'
- * <code>DDspth</code> returns 'thirty-first'
- *
- *
- * All formatting options:
- *
- * <code>-</code> All punctuation and white-space is reproduced unchanged
- * <code>/</code>
- * <code>,</code>
- * <code>.</code>
- * <code>;</code>
- * <code>:</code>
- * <code> </code>
- * <code>"text"</code> Quoted text is reproduced unchanged (escape using
- * '\')
- * <code>AD</code> AD indicator with or without full stops; N.B. if you
- * are using 'Astronomical' year numbering then 'A.D./B.C.'
- * indicators will be out for negative years
- * <code>A.D.</code>
- * <code>AM</code> Meridian indicator with or without full stops
- * <code>A.M.</code>
- * <code>BC</code> BC indicator with or without full stops
- * <code>B.C.</code>
- * <code>BCE</code> BCE indicator with or without full stops
- * <code>B.C.E.</code>
- * <code>CC</code> Century, i.e. the year divided by 100, discarding the
- * remainder; 'S' prefixes negative years with a minus sign
- * <code>SCC</code>
- * <code>CE</code> CE indicator with or without full stops
- * <code>C.E.</code>
- * <code>D</code> Day of week (0-6), where 0 represents Sunday
- * <code>DAY</code> Name of day, padded with blanks to display width of the
- * widest name of day in the locale of the machine
- * <code>DD</code> Day of month (1-31)
- * <code>DDD</code> Day of year (1-366)
- * <code>DY</code> Abbreviated name of day
- * <code>FFF</code> Fractional seconds; no radix character is printed. The
- * no of 'F's determines the no of digits of the
- * part-second to return; e.g. 'HH:MI:SS.FF'
- * <code>F[integer]</code> The integer after 'F' specifies the number of
- * digits of the part-second to return. This is an
- * alternative to using F[integer], and 'F3' is thus
- * equivalent to using 'FFF'.
- * <code>HH</code> Hour of day (0-23)
- * <code>HH12</code> Hour of day (1-12)
- * <code>HH24</code> Hour of day (0-23)
- * <code>ID</code> Day of week (1-7) based on the ISO standard
- * <code>IW</code> Week of year (1-52 or 1-53) based on the ISO standard
- * <code>IYYY</code> 4-digit year based on the ISO 8601 standard; 'S'
- * prefixes negative years with a minus sign
- * <code>SIYYY</code>
- * <code>IYY</code> Last 3, 2, or 1 digit(s) of ISO year
- * <code>IY</code>
- * <code>I</code>
- * <code>J</code> Julian day - the number of days since Monday, 24th
- * November, 4714 B.C. (proleptic Gregorian calendar)
- * <code>MI</code> Minute (0-59)
- * <code>MM</code> Month (01-12; January = 01)
- * <code>MON</code> Abbreviated name of month
- * <code>MONTH</code> Name of month, padded with blanks to display width of
- * the widest name of month in the date language used for
- * <code>PM</code> Meridian indicator with or without full stops
- * <code>P.M.</code>
- * <code>Q</code> Quarter of year (1, 2, 3, 4; January - March = 1)
- * <code>RM</code> Roman numeral month (I-XII; January = I); N.B. padded
- * with leading spaces.
- * <code>SS</code> Second (0-59)
- * <code>SSSSS</code> Seconds past midnight (0-86399)
- * <code>TZC</code> Abbreviated form of time zone name, e.g. 'GMT', or the
- * abbreviation for Summer time if the date falls in Summer
- * time, e.g. 'BST'.
- * N.B. this is not a unique identifier - for this purpose
- * use the time zone region (code 'TZR').
- * <code>TZH</code> Time zone hour; 'S' prefixes the hour with the correct
- * sign, (+/-), which otherwise is not displayed. Note
- * that the leading nought can be suppressed with the
- * no-padding code 'NP'). Also note that if you combine
- * with the 'SP' code, the sign will not be spelled out.
- * (I.e. 'STZHSp' will produce '+One', for example, and
- * not 'Plus One'.
- * 'TZH:TZM' will produce, for example, '+05:30'. (Also
- * see 'TZM' format code)
- * <code>STZH</code>
- * <code>TZI</code> Whether or not the date is in Summer time (daylight
- * saving time). Returns '1' if Summer time, else '0'.
- * <code>TZM</code> Time zone minute, without any +/- sign. (Also see
- * 'TZH' format element)
- * <code>TZN</code> Long form of time zone name, e.g.
- * 'Greenwich Mean Time', or the name of the Summer time if
- * the date falls in Summer time, e.g.
- * 'British Summer Time'. N.B. this is not a unique
- * identifier - for this purpose use the time zone region
- * (code 'TZR').
- * <code>TZO</code> Time zone offset in ISO 8601 form - that is, 'Z' if
- * UTC, else [+/-][hh]:[mm] (which would be equivalent
- * to 'STZH:TZM'). Note that this result is right padded
- * with spaces by default, (i.e. if 'Z').
- * <code>TZS</code> Time zone offset in seconds; 'S' prefixes negative
- * sign with minus sign '-' if negative, and no sign if
- * positive (i.e. -43200 to 50400).
- * <code>STZS</code>
- * <code>TZR</code> Time zone region, that is, the name or ID of the time
- * zone e.g. 'Europe/London'. This value is unique for
- * each time zone.
- * <code>U</code> Seconds since the Unix Epoch -
- * January 1 1970 00:00:00 GMT
- * <code>W</code> 'Absolute' week of month (1-5), counting week 1 as
- * 1st-7th of the year, regardless of the day
- * <code>W1</code> Week of year (1-54), counting week 1 as the week that
- * contains 1st January
- * <code>W4</code> Week of year (1-53), counting week 1 as the week that
- * contains 4th January (i.e. first week with at least 4
- * days)
- * <code>W7</code> Week of year (1-53), counting week 1 as the week that
- * contains 7th January (i.e. first full week)
- * <code>WW</code> 'Absolute' week of year (1-53), counting week 1 as
- * 1st-7th of the year, regardless of the day
- * <code>YEAR</code> Year, spelled out; 'S' prefixes negative years with
- * 'MINUS'; N.B. 'YEAR' differs from 'YYYYSP' in that the
- * first will render 1923, for example, as 'NINETEEN
- * TWENTY-THREE, and the second as 'ONE THOUSAND NINE
- * HUNDRED TWENTY-THREE'
- * <code>SYEAR</code>
- * <code>YYYY</code> 4-digit year; 'S' prefixes negative years with a minus
- * sign
- * <code>SYYYY</code>
- * <code>YYY</code> Last 3, 2, or 1 digit(s) of year
- * <code>YY</code>
- * <code>Y</code>
- * <code>Y,YYY</code> Year with thousands-separator in this position; five
- * possible separators
- * <code>Y.YYY</code>
- * <code>Y·YYY</code> N.B. space-dot (mid-dot, interpunct) is valid only in
- * ISO 8859-1 (so take care when using UTF-8 in
- * particular)
- * <code>Y'YYY</code>
- * <code>Y YYY</code>
- *
- * In addition the following codes can be used in combination with other
- * codes;
- * Codes that modify the next code in the format string:
- *
- * <code>NP</code> 'No Padding' - Returns a value with no trailing blanks
- * and no leading or trailing noughts; N.B. that the
- * default is to include this padding in the return string.
- * N.B. affects the code immediately following only.
- *
- * Codes that modify the previous code in the format string (can only
- * be used with integral codes such as 'MM'):
- *
- * <code>TH</code> Ordinal number
- * <code>SP</code> Spelled cardinal number
- * <code>SPTH</code> Spelled ordinal number (combination of 'SP' and 'TH'
- * in any order)
- * <code>THSP</code>
- *
- * Code 'SP' can have the following three variations (which can also be used
- * in combination with 'TH'):
- *
- * <code>SP</code> returns upper-case spelling, e.g. 'FOUR HUNDRED'
- * <code>Sp</code> returns spelling with first character of each word
- * capitalized, e.g. 'Four Hundred'
- * <code>sp</code> returns lower-case spelling, e.g. 'four hundred'
- *
- * Code 'TH' can have the following two variations (although in combination
- * with code 'SP', the case specification of 'SP' takes precedence):
- *
- * <code>TH</code> returns upper-case ordinal suffix, e.g. 400TH
- * <code>th</code> returns lower-case ordinal suffix, e.g. 400th
- *
- * @param string $ps_format format string for returned date/time
- * @param string $ps_locale language name abbreviation used for formatting
- * numbers as spelled-out words
- *
- * @return string date/time in given format
- * @access public
- * @since Method available since Release 1.5.0
- */
- function format2($ps_format, $ps_locale = "en_GB")
- {
- if (!preg_match('/^("([^"\\\\]|\\\\\\\\|\\\\")*"|(D{1,3}|S?C+|' .
- 'HH(12|24)?|I[DW]|S?IY*|J|M[IM]|Q|SS(SSS)?|S?TZ[HS]|' .
- 'TZM|U|W[W147]?|S?Y{1,3}([,.·\' ]?YYY)*)(SP(TH)?|' .
- 'TH(SP)?)?|AD|A\.D\.|AM|A\.M\.|BCE?|B\.C\.(E\.)?|CE|' .
- 'C\.E\.|DAY|DY|F(F*|[1-9][0-9]*)|MON(TH)?|NP|PM|' .
- 'P\.M\.|RM|TZ[CINOR]|S?YEAR|[^A-Z0-9"])*$/i',
- $ps_format)) {
- return PEAR::raiseError("Invalid date format '$ps_format'",
- DATE_ERROR_INVALIDFORMATSTRING);
- }
-
- $ret = "";
- $i = 0;
-
- $hb_nopadflag = false;
- $hb_showsignflag = false;
-
- $hn_weekdaypad = null;
- $hn_monthpad = null;
- $hn_isoyear = null;
- $hn_isoweek = null;
- $hn_isoday = null;
- $hn_tzoffset = null;
-
- while ($i < strlen($ps_format)) {
- $hb_lower = false;
-
- if ($hb_nopadflag) {
- $hb_nopad = true;
- } else {
- $hb_nopad = false;
- }
- if ($hb_showsignflag) {
- $hb_nosign = false;
- } else {
- $hb_nosign = true;
- }
- $hb_nopadflag = false;
- $hb_showsignflag = false;
-
- switch ($hs_char = substr($ps_format, $i, 1)) {
- case "-":
- case "/":
- case ",":
- case ".":
- case ";":
- case ":":
- case " ":
- $ret .= $hs_char;
- $i += 1;
- break;
- case "\"":
- preg_match('/(([^"\\\\]|\\\\\\\\|\\\\")*)"/',
- $ps_format,
- $ha_matches,
- PREG_OFFSET_CAPTURE,
- $i + 1);
- $ret .= str_replace(array('\\\\', '\\"'),
- array('\\', '"'),
- $ha_matches[1][0]);
- $i += strlen($ha_matches[0][0]) + 1;
- break;
- case "a":
- $hb_lower = true;
- case "A":
- if (strtoupper(substr($ps_format, $i, 4)) == "A.D.") {
- $ret .= $this->year >= 0 ?
- ($hb_lower ? "a.d." : "A.D.") :
- ($hb_lower ? "b.c." : "B.C.");
- $i += 4;
- } else if (strtoupper(substr($ps_format, $i, 2)) == "AD") {
- $ret .= $this->year >= 0 ?
- ($hb_lower ? "ad" : "AD") :
- ($hb_lower ? "bc" : "BC");
- $i += 2;
- } else {
- if ($this->ob_invalidtime)
- return $this->_getErrorInvalidTime();
- if (strtoupper(substr($ps_format, $i, 4)) == "A.M.") {
- $ret .= $this->hour < 12 ?
- ($hb_lower ? "a.m." : "A.M.") :
- ($hb_lower ? "p.m." : "P.M.");
- $i += 4;
- } else if (strtoupper(substr($ps_format, $i, 2)) == "AM") {
- $ret .= $this->hour < 12 ?
- ($hb_lower ? "am" : "AM") :
- ($hb_lower ? "pm" : "PM");
- $i += 2;
- }
- }
-
- break;
- case "b":
- $hb_lower = true;
- case "B":
- // Check for 'B.C.E.' first:
- //
- if (strtoupper(substr($ps_format, $i, 6)) == "B.C.E.") {
- if ($this->year >= 0) {
- $hs_era = $hb_lower ? "c.e." : "C.E.";
- $ret .= $hb_nopad ?
- $hs_era :
- str_pad($hs_era, 6, " ", STR_PAD_RIGHT);
- } else {
- $ret .= $hb_lower ? "b.c.e." : "B.C.E.";
- }
- $i += 6;
- } else if (strtoupper(substr($ps_format, $i, 3)) == "BCE") {
- if ($this->year >= 0) {
- $hs_era = $hb_lower ? "ce" : "CE";
- $ret .= $hb_nopad ?
- $hs_era :
- str_pad($hs_era, 3, " ", STR_PAD_RIGHT);
- } else {
- $ret .= $hb_lower ? "bce" : "BCE";
- }
- $i += 3;
- } else if (strtoupper(substr($ps_format, $i, 4)) == "B.C.") {
- $ret .= $this->year >= 0 ?
- ($hb_lower ? "a.d." : "A.D.") :
- ($hb_lower ? "b.c." : "B.C.");
- $i += 4;
- } else if (strtoupper(substr($ps_format, $i, 2)) == "BC") {
- $ret .= $this->year >= 0 ?
- ($hb_lower ? "ad" : "AD") :
- ($hb_lower ? "bc" : "BC");
- $i += 2;
- }
-
- break;
- case "c":
- $hb_lower = true;
- case "C":
- if (strtoupper(substr($ps_format, $i, 4)) == "C.E.") {
- if ($this->year >= 0) {
- $hs_era = $hb_lower ? "c.e." : "C.E.";
- $ret .= $hb_nopad ?
- $hs_era :
- str_pad($hs_era, 6, " ", STR_PAD_RIGHT);
- } else {
- $ret .= $hb_lower ? "b.c.e." : "B.C.E.";
- }
- $i += 4;
- } else if (strtoupper(substr($ps_format, $i, 2)) == "CE") {
- if ($this->year >= 0) {
- $hs_era = $hb_lower ? "ce" : "CE";
- $ret .= $hb_nopad ?
- $hs_era :
- str_pad($hs_era, 3, " ", STR_PAD_RIGHT);
- } else {
- $ret .= $hb_lower ? "bce" : "BCE";
- }
- $i += 2;
- } else {
- // Code C(CCC...):
- //
- $hn_codelen = 1;
- while (strtoupper(substr($ps_format,
- $i + $hn_codelen,
- 1)) == "C")
- ++$hn_codelen;
-
- // Check next code is not 'CE' or 'C.E.'
- //
- if ($hn_codelen > 1 &&
- (strtoupper(substr($ps_format,
- $i + $hn_codelen - 1,
- 4)) == "C.E." ||
- strtoupper(substr($ps_format,
- $i + $hn_codelen - 1,
- 2)) == "CE"
- ))
- --$hn_codelen;
-
- $hn_century = intval($this->year / 100);
- $hs_numberformat = substr($ps_format, $i + $hn_codelen, 4);
- $hs_century = $this->_formatNumber($hn_century,
- $hs_numberformat,
- $hn_codelen,
- $hb_nopad,
- $hb_nosign,
- $ps_locale);
- if (Pear::isError($hs_century))
- return $hs_century;
-
- $ret .= $hs_century;
- $i += $hn_codelen + strlen($hs_numberformat);
- }
-
- break;
- case "d":
- $hb_lower = true;
- case "D":
- if (strtoupper(substr($ps_format, $i, 3)) == "DAY") {
- $hs_day = Date_Calc::getWeekdayFullname($this->day,
- $this->month,
- $this->year);
-
- if (!$hb_nopad) {
- if (is_null($hn_weekdaypad)) {
- // Set week-day padding variable:
- //
- $hn_weekdaypad = 0;
- foreach (Date_Calc::getWeekDays() as $hs_weekday)
- $hn_weekdaypad = max($hn_weekdaypad,
- strlen($hs_weekday));
- }
- $hs_day = str_pad($hs_day,
- $hn_weekdaypad,
- " ",
- STR_PAD_RIGHT);
- }
-
- $ret .= $hb_lower ?
- strtolower($hs_day) :
- (substr($ps_format, $i + 1, 1) == "A" ?
- strtoupper($hs_day) :
- $hs_day);
- $i += 3;
- } else if (strtoupper(substr($ps_format, $i, 2)) == "DY") {
- $hs_day = Date_Calc::getWeekdayAbbrname($this->day,
- $this->month,
- $this->year);
- $ret .= $hb_lower ?
- strtolower($hs_day) :
- (substr($ps_format, $i + 1, 1) == "Y" ?
- strtoupper($hs_day) :
- $hs_day);
- $i += 2;
- } else if (strtoupper(substr($ps_format, $i, 3)) == "DDD" &&
- strtoupper(substr($ps_format, $i + 2, 3)) != "DAY" &&
- strtoupper(substr($ps_format, $i + 2, 2)) != "DY"
- ) {
- $hn_day = Date_Calc::dayOfYear($this->day,
- $this->month,
- $this->year);
- $hs_numberformat = substr($ps_format, $i + 3, 4);
- $hs_day = $this->_formatNumber($hn_day,
- $hs_numberformat,
- 3,
- $hb_nopad,
- true,
- $ps_locale);
- if (Pear::isError($hs_day))
- return $hs_day;
-
- $ret .= $hs_day;
- $i += 3 + strlen($hs_numberformat);
- } else if (strtoupper(substr($ps_format, $i, 2)) == "DD" &&
- strtoupper(substr($ps_format, $i + 1, 3)) != "DAY" &&
- strtoupper(substr($ps_format, $i + 1, 2)) != "DY"
- ) {
- $hs_numberformat = substr($ps_format, $i + 2, 4);
- $hs_day = $this->_formatNumber($this->day,
- $hs_numberformat,
- 2,
- $hb_nopad,
- true,
- $ps_locale);
- if (Pear::isError($hs_day))
- return $hs_day;
-
- $ret .= $hs_day;
- $i += 2 + strlen($hs_numberformat);
- } else {
- // Code 'D':
- //
- $hn_day = Date_Calc::dayOfWeek($this->day,
- $this->month,
- $this->year);
- $hs_numberformat = substr($ps_format, $i + 1, 4);
- $hs_day = $this->_formatNumber($hn_day,
- $hs_numberformat,
- 1,
- $hb_nopad,
- true,
- $ps_locale);
- if (Pear::isError($hs_day))
- return $hs_day;
-
- $ret .= $hs_day;
- $i += 1 + strlen($hs_numberformat);
- }
-
- break;
- case "f":
- case "F":
- if ($this->ob_invalidtime)
- return $this->_getErrorInvalidTime();
- $hn_codelen = 1;
- if (is_numeric(substr($ps_format, $i + $hn_codelen, 1))) {
- ++$hn_codelen;
- while (is_numeric(substr($ps_format, $i + $hn_codelen, 1)))
- ++$hn_codelen;
-
- $hn_partsecdigits = substr($ps_format, $i + 1, $hn_codelen - 1);
- } else {
- while (strtoupper(substr($ps_format,
- $i + $hn_codelen,
- 1)) == "F")
- ++$hn_codelen;
-
- // Check next code is not F[numeric]:
- //
- if ($hn_codelen > 1 &&
- is_numeric(substr($ps_format, $i + $hn_codelen, 1)))
- --$hn_codelen;
-
- $hn_partsecdigits = $hn_codelen;
- }
-
- $hs_partsec = (string) $this->partsecond;
- if (preg_match('/^([0-9]+)(\.([0-9]+))?E-([0-9]+)$/i',
- $hs_partsec,
- $ha_matches)) {
- $hs_partsec =
- str_repeat("0", $ha_matches[4] - strlen($ha_matches[1])) .
- $ha_matches[1] .
- $ha_matches[3];
- } else {
- $hs_partsec = substr($hs_partsec, 2);
- }
- $hs_partsec = substr($hs_partsec, 0, $hn_partsecdigits);
-
- // '_formatNumber() will not work for this because the
- // part-second is an int, and we want it to behave like a float:
- //
- if ($hb_nopad) {
- $hs_partsec = rtrim($hs_partsec, "0");
- if ($hs_partsec == "")
- $hs_partsec = "0";
- } else {
- $hs_partsec = str_pad($hs_partsec,
- $hn_partsecdigits,
- "0",
- STR_PAD_RIGHT);
- }
-
- $ret .= $hs_partsec;
- $i += $hn_codelen;
- break;
- case "h":
- case "H":
- if ($this->ob_invalidtime)
- return $this->_getErrorInvalidTime();
- if (strtoupper(substr($ps_format, $i, 4)) == "HH12") {
- $hn_hour = $this->hour % 12;
- if ($hn_hour == 0)
- $hn_hour = 12;
-
- $hn_codelen = 4;
- } else {
- // Code 'HH' or 'HH24':
- //
- $hn_hour = $this->hour;
- $hn_codelen = strtoupper(substr($ps_format,
- $i,
- 4)) == "HH24" ? 4 : 2;
- }
-
- $hs_numberformat = substr($ps_format, $i + $hn_codelen, 4);
- $hs_hour = $this->_formatNumber($hn_hour,
- $hs_numberformat,
- 2,
- $hb_nopad,
- true,
- $ps_locale);
- if (Pear::isError($hs_hour))
- return $hs_hour;
-
- $ret .= $hs_hour;
- $i += $hn_codelen + strlen($hs_numberformat);
- break;
- case "i":
- case "I":
- if (is_null($hn_isoyear))
- list($hn_isoyear, $hn_isoweek, $hn_isoday) =
- Date_Calc::isoWeekDate($this->day,
- $this->month,
- $this->year);
-
- if (strtoupper(substr($ps_format, $i, 2)) == "ID" &&
- strtoupper(substr($ps_format, $i + 1, 3)) != "DAY"
- ) {
- $hs_numberformat = substr($ps_format, $i + 2, 4);
- $hs_isoday = $this->_formatNumber($hn_isoday,
- $hs_numberformat,
- 1,
- $hb_nopad,
- true,
- $ps_locale);
- if (Pear::isError($hs_isoday))
- return $hs_isoday;
-
- $ret .= $hs_isoday;
- $i += 2 + strlen($hs_numberformat);
- } else if (strtoupper(substr($ps_format, $i, 2)) == "IW") {
- $hs_numberformat = substr($ps_format, $i + 2, 4);
- $hs_isoweek = $this->_formatNumber($hn_isoweek,
- $hs_numberformat,
- 2,
- $hb_nopad,
- true,
- $ps_locale);
- if (Pear::isError($hs_isoweek))
- return $hs_isoweek;
-
- $ret .= $hs_isoweek;
- $i += 2 + strlen($hs_numberformat);
- } else {
- // Code I(YYY...):
- //
- $hn_codelen = 1;
- while (strtoupper(substr($ps_format,
- $i + $hn_codelen,
- 1)) == "Y")
- ++$hn_codelen;
-
- $hs_numberformat = substr($ps_format, $i + $hn_codelen, 4);
- $hs_isoyear = $this->_formatNumber($hn_isoyear,
- $hs_numberformat,
- $hn_codelen,
- $hb_nopad,
- $hb_nosign,
- $ps_locale);
- if (Pear::isError($hs_isoyear))
- return $hs_isoyear;
-
- $ret .= $hs_isoyear;
- $i += $hn_codelen + strlen($hs_numberformat);
- }
-
- break;
- case "j":
- case "J":
- $hn_jd = Date_Calc::dateToDays($this->day,
- $this->month,
- $this->year);
- $hs_numberformat = substr($ps_format, $i + 1, 4);
-
- // Allow sign if negative; allow all digits (specify nought);
- // suppress padding:
- //
- $hs_jd = $this->_formatNumber($hn_jd,
- $hs_numberformat,
- 0,
- true,
- false,
- $ps_locale);
- if (Pear::isError($hs_jd))
- return $hs_jd;
-
- $ret .= $hs_jd;
- $i += 1 + strlen($hs_numberformat);
- break;
- case "m":
- $hb_lower = true;
- case "M":
- if (strtoupper(substr($ps_format, $i, 2)) == "MI") {
- if ($this->ob_invalidtime)
- return $this->_getErrorInvalidTime();
- $hs_numberformat = substr($ps_format, $i + 2, 4);
- $hs_minute = $this->_formatNumber($this->minute,
- $hs_numberformat,
- 2,
- $hb_nopad,
- true,
- $ps_locale);
- if (Pear::isError($hs_minute))
- return $hs_minute;
-
- $ret .= $hs_minute;
- $i += 2 + strlen($hs_numberformat);
- } else if (strtoupper(substr($ps_format, $i, 2)) == "MM") {
- $hs_numberformat = substr($ps_format, $i + 2, 4);
- $hs_month = $this->_formatNumber($this->month,
- $hs_numberformat,
- 2,
- $hb_nopad,
- true,
- $ps_locale);
- if (Pear::isError($hs_month))
- return $hs_month;
-
- $ret .= $hs_month;
- $i += 2 + strlen($hs_numberformat);
- } else if (strtoupper(substr($ps_format, $i, 5)) == "MONTH") {
- $hs_month = Date_Calc::getMonthFullname($this->month);
-
- if (!$hb_nopad) {
- if (is_null($hn_monthpad)) {
- // Set month padding variable:
- //
- $hn_monthpad = 0;
- foreach (Date_Calc::getMonthNames() as $hs_monthofyear)
- $hn_monthpad = max($hn_monthpad,
- strlen($hs_monthofyear));
- }
- $hs_month = str_pad($hs_month,
- $hn_monthpad,
- " ",
- STR_PAD_RIGHT);
- }
-
- $ret .= $hb_lower ?
- strtolower($hs_month) :
- (substr($ps_format, $i + 1, 1) == "O" ?
- strtoupper($hs_month) :
- $hs_month);
- $i += 5;
- } else if (strtoupper(substr($ps_format, $i, 3)) == "MON") {
- $hs_month = Date_Calc::getMonthAbbrname($this->month);
- $ret .= $hb_lower ?
- strtolower($hs_month) :
- (substr($ps_format, $i + 1, 1) == "O" ?
- strtoupper($hs_month) :
- $hs_month);
- $i += 3;
- }
-
- break;
- case "n":
- case "N":
- // No-Padding rule 'NP' applies to the next code (either trailing
- // spaces or leading/trailing noughts):
- //
- $hb_nopadflag = true;
- $i += 2;
- break;
- case "p":
- $hb_lower = true;
- case "P":
- if ($this->ob_invalidtime)
- return $this->_getErrorInvalidTime();
- if (strtoupper(substr($ps_format, $i, 4)) == "P.M.") {
- $ret .= $this->hour < 12 ?
- ($hb_lower ? "a.m." : "A.M.") :
- ($hb_lower ? "p.m." : "P.M.");
- $i += 4;
- } else if (strtoupper(substr($ps_format, $i, 2)) == "PM") {
- $ret .= $this->hour < 12 ?
- ($hb_lower ? "am" : "AM") :
- ($hb_lower ? "pm" : "PM");
- $i += 2;
- }
-
- break;
- case "q":
- case "Q":
- // N.B. Current implementation ignores the day and year, but
- // it is possible that a different implementation might be
- // desired, so pass these parameters anyway:
- //
- $hn_quarter = Date_Calc::quarterOfYear($this->day,
- $this->month,
- $this->year);
- $hs_numberformat = substr($ps_format, $i + 1, 4);
- $hs_quarter = $this->_formatNumber($hn_quarter,
- $hs_numberformat,
- 1,
- $hb_nopad,
- true,
- $ps_locale);
- if (Pear::isError($hs_quarter))
- return $hs_quarter;
-
- $ret .= $hs_quarter;
- $i += 1 + strlen($hs_numberformat);
- break;
- case "r":
- $hb_lower = true;
- case "R":
- // Code 'RM':
- //
- switch ($this->month) {
- case 1:
- $hs_monthroman = "i";
- break;
- case 2:
- $hs_monthroman = "ii";
- break;
- case 3:
- $hs_monthroman = "iii";
- break;
- case 4:
- $hs_monthroman = "iv";
- break;
- case 5:
- $hs_monthroman = "v";
- break;
- case 6:
- $hs_monthroman = "vi";
- break;
- case 7:
- $hs_monthroman = "vii";
- break;
- case 8:
- $hs_monthroman = "viii";
- break;
- case 9:
- $hs_monthroman = "ix";
- break;
- case 10:
- $hs_monthroman = "x";
- break;
- case 11:
- $hs_monthroman = "xi";
- break;
- case 12:
- $hs_monthroman = "xii";
- break;
- }
-
- $hs_monthroman = $hb_lower ?
- $hs_monthroman :
- strtoupper($hs_monthroman);
- $ret .= $hb_nopad ?
- $hs_monthroman :
- str_pad($hs_monthroman, 4, " ", STR_PAD_LEFT);
- $i += 2;
- break;
- case "s":
- case "S":
- // Check for 'SSSSS' before 'SS':
- //
- if (strtoupper(substr($ps_format, $i, 5)) == "SSSSS") {
- if ($this->ob_invalidtime)
- return $this->_getErrorInvalidTime();
- $hs_numberformat = substr($ps_format, $i + 5, 4);
- $hn_second = Date_Calc::secondsPastMidnight($this->hour,
- $this->minute,
- $this->second);
- $hs_second = $this->_formatNumber($hn_second,
- $hs_numberformat,
- 5,
- $hb_nopad,
- true,
- $ps_locale);
- if (Pear::isError($hs_second))
- return $hs_second;
-
- $ret .= $hs_second;
- $i += 5 + strlen($hs_numberformat);
- } else if (strtoupper(substr($ps_format, $i, 2)) == "SS") {
- if ($this->ob_invalidtime)
- return $this->_getErrorInvalidTime();
- $hs_numberformat = substr($ps_format, $i + 2, 4);
- $hs_second = $this->_formatNumber($this->second,
- $hs_numberformat,
- 2,
- $hb_nopad,
- true,
- $ps_locale);
- if (Pear::isError($hs_second))
- return $hs_second;
-
- $ret .= $hs_second;
- $i += 2 + strlen($hs_numberformat);
- } else {
- // One of the following codes:
- // 'SC(CCC...)'
- // 'SY(YYY...)'
- // 'SIY(YYY...)'
- // 'STZH'
- // 'STZS'
- // 'SYEAR'
- //
- $hb_showsignflag = true;
- if ($hb_nopad)
- $hb_nopadflag = true;
- ++$i;
- }
-
- break;
- case "t":
- case "T":
- // Code TZ[...]:
- //
-
- if (strtoupper(substr($ps_format, $i, 3)) == "TZR") {
- // This time-zone-related code can be called when the time is
- // invalid, but the others should return an error:
- //
- $ret .= $this->getTZID();
- $i += 3;
- } else {
- if ($this->ob_invalidtime)
- return $this->_getErrorInvalidTime();
-
- if (strtoupper(substr($ps_format, $i, 3)) == "TZC") {
- $ret .= $this->getTZShortName();
- $i += 3;
- } else if (strtoupper(substr($ps_format, $i, 3)) == "TZH") {
- if (is_null($hn_tzoffset))
- $hn_tzoffset = $this->getTZOffset();
-
- $hs_numberformat = substr($ps_format, $i + 3, 4);
- $hn_tzh = intval($hn_tzoffset / 3600000);
-
- // Suppress sign here (it is added later):
- //
- $hs_tzh = $this->_formatNumber($hn_tzh,
- $hs_numberformat,
- 2,
- $hb_nopad,
- true,
- $ps_locale);
- if (Pear::isError($hs_tzh))
- return $hs_tzh;
-
- // Display sign, even if positive:
- //
- $ret .= ($hb_nosign ? "" : ($hn_tzh >= 0 ? '+' : '-')) .
- $hs_tzh;
- $i += 3 + strlen($hs_numberformat);
- } else if (strtoupper(substr($ps_format, $i, 3)) == "TZI") {
- $ret .= ($this->inDaylightTime() ? '1' : '0');
- $i += 3;
- } else if (strtoupper(substr($ps_format, $i, 3)) == "TZM") {
- if (is_null($hn_tzoffset))
- $hn_tzoffset = $this->getTZOffset();
-
- $hs_numberformat = substr($ps_format, $i + 3, 4);
- $hn_tzm = intval(($hn_tzoffset % 3600000) / 60000);
-
- // Suppress sign:
- //
- $hs_tzm = $this->_formatNumber($hn_tzm,
- $hs_numberformat,
- 2,
- $hb_nopad,
- true,
- $ps_locale);
- if (Pear::isError($hs_tzm))
- return $hs_tzm;
-
- $ret .= $hs_tzm;
- $i += 3 + strlen($hs_numberformat);
- } else if (strtoupper(substr($ps_format, $i, 3)) == "TZN") {
- $ret .= $this->getTZLongName();
- $i += 3;
- } else if (strtoupper(substr($ps_format, $i, 3)) == "TZO") {
- if (is_null($hn_tzoffset))
- $hn_tzoffset = $this->getTZOffset();
-
- $hn_tzh = intval(abs($hn_tzoffset) / 3600000);
- $hn_tzm = intval((abs($hn_tzoffset) % 3600000) / 60000);
-
- if ($hn_tzoffset == 0) {
- $ret .= $hb_nopad ? "Z" : "Z ";
- } else {
- // Display sign, even if positive:
- //
- $ret .= ($hn_tzoffset >= 0 ? '+' : '-') .
- sprintf("%02d", $hn_tzh) .
- ":" .
- sprintf("%02d", $hn_tzm);
- }
- $i += 3;
- } else if (strtoupper(substr($ps_format, $i, 3)) == "TZS") {
- if (is_null($hn_tzoffset))
- $hn_tzoffset = $this->getTZOffset();
-
- $hs_numberformat = substr($ps_format, $i + 3, 4);
- $hn_tzs = intval($hn_tzoffset / 1000);
- $hs_tzs = $this->_formatNumber($hn_tzs,
- $hs_numberformat,
- 5,
- $hb_nopad,
- $hb_nosign,
- $ps_locale);
- if (Pear::isError($hs_tzs))
- return $hs_tzs;
-
- $ret .= $hs_tzs;
- $i += 3 + strlen($hs_numberformat);
- }
- }
-
- break;
- case "u":
- case "U":
- if ($this->ob_invalidtime)
- return $this->_getErrorInvalidTime();
- $hn_unixtime = $this->getTime();
- $hs_numberformat = substr($ps_format, $i + 1, 4);
-
- // Allow sign if negative; allow all digits (specify nought);
- // suppress padding:
- //
- $hs_unixtime = $this->_formatNumber($hn_unixtime,
- $hs_numberformat,
- 0,
- true,
- false,
- $ps_locale);
- if (Pear::isError($hs_unixtime))
- return $hs_unixtime;
-
- $ret .= $hs_unixtime;
- $i += 1 + strlen($hs_numberformat);
- break;
- case "w":
- case "W":
- // Check for 'WW' before 'W':
- //
- if (strtoupper(substr($ps_format, $i, 2)) == "WW") {
- $hn_week = Date_Calc::weekOfYearAbsolute($this->day,
- $this->month,
- $this->year);
- $hs_numberformat = substr($ps_format, $i + 2, 4);
- $hs_week = $this->_formatNumber($hn_week,
- $hs_numberformat,
- 2,
- $hb_nopad,
- true,
- $ps_locale);
- if (Pear::isError($hs_week))
- return $hs_week;
-
- $ret .= $hs_week;
- $i += 2 + strlen($hs_numberformat);
- } else if (strtoupper(substr($ps_format, $i, 2)) == "W1") {
- $hn_week = Date_Calc::weekOfYear1st($this->day,
- $this->month,
- $this->year);
- $hs_numberformat = substr($ps_format, $i + 2, 4);
- $hs_week = $this->_formatNumber($hn_week,
- $hs_numberformat,
- 2,
- $hb_nopad,
- true,
- $ps_locale);
- if (Pear::isError($hs_week))
- return $hs_week;
-
- $ret .= $hs_week;
- $i += 2 + strlen($hs_numberformat);
- } else if (strtoupper(substr($ps_format, $i, 2)) == "W4") {
- $ha_week = Date_Calc::weekOfYear4th($this->day,
- $this->month,
- $this->year);
- $hn_week = $ha_week[1];
- $hs_numberformat = substr($ps_format, $i + 2, 4);
- $hs_week = $this->_formatNumber($hn_week,
- $hs_numberformat,
- 2,
- $hb_nopad,
- true,
- $ps_locale);
- if (Pear::isError($hs_week))
- return $hs_week;
-
- $ret .= $hs_week;
- $i += 2 + strlen($hs_numberformat);
- } else if (strtoupper(substr($ps_format, $i, 2)) == "W7") {
- $ha_week = Date_Calc::weekOfYear7th($this->day,
- $this->month,
- $this->year);
- $hn_week = $ha_week[1];
- $hs_numberformat = substr($ps_format, $i + 2, 4);
- $hs_week = $this->_formatNumber($hn_week,
- $hs_numberformat,
- 2,
- $hb_nopad,
- true,
- $ps_locale);
- if (Pear::isError($hs_week))
- return $hs_week;
-
- $ret .= $hs_week;
- $i += 2 + strlen($hs_numberformat);
- } else {
- // Code 'W':
- //
- $hn_week = Date_Calc::weekOfMonthAbsolute($this->day,
- $this->month,
- $this->year);
- $hs_numberformat = substr($ps_format, $i + 1, 4);
- $hs_week = $this->_formatNumber($hn_week,
- $hs_numberformat,
- 1,
- $hb_nopad,
- true,
- $ps_locale);
- if (Pear::isError($hs_week))
- return $hs_week;
-
- $ret .= $hs_week;
- $i += 1 + strlen($hs_numberformat);
- }
-
- break;
- case "y":
- case "Y":
- // Check for 'YEAR' first:
- //
- if (strtoupper(substr($ps_format, $i, 4)) == "YEAR") {
- switch (substr($ps_format, $i, 2)) {
- case "YE":
- $hs_spformat = "SP";
- break;
- case "Ye":
- $hs_spformat = "Sp";
- break;
- default:
- $hs_spformat = "sp";
- }
-
- if (($hn_yearabs = abs($this->year)) < 100 ||
- $hn_yearabs % 100 < 10) {
-
- $hs_numberformat = $hs_spformat;
-
- // Allow all digits (specify nought); padding irrelevant:
- //
- $hs_year = $this->_formatNumber($this->year,
- $hs_numberformat,
- 0,
- true,
- $hb_nosign,
- $ps_locale);
- if (Pear::isError($hs_year))
- return $hs_year;
-
- $ret .= $hs_year;
- } else {
- // Year is spelled 'Nineteen Twelve' rather than
- // 'One thousand Nine Hundred Twelve':
- //
- $hn_century = intval($this->year / 100);
- $hs_numberformat = $hs_spformat;
-
- // Allow all digits (specify nought); padding irrelevant:
- //
- $hs_century = $this->_formatNumber($hn_century,
- $hs_numberformat,
- 0,
- true,
- $hb_nosign,
- $ps_locale);
- if (Pear::isError($hs_century))
- return $hs_century;
-
- $ret .= $hs_century . " ";
-
- $hs_numberformat = $hs_spformat;
-
- // Discard sign; padding irrelevant:
- //
- $hs_year = $this->_formatNumber($this->year,
- $hs_numberformat,
- 2,
- false,
- true,
- $ps_locale);
- if (Pear::isError($hs_year))
- return $hs_year;
-
- $ret .= $hs_year;
- }
-
- $i += 4;
- } else {
- // Code Y(YYY...):
- //
- $hn_codelen = 1;
- while (strtoupper(substr($ps_format,
- $i + $hn_codelen,
- 1)) == "Y")
- ++$hn_codelen;
-
- $hs_thousandsep = null;
- $hn_thousandseps = 0;
- if ($hn_codelen <= 3) {
- while (preg_match('/([,.·\' ])YYY/i',
- substr($ps_format,
- $i + $hn_codelen,
- 4),
- $ha_matches)) {
- $hn_codelen += 4;
- $hs_thousandsep = $ha_matches[1];
- ++$hn_thousandseps;
- }
- }
-
- // Check next code is not 'YEAR'
- //
- if ($hn_codelen > 1 &&
- strtoupper(substr($ps_format,
- $i + $hn_codelen - 1,
- 4)) == "YEAR")
- --$hn_codelen;
-
- $hs_numberformat = substr($ps_format, $i + $hn_codelen, 4);
- $hs_year = $this->_formatNumber($this->year,
- $hs_numberformat,
- $hn_codelen -
- $hn_thousandseps,
- $hb_nopad,
- $hb_nosign,
- $ps_locale,
- $hs_thousandsep);
- if (Pear::isError($hs_year))
- return $hs_year;
-
- $ret .= $hs_year;
- $i += $hn_codelen + strlen($hs_numberformat);
- }
-
- break;
- default:
- $ret .= $hs_char;
- ++$i;
- break;
- }
- }
- return $ret;
- }
-
-
- // }}}
- // {{{ format3()
-
- /**
- * Formats the date in the same way as 'format()', but using the
- * formatting codes used by the PHP function 'date()'
- *
- * All 'date()' formatting options are supported except 'B'. This
- * function also responds to the DATE_* constants, such as DATE_COOKIE,
- * which are specified at:
- *
- * http://www.php.net/manual/en/ref.datetime.php#datetime.constants
- *
- *
- * Formatting options:
- *
- * (Day)
- *
- * <code>d</code> Day of the month, 2 digits with leading zeros (01 to 31)
- * <code>D</code> A textual representation of a day, three letters ('Mon'
- * to 'Sun')
- * <code>j</code> Day of the month without leading zeros (1 to 31)
- * <code>l</code> [lowercase 'L'] A full textual representation of the day
- * of the week ('Sunday' to 'Saturday')
- * <code>N</code> ISO-8601 numeric representation of the day of the week
- * (1 (for Monday) to 7 (for Sunday))
- * <code>S</code> English ordinal suffix for the day of the month, 2
- * characters ('st', 'nd', 'rd' or 'th')
- * <code>w</code> Numeric representation of the day of the week (0 (for
- * Sunday) to 6 (for Saturday))
- * <code>z</code> The day of the year, starting from 0 (0 to 365)
- *
- * (Week)
- *
- * <code>W</code> ISO-8601 week number of year, weeks starting on Monday
- * (00 to 53)
- *
- * (Month)
- *
- * <code>F</code> A full textual representation of a month ('January' to
- * 'December')
- * <code>m</code> Numeric representation of a month, with leading zeros
- * (01 to 12)
- * <code>M</code> A short textual representation of a month, three letters
- * ('Jan' to 'Dec')
- * <code>n</code> Numeric representation of a month, without leading zeros
- * (1 to 12)
- * <code>t</code> Number of days in the given month (28 to 31)
- *
- * (Year)
- *
- * <code>L</code> Whether it is a leap year (1 if it is a leap year, 0
- * otherwise)
- * <code>o</code> ISO-8601 year number. This has the same value as Y,
- * except that if the ISO week number (W) belongs to the
- * previous or next year, that year is used instead.
- * <code>Y</code> A full numeric representation of a year, 4 digits (0000
- * to 9999)
- * <code>y</code> A two digit representation of a year (00 to 99)
- *
- * (Time)
- *
- * <code>a</code> Lowercase Ante meridiem and Post meridiem ('am' or
- * 'pm')
- * <code>A</code> Uppercase Ante meridiem and Post meridiem ('AM' or
- * 'PM')
- * <code>g</code> 12-hour format of an hour without leading zeros (1 to 12)
- * <code>G</code> 24-hour format of an hour without leading zeros (0 to 23)
- * <code>h</code> 12-hour format of an hour with leading zeros (01 to 12)
- * <code>H</code> 24-hour format of an hour with leading zeros (00 to 23)
- * <code>i</code> Minutes with leading zeros (00 to 59)
- * <code>s</code> Seconds, with leading zeros (00 to 59)
- * <code>u</code> Milliseconds, e.g. '54321'
- *
- * (Time Zone)
- *
- * <code>e</code> Timezone identifier, e.g. Europe/London
- * <code>I</code> Whether or not the date is in Summer time (1 if Summer
- * time, 0 otherwise)
- * <code>O</code> Difference to Greenwich time (GMT) in hours, e.g. '+0200'
- * <code>P</code> Difference to Greenwich time (GMT) with colon between
- * hours and minutes, e.g. '+02:00'
- * <code>T</code> Timezone abbreviation, e.g. 'GMT', 'EST'
- * <code>Z</code> Timezone offset in seconds. The offset for timezones west
- * of UTC is always negative, and for those east of UTC is
- * always positive. (-43200 to 50400)
- *
- * (Full Date/Time)
- *
- * <code>c</code> ISO 8601 date, e.g. '2004-02-12T15:19:21+00:00'
- * <code>r</code> RFC 2822 formatted date, e.g.
- * 'Thu, 21 Dec 2000 16:01:07 +0200'
- * <code>U</code> Seconds since the Unix Epoch
- * (January 1 1970 00:00:00 GMT)
- *
- * @param string $ps_format the format string for returned date/time
- *
- * @return string date/time in given format
- * @access public
- * @since Method available since Release 1.5.0
- */
- function format3($ps_format)
- {
- $hs_format2str = "";
-
- for ($i = 0; $i < strlen($ps_format); ++$i) {
- switch ($hs_char = substr($ps_format, $i, 1)) {
- case 'd':
- $hs_format2str .= 'DD';
- break;
- case 'D':
- $hs_format2str .= 'NPDy';
- break;
- case 'j':
- $hs_format2str .= 'NPDD';
- break;
- case 'l':
- $hs_format2str .= 'NPDay';
- break;
- case 'N':
- $hs_format2str .= 'ID';
- break;
- case 'S':
- $hs_format2str .= 'th';
- break;
- case 'w':
- $hs_format2str .= 'D';
- break;
- case 'z':
- $hs_format2str .= '"' . ($this->getDayOfYear() - 1) . '"';
- break;
- case 'W':
- $hs_format2str .= 'IW';
- break;
- case 'F':
- $hs_format2str .= 'NPMonth';
- break;
- case 'm':
- $hs_format2str .= 'MM';
- break;
- case 'M':
- $hs_format2str .= 'NPMon';
- break;
- case 'n':
- $hs_format2str .= 'NPMM';
- break;
- case 't':
- $hs_format2str .= '"' . $this->getDaysInMonth() . '"';
- break;
- case 'L':
- $hs_format2str .= '"' . ($this->isLeapYear() ? 1 : 0) . '"';
- break;
- case 'o':
- $hs_format2str .= 'IYYY';
- break;
- case 'Y':
- $hs_format2str .= 'YYYY';
- break;
- case 'y':
- $hs_format2str .= 'YY';
- break;
- case 'a':
- $hs_format2str .= 'am';
- break;
- case 'A':
- $hs_format2str .= 'AM';
- break;
- case 'g':
- $hs_format2str .= 'NPHH12';
- break;
- case 'G':
- $hs_format2str .= 'NPHH24';
- break;
- case 'h':
- $hs_format2str .= 'HH12';
- break;
- case 'H':
- $hs_format2str .= 'HH24';
- break;
- case 'i':
- $hs_format2str .= 'MI';
- break;
- case 's':
- $hs_format2str .= 'SS';
- break;
- case 'u':
- $hs_format2str .= 'SSFFF';
- break;
- case 'e':
- $hs_format2str .= 'TZR';
- break;
- case 'I':
- $hs_format2str .= 'TZI';
- break;
- case 'O':
- $hs_format2str .= 'STZHTZM';
- break;
- case 'P':
- $hs_format2str .= 'STZH:TZM';
- break;
- case 'T':
- $hs_format2str .= 'TZC';
- break;
- case 'Z':
- $hs_format2str .= 'TZS';
- break;
- case 'c':
- $hs_format2str .= 'YYYY-MM-DD"T"HH24:MI:SSSTZH:TZM';
- break;
- case 'r':
- $hs_format2str .= 'Dy, DD Mon YYYY HH24:MI:SS STZHTZM';
- break;
- case 'U':
- $hs_format2str .= 'U';
- break;
- case '\\':
- $hs_char = substr($ps_format, ++$i, 1);
- $hs_format2str .= '"' . ($hs_char == '\\' ? '\\\\' : $hs_char) . '"';
- break;
- case '"':
- $hs_format2str .= '"\\""';
- break;
- default:
- $hs_format2str .= '"' . $hs_char . '"';
- }
- }
-
- $ret = $this->format2($hs_format2str);
- if (PEAR::isError($ret) &&
- $ret->getCode() == DATE_ERROR_INVALIDFORMATSTRING) {
- return PEAR::raiseError("Invalid date format '$ps_format'",
- DATE_ERROR_INVALIDFORMATSTRING);
- }
-
- return $ret;
- }
-
-
- // }}}
- // {{{ getTime()
-
- /**
- * Returns the date/time in Unix time() format
- *
- * Returns a representation of this date in Unix time() format. This may
- * only be valid for dates from 1970 to ~2038.
- *
- * @return int number of seconds since the unix epoch
- * @access public
- */
- function getTime()
- {
- return $this->getDate(DATE_FORMAT_UNIXTIME);
- }
-
-
- // }}}
- // {{{ getTZID()
-
- /**
- * Returns the unique ID of the time zone, e.g. 'America/Chicago'
- *
- * @return string the time zone ID
- * @access public
- * @since Method available since Release 1.5.0
- */
- function getTZID()
- {
- return $this->tz->getID();
- }
-
-
- // }}}
- // {{{ _setTZToDefault()
-
- /**
- * sets time zone to the default time zone
- *
- * If PHP version >= 5.1.0, uses the php.ini configuration directive
- * 'date.timezone' if set and valid, else the value returned by
- * 'date("e")' if valid, else the default specified if the global
- * constant '$GLOBALS["_DATE_TIMEZONE_DEFAULT"]', which if itself
- * left unset, defaults to "UTC".
- *
- * N.B. this is a private method; to set the time zone to the
- * default publicly you should call 'setTZByID()', that is, with no
- * parameter (or a parameter of null).
- *
- * @return void
- * @access private
- * @since Method available since Release 1.5.0
- */
- function _setTZToDefault()
- {
- if (function_exists('version_compare') &&
- version_compare(phpversion(), "5.1.0", ">=") &&
- (Date_TimeZone::isValidID($hs_id = ini_get("date.timezone")) ||
- Date_TimeZone::isValidID($hs_id = date("e"))
- )
- ) {
- $this->tz = new Date_TimeZone($hs_id);
- } else {
- $this->tz = Date_TimeZone::getDefault();
- }
- }
-
-
- // }}}
- // {{{ setTZ()
-
- /**
- * Sets the time zone of this Date
- *
- * Sets the time zone of this date with the given
- * Date_TimeZone object. Does not alter the date/time,
- * only assigns a new time zone. For conversion, use
- * convertTZ().
- *
- * @param object $tz the Date_TimeZone object to use. If called with a
- * parameter that is not a Date_TimeZone object, will
- * fall through to setTZByID().
- *
- * @return void
- * @access public
- * @see Date::setTZByID()
- */
- function setTZ($tz)
- {
- if (is_a($tz, 'Date_Timezone')) {
- $this->setTZByID($tz->getID());
- } else {
- $res = $this->setTZByID($tz);
- if (PEAR::isError($res))
- return $res;
- }
- }
-
-
- // }}}
- // {{{ setTZByID()
-
- /**
- * Sets the time zone of this date with the given time zone ID
- *
- * The time zone IDs are drawn from the 'tz data-base' (see
- * http://en.wikipedia.org/wiki/Zoneinfo), which is the de facto
- * internet and IT standard. (There is no official standard, and
- * the tz data-base is not intended to be a regulating body
- * anyway.) Lists of valid IDs are maintained at:
- *
- * http://en.wikipedia.org/wiki/List_of_zoneinfo_timezones
- * http://www.php.net/manual/en/timezones.php
- *
- * If no time-zone is specified and PHP version >= 5.1.0, the time
- * zone is set automatically to the php.ini configuration directive
- * 'date.timezone' if set and valid, else the value returned by
- * 'date("e")' if valid, else the default specified if the global
- * constant '$GLOBALS["_DATE_TIMEZONE_DEFAULT"]', which if itself
- * left unset, defaults to "UTC".
- *
- * N.B. this function preserves the local date and time, that is,
- * whether in local Summer time or local standard time. For example,
- * if the time is set to 11.00 Summer time, and the time zone is then
- * set to another time zone, using this function, in which the date
- * falls in standard time, then the time will remain set to 11.00 UTC,
- * and not 10.00. You can convert a date to another time zone by
- * calling 'convertTZ()'.
- *
- * The ID can also be specified as a UTC offset in one of the following
- * forms, i.e. an offset with no geographical or political base:
- *
- * UTC[+/-][h] - e.g. UTC-1 (the preferred form)
- * UTC[+/-][hh] - e.g. UTC+03
- * UTC[+/-][hh][mm] - e.g. UTC-0530
- * UTC[+/-][hh]:[mm] - e.g. UTC+03:00
- *
- * N.B. 'UTC' seems to be technically preferred over 'GMT'. GMT-based
- * IDs still exist in the tz data-base, but beware of POSIX-style
- * offsets which are the opposite way round to what people normally
- * expect.
- *
- * @param string $ps_id a valid time zone id, e.g. 'Europe/London'
- *
- * @return void
- * @access public
- * @see Date::convertTZByID(), Date_TimeZone::isValidID(),
- * Date_TimeZone::Date_TimeZone()
- */
- function setTZByID($ps_id = null)
- {
- // Whether the date is in Summer time forms the default for
- // the new time zone (if needed, which is very unlikely anyway).
- // This is mainly to prevent unexpected (defaulting) behaviour
- // if the user is in the repeated hour, and switches to a time
- // zone that is also in the repeated hour (e.g. 'Europe/London'
- // and 'Europe/Lisbon').
- //
- $hb_insummertime = $this->inDaylightTime();
- if (PEAR::isError($hb_insummertime)) {
- if ($hb_insummertime->getCode() == DATE_ERROR_INVALIDTIME) {
- $hb_insummertime = false;
- } else {
- return $hb_insummertime;
- }
- }
-
- if (is_null($ps_id)) {
- $this->_setTZToDefault();
- } else if (Date_TimeZone::isValidID($ps_id)) {
- $this->tz = new Date_TimeZone($ps_id);
- } else {
- return PEAR::raiseError("Invalid time zone ID '$ps_id'",
- DATE_ERROR_INVALIDTIMEZONE);
- }
-
- $this->setLocalTime($this->day,
- $this->month,
- $this->year,
- $this->hour,
- $this->minute,
- $this->second,
- $this->partsecond,
- $hb_insummertime);
- }
-
-
- // }}}
- // {{{ getTZLongName()
-
- /**
- * Returns the long name of the time zone
- *
- * Returns long form of time zone name, e.g. 'Greenwich Mean Time'.
- * N.B. if the date falls in Summer time, the Summer time name will be
- * returned instead, e.g. 'British Summer Time'.
- *
- * N.B. this is not a unique identifier for the time zone - for this
- * purpose use the time zone ID.
- *
- * @return string the long name of the time zone
- * @access public
- * @since Method available since Release 1.5.0
- */
- function getTZLongName()
- {
- if ($this->ob_invalidtime)
- return $this->_getErrorInvalidTime();
-
- return $this->tz->getLongName($this->inDaylightTime());
- }
-
-
- // }}}
- // {{{ getTZShortName()
-
- /**
- * Returns the short name of the time zone
- *
- * Returns abbreviated form of time zone name, e.g. 'GMT'. N.B. if the
- * date falls in Summer time, the Summer time name will be returned
- * instead, e.g. 'BST'.
- *
- * N.B. this is not a unique identifier - for this purpose use the
- * time zone ID.
- *
- * @return string the short name of the time zone
- * @access public
- * @since Method available since Release 1.5.0
- */
- function getTZShortName()
- {
- if ($this->ob_invalidtime)
- return $this->_getErrorInvalidTime();
-
- return $this->tz->getShortName($this->inDaylightTime());
- }
-
-
- // }}}
- // {{{ getTZOffset()
-
- /**
- * Returns the DST-corrected offset from UTC for the given date
- *
- * Gets the offset to UTC for a given date/time, taking into
- * account daylight savings time, if the time zone observes it and if
- * it is in effect.
- *
- * N.B. that the offset is calculated historically
- * and in the future according to the current Summer time rules,
- * and so this function is proleptically correct, but not necessarily
- * historically correct. (Although if you want to be correct about
- * times in the distant past, this class is probably not for you
- * because the whole notion of time zones does not apply, and
- * historically there are so many time zone changes, Summer time
- * rule changes, name changes, calendar changes, that calculating
- * this sort of information is beyond the scope of this package
- * altogether.)
- *
- * @return int the corrected offset to UTC in milliseconds
- * @access public
- * @since Method available since Release 1.5.0
- */
- function getTZOffset()
- {
- if ($this->ob_invalidtime)
- return $this->_getErrorInvalidTime();
-
- return $this->tz->getOffset($this->inDaylightTime());
- }
-
-
- // }}}
- // {{{ inDaylightTime()
-
- /**
- * Tests if this date/time is in DST
- *
- * Returns true if daylight savings time is in effect for
- * this date in this date's time zone.
- *
- * @param bool $pb_repeatedhourdefault value to return if repeated hour is
- * specified (defaults to false)
- *
- * @return boolean true if DST is in effect for this date
- * @access public
- */
- function inDaylightTime($pb_repeatedhourdefault = false)
- {
- if (!$this->tz->hasDaylightTime())
- return false;
- if ($this->ob_invalidtime)
- return $this->_getErrorInvalidTime();
-
- // The return value is 'cached' whenever the date/time is set:
- //
- return $this->hour != $this->on_standardhour ||
- $this->minute != $this->on_standardminute ||
- $this->second != $this->on_standardsecond ||
- $this->partsecond != $this->on_standardpartsecond ||
- $this->day != $this->on_standardday ||
- $this->month != $this->on_standardmonth ||
- $this->year != $this->on_standardyear;
- //
- // (these last 3 conditions are theoretical
- // possibilities but normally will never occur)
- }
-
-
- // }}}
- // {{{ convertTZ()
-
- /**
- * Converts this date to a new time zone
- *
- * Previously this might not have worked correctly if your system did
- * not allow putenv() or if localtime() did not work in your
- * environment, but this implementation is no longer used.
- *
- * @param object $tz Date_TimeZone object to convert to
- *
- * @return void
- * @access public
- * @see Date::convertTZByID()
- */
- function convertTZ($tz)
- {
- if ($this->getTZID() == $tz->getID())
- return;
- if ($this->ob_invalidtime)
- return $this->_getErrorInvalidTime();
-
- $hn_rawoffset = $tz->getRawOffset() - $this->tz->getRawOffset();
- $this->tz = new Date_TimeZone($tz->getID());
-
- list($hn_standardyear,
- $hn_standardmonth,
- $hn_standardday,
- $hn_standardhour,
- $hn_standardminute,
- $hn_standardsecond,
- $hn_standardpartsecond) =
- $this->_addOffset($hn_rawoffset,
- $this->on_standardday,
- $this->on_standardmonth,
- $this->on_standardyear,
- $this->on_standardhour,
- $this->on_standardminute,
- $this->on_standardsecond,
- $this->on_standardpartsecond);
-
- $this->setStandardTime($hn_standardday,
- $hn_standardmonth,
- $hn_standardyear,
- $hn_standardhour,
- $hn_standardminute,
- $hn_standardsecond,
- $hn_standardpartsecond);
- }
-
-
- // }}}
- // {{{ toUTC()
-
- /**
- * Converts this date to UTC and sets this date's timezone to UTC
- *
- * @return void
- * @access public
- */
- function toUTC()
- {
- if ($this->getTZID() == "UTC")
- return;
- if ($this->ob_invalidtime)
- return $this->_getErrorInvalidTime();
-
- $res = $this->convertTZ(new Date_TimeZone("UTC"));
- if (PEAR::isError($res))
- return $res;
- }
-
-
- // }}}
- // {{{ convertTZByID()
-
- /**
- * Converts this date to a new time zone, given a valid time zone ID
- *
- * Previously this might not have worked correctly if your system did
- * not allow putenv() or if localtime() does not work in your
- * environment, but this implementation is no longer used.
- *
- * @param string $ps_id a valid time zone id, e.g. 'Europe/London'
- *
- * @return void
- * @access public
- * @see Date::setTZByID(), Date_TimeZone::isValidID(),
- * Date_TimeZone::Date_TimeZone()
- */
- function convertTZByID($ps_id)
- {
- if (!Date_TimeZone::isValidID($ps_id)) {
- return PEAR::raiseError("Invalid time zone ID '$ps_id'",
- DATE_ERROR_INVALIDTIMEZONE);
- }
-
- $res = $this->convertTZ(new Date_TimeZone($ps_id));
-
- if (PEAR::isError($res))
- return $res;
- }
-
-
- // }}}
- // {{{ toUTCbyOffset()
-
- /**
- * Converts the date/time to UTC by the offset specified
- *
- * This function is no longer called from within the Date class
- * itself because a time zone can be set using a pure offset
- * (e.g. UTC+1), i.e. not a geographical time zone. However
- * it is retained for backwards compaibility.
- *
- * @param string $ps_offset offset of the form '[+/-][hh]:[mm]',
- * '[+/-][hh][mm]', or 'Z'
- *
- * @return bool
- * @access private
- */
- function toUTCbyOffset($ps_offset)
- {
- if ($ps_offset == "Z" ||
- preg_match('/^[+\-](00:?00|0{1,2})$/', $ps_offset)) {
- $hs_tzid = "UTC";
- } else if (preg_match('/^[+\-]([0-9]{2,2}:?[0-5][0-9]|[0-9]{1,2})$/',
- $ps_offset)) {
- $hs_tzid = "UTC" . $ps_offset;
- } else {
- return PEAR::raiseError("Invalid offset '$ps_offset'");
- }
-
- // If the time is invalid, it does not matter here:
- //
- $this->setTZByID($hs_tzid);
-
- // Now the time will be valid because it is a time zone that
- // does not observe Summer time:
- //
- $this->toUTC();
- }
-
-
- // }}}
- // {{{ addYears()
-
- /**
- * Converts the date to the specified no of years from the given date
- *
- * To subtract years use a negative value for the '$pn_years'
- * parameter
- *
- * @param int $pn_years years to add
- *
- * @return void
- * @access public
- * @since Method available since Release 1.5.0
- */
- function addYears($pn_years)
- {
- list($hs_year, $hs_month, $hs_day) =
- explode(" ", Date_Calc::addYears($pn_years,
- $this->day,
- $this->month,
- $this->year,
- "%Y %m %d"));
- $this->setLocalTime($hs_day,
- $hs_month,
- $hs_year,
- $this->hour,
- $this->minute,
- $this->second,
- $this->partsecond);
- }
-
-
- // }}}
- // {{{ addMonths()
-
- /**
- * Converts the date to the specified no of months from the given date
- *
- * To subtract months use a negative value for the '$pn_months'
- * parameter
- *
- * @param int $pn_months months to add
- *
- * @return void
- * @access public
- * @since Method available since Release 1.5.0
- */
- function addMonths($pn_months)
- {
- list($hs_year, $hs_month, $hs_day) =
- explode(" ", Date_Calc::addMonths($pn_months,
- $this->day,
- $this->month,
- $this->year,
- "%Y %m %d"));
- $this->setLocalTime($hs_day,
- $hs_month,
- $hs_year,
- $this->hour,
- $this->minute,
- $this->second,
- $this->partsecond);
- }
-
-
- // }}}
- // {{{ addDays()
-
- /**
- * Converts the date to the specified no of days from the given date
- *
- * To subtract days use a negative value for the '$pn_days' parameter
- *
- * @param int $pn_days days to add
- *
- * @return void
- * @access public
- * @since Method available since Release 1.5.0
- */
- function addDays($pn_days)
- {
- list($hs_year, $hs_month, $hs_day) =
- explode(" ", Date_Calc::addDays($pn_days,
- $this->day,
- $this->month,
- $this->year,
- "%Y %m %d"));
- $this->setLocalTime($hs_day,
- $hs_month,
- $hs_year,
- $this->hour,
- $this->minute,
- $this->second,
- $this->partsecond);
- }
-
-
- // }}}
- // {{{ addHours()
-
- /**
- * Converts the date to the specified no of hours from the given date
- *
- * To subtract hours use a negative value for the '$pn_hours' parameter
- *
- * @param int $pn_hours hours to add
- *
- * @return void
- * @access public
- * @since Method available since Release 1.5.0
- */
- function addHours($pn_hours)
- {
- if ($this->ob_invalidtime)
- return $this->_getErrorInvalidTime();
-
- list($hn_standardyear,
- $hn_standardmonth,
- $hn_standardday,
- $hn_standardhour) =
- Date_Calc::addHours($pn_hours,
- $this->on_standardday,
- $this->on_standardmonth,
- $this->on_standardyear,
- $this->on_standardhour);
-
- $this->setStandardTime($hn_standardday,
- $hn_standardmonth,
- $hn_standardyear,
- $hn_standardhour,
- $this->on_standardminute,
- $this->on_standardsecond,
- $this->on_standardpartsecond);
- }
-
-
- // }}}
- // {{{ addMinutes()
-
- /**
- * Converts the date to the specified no of minutes from the given date
- *
- * To subtract minutes use a negative value for the '$pn_minutes' parameter
- *
- * @param int $pn_minutes minutes to add
- *
- * @return void
- * @access public
- * @since Method available since Release 1.5.0
- */
- function addMinutes($pn_minutes)
- {
- if ($this->ob_invalidtime)
- return $this->_getErrorInvalidTime();
-
- list($hn_standardyear,
- $hn_standardmonth,
- $hn_standardday,
- $hn_standardhour,
- $hn_standardminute) =
- Date_Calc::addMinutes($pn_minutes,
- $this->on_standardday,
- $this->on_standardmonth,
- $this->on_standardyear,
- $this->on_standardhour,
- $this->on_standardminute);
-
- $this->setStandardTime($hn_standardday,
- $hn_standardmonth,
- $hn_standardyear,
- $hn_standardhour,
- $hn_standardminute,
- $this->on_standardsecond,
- $this->on_standardpartsecond);
- }
-
-
- // }}}
- // {{{ addSeconds()
-
- /**
- * Adds a given number of seconds to the date
- *
- * @param mixed $sec the no of seconds to add as integer or float
- * @param bool $pb_countleap whether to count leap seconds (defaults to
- * value of count-leap-second object property)
- *
- * @return void
- * @access public
- */
- function addSeconds($sec, $pb_countleap = null)
- {
- if ($this->ob_invalidtime)
- return $this->_getErrorInvalidTime();
- if (!is_int($sec) && !is_float($sec))
- settype($sec, 'int');
- if (!is_null($pb_countleap))
- $pb_countleap = $this->ob_countleapseconds;
-
- if ($pb_countleap) {
- // Convert to UTC:
- //
- list($hn_standardyear,
- $hn_standardmonth,
- $hn_standardday,
- $hn_standardhour,
- $hn_standardminute,
- $hn_standardsecond,
- $hn_standardpartsecond) =
- $this->_addOffset($this->tz->getRawOffset() * -1,
- $this->on_standardday,
- $this->on_standardmonth,
- $this->on_standardyear,
- $this->on_standardhour,
- $this->on_standardminute,
- $this->on_standardsecond,
- $this->on_standardpartsecond);
- list($hn_standardyear,
- $hn_standardmonth,
- $hn_standardday,
- $hn_standardhour,
- $hn_standardminute,
- $hn_secondraw) =
- Date_Calc::addSeconds($sec,
- $hn_standardday,
- $hn_standardmonth,
- $hn_standardyear,
- $hn_standardhour,
- $hn_standardminute,
- $hn_standardpartsecond == 0.0 ?
- $hn_standardsecond :
- $hn_standardsecond +
- $hn_standardpartsecond,
- $pb_countleap);
-
- if (is_float($hn_secondraw)) {
- $hn_standardsecond = intval($hn_secondraw);
- $hn_standardpartsecond = $hn_secondraw - $hn_standardsecond;
- } else {
- $hn_standardsecond = $hn_secondraw;
- $hn_standardpartsecond = 0.0;
- }
-
- list($hn_standardyear,
- $hn_standardmonth,
- $hn_standardday,
- $hn_standardhour,
- $hn_standardminute,
- $hn_standardsecond,
- $hn_standardpartsecond) =
- $this->_addOffset($this->tz->getRawOffset(),
- $hn_standardday,
- $hn_standardmonth,
- $hn_standardyear,
- $hn_standardhour,
- $hn_standardminute,
- $hn_standardsecond,
- $hn_standardpartsecond);
- } else {
- // Use local standard time:
- //
- list($hn_standardyear,
- $hn_standardmonth,
- $hn_standardday,
- $hn_standardhour,
- $hn_standardminute,
- $hn_secondraw) =
- Date_Calc::addSeconds($sec,
- $this->on_standardday,
- $this->on_standardmonth,
- $this->on_standardyear,
- $this->on_standardhour,
- $this->on_standardminute,
- $this->on_standardpartsecond == 0.0 ?
- $this->on_standardsecond :
- $this->on_standardsecond +
- $this->on_standardpartsecond,
- false);
-
- if (is_float($hn_secondraw)) {
- $hn_standardsecond = intval($hn_secondraw);
- $hn_standardpartsecond = $hn_secondraw - $hn_standardsecond;
- } else {
- $hn_standardsecond = $hn_secondraw;
- $hn_standardpartsecond = 0.0;
- }
- }
-
- $this->setStandardTime($hn_standardday,
- $hn_standardmonth,
- $hn_standardyear,
- $hn_standardhour,
- $hn_standardminute,
- $hn_standardsecond,
- $hn_standardpartsecond);
- }
-
-
- // }}}
- // {{{ subtractSeconds()
-
- /**
- * Subtracts a given number of seconds from the date
- *
- * @param mixed $sec the no of seconds to subtract as integer or
- * float
- * @param bool $pb_countleap whether to count leap seconds (defaults to
- * value of count-leap-second object property)
- *
- * @return void
- * @access public
- */
- function subtractSeconds($sec, $pb_countleap = null)
- {
- if (is_null($pb_countleap))
- $pb_countleap = $this->ob_countleapseconds;
-
- $res = $this->addSeconds(-$sec, $pb_countleap);
-
- if (PEAR::isError($res))
- return $res;
- }
-
-
- // }}}
- // {{{ addSpan()
-
- /**
- * Adds a time span to the date
- *
- * A time span is defined as a unsigned no of days, hours, minutes
- * and seconds, where the no of minutes and seconds must be less than
- * 60, and the no of hours must be less than 24.
- *
- * A span is added (and subtracted) according to the following logic:
- *
- * Hours, minutes and seconds are added such that if they fall over
- * a leap second, the leap second is ignored, and not counted.
- * For example, if a leap second occurred at 23.59.60, the
- * following calculations:
- *
- * 23.59.59 + one second
- * 23.59.00 + one minute
- * 23.00.00 + one hour
- *
- * would all produce 00.00.00 the next day.
- *
- * A day is treated as equivalent to 24 hours, so if the clocks
- * went backwards at 01.00, and one day was added to the time
- * 00.30, the result would be 23.30 the same day.
- *
- * This is the implementation which is thought to yield the behaviour
- * that the user is most likely to expect, or in another way of
- * looking at it, it is the implementation that produces the least
- * unexpected behaviour. It basically works in hours, that is, a day
- * is treated as exactly equivalent to 24 hours, and minutes and
- * seconds are treated as equivalent to 1/60th and 1/3600th of an
- * hour. It should be obvious that working in days is impractical;
- * working in seconds is problematic when it comes to adding days
- * that fall over leap seconds, where it would appear to most users
- * that the function adds only 23 hours, 59 minutes and 59 seconds.
- * It is also problematic to work in any kind of mixture of days,
- * hours, minutes, and seconds, because then the addition of a span
- * would sometimes depend on which order you add the constituent
- * parts, which undermines the concept of a span altogether.
- *
- * If you want alternative functionality, you must use a mixture of
- * the following functions instead:
- *
- * addYears()
- * addMonths()
- * addDays()
- * addHours()
- * addMinutes()
- * addSeconds()
- *
- * @param object $span the time span to add
- *
- * @return void
- * @access public
- */
- function addSpan($span)
- {
- if (!is_a($span, 'Date_Span')) {
- return PEAR::raiseError("Invalid argument - not 'Date_Span' object");
- } else if ($this->ob_invalidtime) {
- return $this->_getErrorInvalidTime();
- }
-
- $hn_days = $span->day;
- $hn_standardhour = $this->on_standardhour + $span->hour;
- $hn_standardminute = $this->on_standardminute + $span->minute;
- $hn_standardsecond = $this->on_standardsecond + $span->second;
-
- if ($hn_standardsecond >= 60) {
- ++$hn_standardminute;
- $hn_standardsecond -= 60;
- }
-
- if ($hn_standardminute >= 60) {
- ++$hn_standardhour;
- $hn_standardminute -= 60;
- }
-
- if ($hn_standardhour >= 24) {
- ++$hn_days;
- $hn_standardhour -= 24;
- }
-
- list($hn_standardyear, $hn_standardmonth, $hn_standardday) =
- explode(" ",
- Date_Calc::addDays($hn_days,
- $this->on_standardday,
- $this->on_standardmonth,
- $this->on_standardyear,
- "%Y %m %d"));
-
- $this->setStandardTime($hn_standardday,
- $hn_standardmonth,
- $hn_standardyear,
- $hn_standardhour,
- $hn_standardminute,
- $hn_standardsecond,
- $this->on_standardpartsecond);
- }
-
-
- // }}}
- // {{{ subtractSpan()
-
- /**
- * Subtracts a time span from the date
- *
- * N.B. it is impossible for this function to count leap seconds,
- * because the result would be dependent on which order the consituent
- * parts of the span are subtracted from the date. Therefore, leap
- * seconds are ignored by this function. If you want to count leap
- * seconds, use 'subtractSeconds()'.
- *
- * @param object $span the time span to subtract
- *
- * @return void
- * @access public
- */
- function subtractSpan($span)
- {
- if (!is_a($span, 'Date_Span')) {
- return PEAR::raiseError("Invalid argument - not 'Date_Span' object");
- } else if ($this->ob_invalidtime) {
- return $this->_getErrorInvalidTime();
- }
-
- $hn_days = -$span->day;
- $hn_standardhour = $this->on_standardhour - $span->hour;
- $hn_standardminute = $this->on_standardminute - $span->minute;
- $hn_standardsecond = $this->on_standardsecond - $span->second;
-
- if ($hn_standardsecond < 0) {
- --$hn_standardminute;
- $hn_standardsecond += 60;
- }
-
- if ($hn_standardminute < 0) {
- --$hn_standardhour;
- $hn_standardminute += 60;
- }
-
- if ($hn_standardhour < 0) {
- --$hn_days;
- $hn_standardhour += 24;
- }
-
- list($hn_standardyear, $hn_standardmonth, $hn_standardday) =
- explode(" ",
- Date_Calc::addDays($hn_days,
- $this->on_standardday,
- $this->on_standardmonth,
- $this->on_standardyear,
- "%Y %m %d"));
-
- $this->setStandardTime($hn_standardday,
- $hn_standardmonth,
- $hn_standardyear,
- $hn_standardhour,
- $hn_standardminute,
- $hn_standardsecond,
- $this->on_standardpartsecond);
- }
-
-
- // }}}
- // {{{ dateDiff()
-
- /**
- * Subtract supplied date and return answer in days
- *
- * If the second parameter '$pb_ignoretime' is specified as false, the time
- * parts of the two dates will be ignored, and the integral no of days
- * between the day-month-year parts of the two dates will be returned. If
- * either of the two dates have an invalid time, the integral no of days
- * will also be returned, else the returned value will be the no of days as
- * a float, with each hour being treated as 1/24th of a day and so on.
- *
- * For example,
- * 21/11/2007 13.00 minus 21/11/2007 01.00
- * returns 0.5
- *
- * Note that if the passed date is in the past, a positive value will be
- * returned, and if it is in the future, a negative value will be returned.
- *
- * @param object $po_date date to subtract
- * @param bool $pb_ignoretime whether to ignore the time values of the two
- * dates in subtraction (defaults to false)
- *
- * @return mixed days between two dates as int or float
- * @access public
- * @since Method available since Release 1.5.0
- */
- function dateDiff($po_date, $pb_ignoretime = false)
- {
- if ($pb_ignoretime || $this->ob_invalidtime) {
- return Date_Calc::dateToDays($this->day,
- $this->month,
- $this->year) -
- Date_Calc::dateToDays($po_date->getDay(),
- $po_date->getMonth(),
- $po_date->getYear());
- }
-
- $hn_secondscompare = $po_date->getStandardSecondsPastMidnight();
- if (PEAR::isError($hn_secondscompare)) {
- if ($hn_secondscompare->getCode() != DATE_ERROR_INVALIDTIME) {
- return $hn_secondscompare;
- }
-
- return Date_Calc::dateToDays($this->day,
- $this->month,
- $this->year) -
- Date_Calc::dateToDays($po_date->getDay(),
- $po_date->getMonth(),
- $po_date->getYear());
- }
-
- $hn_seconds = $this->getStandardSecondsPastMidnight();
-
- // If time parts are equal, return int, else return float:
- //
- return Date_Calc::dateToDays($this->on_standardday,
- $this->on_standardmonth,
- $this->on_standardyear) -
- Date_Calc::dateToDays($po_date->getStandardDay(),
- $po_date->getStandardMonth(),
- $po_date->getStandardYear()) +
- ($hn_seconds == $hn_secondscompare ? 0 :
- ($hn_seconds - $hn_secondscompare) / 86400);
- }
-
-
- // }}}
- // {{{ inEquivalentTimeZones()
-
- /**
- * Tests whether two dates are in equivalent time zones
- *
- * Equivalence in this context consists in the time zones of the two dates
- * having:
- *
- * an equal offset from UTC in both standard and Summer time (if
- * the time zones observe Summer time)
- * the same Summer time start and end rules, that is, the two time zones
- * must switch from standard time to Summer time, and vice versa, on the
- * same day and at the same time
- *
- * An example of two equivalent time zones is 'Europe/London' and
- * 'Europe/Lisbon', which in London is known as GMT/BST, and in Lisbon as
- * WET/WEST.
- *
- * @param object $po_date1 the first Date object to compare
- * @param object $po_date2 the second Date object to compare
- *
- * @return bool true if the time zones are equivalent
- * @access public
- * @static
- * @since Method available since Release 1.5.0
- */
- function inEquivalentTimeZones($po_date1, $po_date2)
- {
- return $po_date1->tz->isEquivalent($po_date2->getTZID());
- }
-
-
- // }}}
- // {{{ compare()
-
- /**
- * Compares two dates
- *
- * Suitable for use in sorting functions.
- *
- * @param object $od1 the first Date object to compare
- * @param object $od2 the second Date object to compare
- *
- * @return int 0 if the dates are equal, -1 if '$od1' is
- * before '$od2', 1 if '$od1' is after '$od2'
- * @access public
- * @static
- */
- function compare($od1, $od2)
- {
- $d1 = new Date($od1);
- $d2 = new Date($od2);
-
- // If the time zones are equivalent, do nothing:
- //
- if (!Date::inEquivalentTimeZones($d1, $d2)) {
- // Only a time zone with a valid time can be converted:
- //
- if ($d2->isTimeValid()) {
- $d2->convertTZByID($d1->getTZID());
- } else if ($d1->isTimeValid()) {
- $d1->convertTZByID($d2->getTZID());
- } else {
- // No comparison can be made without guessing the time:
- //
- return PEAR::raiseError("Both dates have invalid time",
- DATE_ERROR_INVALIDTIME);
- }
- }
-
- $days1 = Date_Calc::dateToDays($d1->getDay(),
- $d1->getMonth(),
- $d1->getYear());
- $days2 = Date_Calc::dateToDays($d2->getDay(),
- $d2->getMonth(),
- $d2->getYear());
- if ($days1 < $days2)
- return -1;
- if ($days1 > $days2)
- return 1;
-
- $hn_hour1 = $d1->getStandardHour();
- if (PEAR::isError($hn_hour1))
- return $hn_hour1;
- $hn_hour2 = $d2->getStandardHour();
- if (PEAR::isError($hn_hour2))
- return $hn_hour2;
-
- if ($hn_hour1 < $hn_hour2) return -1;
- if ($hn_hour1 > $hn_hour2) return 1;
- if ($d1->getStandardMinute() < $d2->getStandardMinute()) return -1;
- if ($d1->getStandardMinute() > $d2->getStandardMinute()) return 1;
- if ($d1->getStandardSecond() < $d2->getStandardSecond()) return -1;
- if ($d1->getStandardSecond() > $d2->getStandardSecond()) return 1;
- if ($d1->getStandardPartSecond() < $d2->getStandardPartSecond()) return -1;
- if ($d1->getStandardPartSecond() > $d2->getStandardPartSecond()) return 1;
- return 0;
- }
-
-
- // }}}
- // {{{ before()
-
- /**
- * Test if this date/time is before a certain date/time
- *
- * @param object $when the Date object to test against
- *
- * @return boolean true if this date is before $when
- * @access public
- */
- function before($when)
- {
- $hn_compare = Date::compare($this, $when);
- if (PEAR::isError($hn_compare))
- return $hn_compare;
-
- if ($hn_compare == -1) {
- return true;
- } else {
- return false;
- }
- }
-
-
- // }}}
- // {{{ after()
-
- /**
- * Test if this date/time is after a certain date/time
- *
- * @param object $when the Date object to test against
- *
- * @return boolean true if this date is after $when
- * @access public
- */
- function after($when)
- {
- $hn_compare = Date::compare($this, $when);
- if (PEAR::isError($hn_compare))
- return $hn_compare;
-
- if ($hn_compare == 1) {
- return true;
- } else {
- return false;
- }
- }
-
-
- // }}}
- // {{{ equals()
-
- /**
- * Test if this date/time is exactly equal to a certain date/time
- *
- * @param object $when the Date object to test against
- *
- * @return boolean true if this date is exactly equal to $when
- * @access public
- */
- function equals($when)
- {
- $hn_compare = Date::compare($this, $when);
- if (PEAR::isError($hn_compare))
- return $hn_compare;
-
- if ($hn_compare == 0) {
- return true;
- } else {
- return false;
- }
- }
-
-
- // }}}
- // {{{ isFuture()
-
- /**
- * Determine if this date is in the future
- *
- * @return boolean true if this date is in the future
- * @access public
- */
- function isFuture()
- {
- $now = new Date();
- return $this->after($now);
- }
-
-
- // }}}
- // {{{ isPast()
-
- /**
- * Determine if this date is in the past
- *
- * @return boolean true if this date is in the past
- * @access public
- */
- function isPast()
- {
- $now = new Date();
- return $this->before($now);
- }
-
-
- // }}}
- // {{{ isLeapYear()
-
- /**
- * Determine if the year in this date is a leap year
- *
- * @return boolean true if this year is a leap year
- * @access public
- */
- function isLeapYear()
- {
- return Date_Calc::isLeapYear($this->year);
- }
-
-
- // }}}
- // {{{ getJulianDate()
-
- /**
- * Returns the no of days (1-366) since 31st December of the previous year
- *
- * N.B. this function does not return (and never has returned) the 'Julian
- * Date', as described, for example, at:
- *
- * http://en.wikipedia.org/wiki/Julian_day
- *
- * If you want the day of the year (0-366), use 'getDayOfYear()' instead.
- * If you want the true Julian Day, call one of the following:
- *
- * <code>format("%E")</code>
- * <code>format2("J")</code>
- *
- * There currently is no function that calls the Julian Date (as opposed
- * to the 'Julian Day'), although the Julian Day is an approximation.
- *
- * @return int the Julian date
- * @access public
- * @see Date::getDayOfYear()
- * @deprecated Method deprecated in Release 1.5.0
- */
- function getJulianDate()
- {
- return Date_Calc::julianDate($this->day, $this->month, $this->year);
- }
-
-
- // }}}
- // {{{ getDayOfYear()
-
- /**
- * Returns the no of days (1-366) since 31st December of the previous year
- *
- * @return int an integer between 1 and 366
- * @access public
- * @since Method available since Release 1.5.0
- */
- function getDayOfYear()
- {
- return Date_Calc::dayOfYear($this->day, $this->month, $this->year);
- }
-
-
- // }}}
- // {{{ getDayOfWeek()
-
- /**
- * Gets the day of the week for this date (0 = Sunday)
- *
- * @return int the day of the week (0 = Sunday)
- * @access public
- */
- function getDayOfWeek()
- {
- return Date_Calc::dayOfWeek($this->day, $this->month, $this->year);
- }
-
-
- // }}}
- // {{{ getWeekOfYear()
-
- /**
- * Gets the week of the year for this date
- *
- * @return int the week of the year
- * @access public
- */
- function getWeekOfYear()
- {
- return Date_Calc::weekOfYear($this->day, $this->month, $this->year);
- }
-
-
- // }}}
- // {{{ getQuarterOfYear()
-
- /**
- * Gets the quarter of the year for this date
- *
- * @return int the quarter of the year (1-4)
- * @access public
- */
- function getQuarterOfYear()
- {
- return Date_Calc::quarterOfYear($this->day, $this->month, $this->year);
- }
-
-
- // }}}
- // {{{ getDaysInMonth()
-
- /**
- * Gets number of days in the month for this date
- *
- * @return int number of days in this month
- * @access public
- */
- function getDaysInMonth()
- {
- return Date_Calc::daysInMonth($this->month, $this->year);
- }
-
-
- // }}}
- // {{{ getWeeksInMonth()
-
- /**
- * Gets the number of weeks in the month for this date
- *
- * @return int number of weeks in this month
- * @access public
- */
- function getWeeksInMonth()
- {
- return Date_Calc::weeksInMonth($this->month, $this->year);
- }
-
-
- // }}}
- // {{{ getDayName()
-
- /**
- * Gets the full name or abbreviated name of this weekday
- *
- * @param bool $abbr abbreviate the name
- * @param int $length length of abbreviation
- *
- * @return string name of this day
- * @access public
- */
- function getDayName($abbr = false, $length = 3)
- {
- if ($abbr) {
- return Date_Calc::getWeekdayAbbrname($this->day,
- $this->month,
- $this->year,
- $length);
- } else {
- return Date_Calc::getWeekdayFullname($this->day,
- $this->month,
- $this->year);
- }
- }
-
-
- // }}}
- // {{{ getMonthName()
-
- /**
- * Gets the full name or abbreviated name of this month
- *
- * @param boolean $abbr abbreviate the name
- *
- * @return string name of this month
- * @access public
- */
- function getMonthName($abbr = false)
- {
- if ($abbr) {
- return Date_Calc::getMonthAbbrname($this->month);
- } else {
- return Date_Calc::getMonthFullname($this->month);
- }
- }
-
-
- // }}}
- // {{{ getNextDay()
-
- /**
- * Get a Date object for the day after this one
- *
- * The time of the returned Date object is the same as this time.
- *
- * @return object Date object representing the next day
- * @access public
- */
- function getNextDay()
- {
- $ret = new Date($this);
- $ret->addDays(1);
- return $ret;
- }
-
-
- // }}}
- // {{{ getPrevDay()
-
- /**
- * Get a Date object for the day before this one
- *
- * The time of the returned Date object is the same as this time.
- *
- * @return object Date object representing the previous day
- * @access public
- */
- function getPrevDay()
- {
- $ret = new Date($this);
- $ret->addDays(-1);
- return $ret;
- }
-
-
- // }}}
- // {{{ getNextWeekday()
-
- /**
- * Get a Date object for the weekday after this one
- *
- * The time of the returned Date object is the same as this time.
- *
- * @return object Date object representing the next week-day
- * @access public
- */
- function getNextWeekday()
- {
- $ret = new Date($this);
- list($hs_year, $hs_month, $hs_day) =
- explode(" ", Date_Calc::nextWeekday($this->day,
- $this->month,
- $this->year,
- "%Y %m %d"));
- $ret->setDayMonthYear($hs_day, $hs_month, $hs_year);
- return $ret;
- }
-
-
- // }}}
- // {{{ getPrevWeekday()
-
- /**
- * Get a Date object for the weekday before this one
- *
- * The time of the returned Date object is the same as this time.
- *
- * @return object Date object representing the previous week-day
- * @access public
- */
- function getPrevWeekday()
- {
- $ret = new Date($this);
- list($hs_year, $hs_month, $hs_day) =
- explode(" ", Date_Calc::prevWeekday($this->day,
- $this->month,
- $this->year,
- "%Y %m %d"));
- $ret->setDayMonthYear($hs_day, $hs_month, $hs_year);
- return $ret;
- }
-
-
- // }}}
- // {{{ getYear()
-
- /**
- * Returns the year field of the date object
- *
- * @return int the year
- * @access public
- */
- function getYear()
- {
- return $this->year;
- }
-
-
- // }}}
- // {{{ getMonth()
-
- /**
- * Returns the month field of the date object
- *
- * @return int the minute
- * @access public
- */
- function getMonth()
- {
- return $this->month;
- }
-
-
- // }}}
- // {{{ getDay()
-
- /**
- * Returns the day field of the date object
- *
- * @return int the day
- * @access public
- */
- function getDay()
- {
- return $this->day;
- }
-
-
- // }}}
- // {{{ _getErrorInvalidTime()
-
- /**
- * Returns invalid time PEAR Error
- *
- * @return object
- * @access private
- * @since Method available since Release 1.5.0
- */
- function _getErrorInvalidTime()
- {
- return PEAR::raiseError("Invalid time '" .
- sprintf("%02d.%02d.%02d",
- $this->hour,
- $this->minute,
- $this->second) .
- "' specified for date '" .
- Date_Calc::dateFormat($this->day,
- $this->month,
- $this->year,
- "%Y-%m-%d") .
- "' and in this timezone",
- DATE_ERROR_INVALIDTIME);
- }
-
-
- // }}}
- // {{{ _secondsInDayIsValid()
-
- /**
- * If leap seconds are observed, checks if the seconds in the day is valid
- *
- * Note that only the local standard time is accessed.
- *
- * @return bool
- * @access private
- * @since Method available since Release 1.5.0
- */
- function _secondsInDayIsValid()
- {
- if ($this->ob_countleapseconds) {
- // Convert to UTC:
- //
- list($hn_year,
- $hn_month,
- $hn_day,
- $hn_hour,
- $hn_minute,
- $hn_second,
- $hn_partsecond) =
- $this->_addOffset($this->tz->getRawOffset() * -1,
- $this->on_standardday,
- $this->on_standardmonth,
- $this->on_standardyear,
- $this->on_standardhour,
- $this->on_standardminute,
- $this->on_standardsecond,
- $this->on_standardpartsecond);
- return Date_Calc::secondsPastMidnight($hn_hour,
- $hn_minute,
- $hn_second +
- $hn_partsecond) <
- Date_Calc::getSecondsInDay($hn_day, $hn_month, $hn_year);
- } else {
- return $this->getStandardSecondsPastMidnight() < 86400;
- }
- }
-
-
- // }}}
- // {{{ isTimeValid()
-
- /**
- * Whether the stored time is valid as a local time
- *
- * An invalid time is one that lies in the 'skipped hour' at the point
- * that the clocks go forward. Note that the stored date (i.e.
- * the day/month/year, is always valid).
- *
- * The object is able to store an invalid time because a user might
- * unwittingly and correctly store a valid time, and then add one day so
- * as to put the object in the 'skipped' hour (when the clocks go forward).
- * This could be corrected by a conversion to Summer time (by adding one
- * hour); however, if the user then added another day, and had no need for
- * or interest in the time anyway, the behaviour may be rather unexpected.
- * And anyway in this situation, the time originally specified would now,
- * two days on, be valid again.
- *
- * So this class allows an invalid time like this so long as the user does
- * not in any way make use of or request the time while it is in this
- * semi-invalid state, in order to allow for for the fact that he might be
- * only interested in the date, and not the time, and in order not to behave
- * in an unexpected way, especially without throwing an exception to tell
- * the user about it.
- *
- * @return bool
- * @access public
- * @since Method available since Release 1.5.0
- */
- function isTimeValid()
- {
- return !$this->ob_invalidtime;
- }
-
-
- // }}}
- // {{{ getHour()
-
- /**
- * Returns the hour field of the date object
- *
- * @return int the hour
- * @access public
- */
- function getHour()
- {
- if ($this->ob_invalidtime)
- return $this->_getErrorInvalidTime();
-
- return $this->hour;
- }
-
-
- // }}}
- // {{{ getMinute()
-
- /**
- * Returns the minute field of the date object
- *
- * @return int the minute
- * @access public
- */
- function getMinute()
- {
- if ($this->ob_invalidtime)
- return $this->_getErrorInvalidTime();
-
- return $this->minute;
- }
-
-
- // }}}
- // {{{ getSecond()
-
- /**
- * Returns the second field of the date object
- *
- * @return int the second
- * @access public
- */
- function getSecond()
- {
- if ($this->ob_invalidtime)
- return $this->_getErrorInvalidTime();
-
- return $this->second;
- }
-
-
- // }}}
- // {{{ getSecondsPastMidnight()
-
- /**
- * Returns the no of seconds since midnight (0-86400) as float
- *
- * @return float float which is at least 0 and less than 86400
- * @access public
- * @since Method available since Release 1.5.0
- */
- function getSecondsPastMidnight()
- {
- if ($this->ob_invalidtime)
- return $this->_getErrorInvalidTime();
-
- return Date_Calc::secondsPastMidnight($this->hour,
- $this->minute,
- $this->second) +
- $this->partsecond;
- }
-
-
- // }}}
- // {{{ getPartSecond()
-
- /**
- * Returns the part-second field of the date object
- *
- * @return float the part-second
- * @access protected
- * @since Method available since Release 1.5.0
- */
- function getPartSecond()
- {
- if ($this->ob_invalidtime)
- return $this->_getErrorInvalidTime();
-
- return $this->partsecond;
- }
-
-
- // }}}
- // {{{ getStandardYear()
-
- /**
- * Returns the year field of the local standard time
- *
- * @return int the year
- * @access public
- * @since Method available since Release 1.5.0
- */
- function getStandardYear()
- {
- if ($this->ob_invalidtime)
- return $this->_getErrorInvalidTime();
-
- return $this->on_standardyear;
- }
-
-
- // }}}
- // {{{ getStandardMonth()
-
- /**
- * Returns the month field of the local standard time
- *
- * @return int the minute
- * @access public
- * @since Method available since Release 1.5.0
- */
- function getStandardMonth()
- {
- if ($this->ob_invalidtime)
- return $this->_getErrorInvalidTime();
-
- return $this->on_standardmonth;
- }
-
-
- // }}}
- // {{{ getStandardDay()
-
- /**
- * Returns the day field of the local standard time
- *
- * @return int the day
- * @access public
- * @since Method available since Release 1.5.0
- */
- function getStandardDay()
- {
- if ($this->ob_invalidtime)
- return $this->_getErrorInvalidTime();
-
- return $this->on_standardday;
- }
-
-
- // }}}
- // {{{ getStandardHour()
-
- /**
- * Returns the hour field of the local standard time
- *
- * @return int the hour
- * @access public
- * @since Method available since Release 1.5.0
- */
- function getStandardHour()
- {
- if ($this->ob_invalidtime)
- return $this->_getErrorInvalidTime();
-
- return $this->on_standardhour;
- }
-
-
- // }}}
- // {{{ getStandardMinute()
-
- /**
- * Returns the minute field of the local standard time
- *
- * @return int the minute
- * @access public
- * @since Method available since Release 1.5.0
- */
- function getStandardMinute()
- {
- if ($this->ob_invalidtime)
- return $this->_getErrorInvalidTime();
-
- return $this->on_standardminute;
- }
-
-
- // }}}
- // {{{ getStandardSecond()
-
- /**
- * Returns the second field of the local standard time
- *
- * @return int the second
- * @access public
- * @since Method available since Release 1.5.0
- */
- function getStandardSecond()
- {
- if ($this->ob_invalidtime)
- return $this->_getErrorInvalidTime();
-
- return $this->on_standardsecond;
- }
-
-
- // }}}
- // {{{ getStandardSecondsPastMidnight()
-
- /**
- * Returns the no of seconds since midnight (0-86400) of the
- * local standard time as float
- *
- * @return float float which is at least 0 and less than 86400
- * @access public
- * @since Method available since Release 1.5.0
- */
- function getStandardSecondsPastMidnight()
- {
- if ($this->ob_invalidtime)
- return $this->_getErrorInvalidTime();
-
- return Date_Calc::secondsPastMidnight($this->on_standardhour,
- $this->on_standardminute,
- $this->on_standardsecond) +
- $this->on_standardpartsecond;
- }
-
-
- // }}}
- // {{{ getStandardPartSecond()
-
- /**
- * Returns the part-second field of the local standard time
- *
- * @return float the part-second
- * @access protected
- * @since Method available since Release 1.5.0
- */
- function getStandardPartSecond()
- {
- if ($this->ob_invalidtime)
- return $this->_getErrorInvalidTime();
-
- return $this->on_standardpartsecond;
- }
-
-
- // }}}
- // {{{ _addOffset()
-
- /**
- * Add a time zone offset to the passed date/time
- *
- * @param int $pn_offset the offset to add in milliseconds
- * @param int $pn_day the day
- * @param int $pn_month the month
- * @param int $pn_year the year
- * @param int $pn_hour the hour
- * @param int $pn_minute the minute
- * @param int $pn_second the second
- * @param float $pn_partsecond the part-second
- *
- * @return array array of year, month, day, hour, minute, second,
- * and part-second
- * @access private
- * @static
- * @since Method available since Release 1.5.0
- */
- function _addOffset($pn_offset,
- $pn_day,
- $pn_month,
- $pn_year,
- $pn_hour,
- $pn_minute,
- $pn_second,
- $pn_partsecond)
- {
- if ($pn_offset == 0) {
- return array((int) $pn_year,
- (int) $pn_month,
- (int) $pn_day,
- (int) $pn_hour,
- (int) $pn_minute,
- (int) $pn_second,
- (float) $pn_partsecond);
- }
-
- if ($pn_offset % 3600000 == 0) {
- list($hn_year,
- $hn_month,
- $hn_day,
- $hn_hour) =
- Date_Calc::addHours($pn_offset / 3600000,
- $pn_day,
- $pn_month,
- $pn_year,
- $pn_hour);
-
- $hn_minute = (int) $pn_minute;
- $hn_second = (int) $pn_second;
- $hn_partsecond = (float) $pn_partsecond;
- } else if ($pn_offset % 60000 == 0) {
- list($hn_year,
- $hn_month,
- $hn_day,
- $hn_hour,
- $hn_minute) =
- Date_Calc::addMinutes($pn_offset / 60000,
- $pn_day,
- $pn_month,
- $pn_year,
- $pn_hour,
- $pn_minute);
-
- $hn_second = (int) $pn_second;
- $hn_partsecond = (float) $pn_partsecond;
- } else {
- list($hn_year,
- $hn_month,
- $hn_day,
- $hn_hour,
- $hn_minute,
- $hn_secondraw) =
- Date_Calc::addSeconds($pn_offset / 1000,
- $pn_day,
- $pn_month,
- $pn_year,
- $pn_hour,
- $pn_partsecond == 0.0 ?
- $pn_second :
- $pn_second + $pn_partsecond,
- false); // N.B. do not count
- // leap seconds
-
- if (is_float($hn_secondraw)) {
- $hn_second = intval($hn_secondraw);
- $hn_partsecond = $hn_secondraw - $hn_second;
- } else {
- $hn_second = $hn_secondraw;
- $hn_partsecond = 0.0;
- }
- }
-
- return array($hn_year,
- $hn_month,
- $hn_day,
- $hn_hour,
- $hn_minute,
- $hn_second,
- $hn_partsecond);
- }
-
-
- // }}}
- // {{{ setLocalTime()
-
- /**
- * Sets local time (Summer-time-adjusted) and then calculates local
- * standard time
- *
- * @param int $pn_day the day
- * @param int $pn_month the month
- * @param int $pn_year the year
- * @param int $pn_hour the hour
- * @param int $pn_minute the minute
- * @param int $pn_second the second
- * @param float $pn_partsecond the part-second
- * @param bool $pb_repeatedhourdefault whether to assume Summer time if a
- * repeated hour is specified (defaults
- * to false)
- * @param bool $pb_correctinvalidtime whether to correct, by adding the
- * local Summer time offset, the
- * specified time if it falls in the
- * skipped hour (defaults to
- * DATE_CORRECTINVALIDTIME_DEFAULT)
- *
- * @return void
- * @access protected
- * @see Date::setStandardTime()
- * @since Method available since Release 1.5.0
- */
- function setLocalTime($pn_day,
- $pn_month,
- $pn_year,
- $pn_hour,
- $pn_minute,
- $pn_second,
- $pn_partsecond,
- $pb_repeatedhourdefault = false,
- $pb_correctinvalidtime = DATE_CORRECTINVALIDTIME_DEFAULT)
- {
- settype($pn_day, "int");
- settype($pn_month, "int");
- settype($pn_year, "int");
- settype($pn_hour, "int");
- settype($pn_minute, "int");
- settype($pn_second, "int");
- settype($pn_partsecond, "float");
-
- $hb_insummertime =
- $this->tz->inDaylightTime(array($pn_day,
- $pn_month, $pn_year, Date_Calc::secondsPastMidnight($pn_hour,
- $pn_minute, $pn_second) + $pn_partsecond),
- $pb_repeatedhourdefault);
- if (PEAR::isError($hb_insummertime)) {
- if ($hb_insummertime->getCode() != DATE_ERROR_INVALIDTIME) {
- return $hb_insummertime;
- } else if ($pb_correctinvalidtime) {
- // Store passed time as local standard time:
- //
- $this->on_standardday = $pn_day;
- $this->on_standardmonth = $pn_month;
- $this->on_standardyear = $pn_year;
- $this->on_standardhour = $pn_hour;
- $this->on_standardminute = $pn_minute;
- $this->on_standardsecond = $pn_second;
- $this->on_standardpartsecond = $pn_partsecond;
-
- // Add Summer time offset to passed time:
- //
- list($this->year,
- $this->month,
- $this->day,
- $this->hour,
- $this->minute,
- $this->second,
- $this->partsecond) =
- $this->_addOffset($this->tz->getDSTSavings(),
- $pn_day,
- $pn_month,
- $pn_year,
- $pn_hour,
- $pn_minute,
- $pn_second,
- $pn_partsecond);
-
- $this->ob_invalidtime = !$this->_secondsInDayIsValid();
- } else {
- // Hedge bets - if the user adds/subtracts a day, then the time
- // will be uncorrupted, and if the user does
- // addition/subtraction with the time, or requests the time,
- // then return an error at that point:
- //
- $this->day = $pn_day;
- $this->month = $pn_month;
- $this->year = $pn_year;
- $this->hour = $pn_hour;
- $this->minute = $pn_minute;
- $this->second = $pn_second;
- $this->partsecond = $pn_partsecond;
-
- $this->ob_invalidtime = true;
- }
-
- return;
- } else {
- // Passed time is valid as local time:
- //
- $this->day = $pn_day;
- $this->month = $pn_month;
- $this->year = $pn_year;
- $this->hour = $pn_hour;
- $this->minute = $pn_minute;
- $this->second = $pn_second;
- $this->partsecond = $pn_partsecond;
- }
-
- $this->ob_invalidtime = !$this->_secondsInDayIsValid();
-
- if ($hb_insummertime) {
- // Calculate local standard time:
- //
- list($this->on_standardyear,
- $this->on_standardmonth,
- $this->on_standardday,
- $this->on_standardhour,
- $this->on_standardminute,
- $this->on_standardsecond,
- $this->on_standardpartsecond) =
- $this->_addOffset($this->tz->getDSTSavings() * -1,
- $pn_day,
- $pn_month,
- $pn_year,
- $pn_hour,
- $pn_minute,
- $pn_second,
- $pn_partsecond);
- } else {
- // Time is already local standard time:
- //
- $this->on_standardday = $pn_day;
- $this->on_standardmonth = $pn_month;
- $this->on_standardyear = $pn_year;
- $this->on_standardhour = $pn_hour;
- $this->on_standardminute = $pn_minute;
- $this->on_standardsecond = $pn_second;
- $this->on_standardpartsecond = $pn_partsecond;
- }
- }
-
-
- // }}}
- // {{{ setStandardTime()
-
- /**
- * Sets local standard time and then calculates local time (i.e.
- * Summer-time-adjusted)
- *
- * @param int $pn_day the day
- * @param int $pn_month the month
- * @param int $pn_year the year
- * @param int $pn_hour the hour
- * @param int $pn_minute the minute
- * @param int $pn_second the second
- * @param float $pn_partsecond the part-second
- *
- * @return void
- * @access protected
- * @see Date::setLocalTime()
- * @since Method available since Release 1.5.0
- */
- function setStandardTime($pn_day,
- $pn_month,
- $pn_year,
- $pn_hour,
- $pn_minute,
- $pn_second,
- $pn_partsecond)
- {
- settype($pn_day, "int");
- settype($pn_month, "int");
- settype($pn_year, "int");
- settype($pn_hour, "int");
- settype($pn_minute, "int");
- settype($pn_second, "int");
- settype($pn_partsecond, "float");
-
- $this->on_standardday = $pn_day;
- $this->on_standardmonth = $pn_month;
- $this->on_standardyear = $pn_year;
- $this->on_standardhour = $pn_hour;
- $this->on_standardminute = $pn_minute;
- $this->on_standardsecond = $pn_second;
- $this->on_standardpartsecond = $pn_partsecond;
-
- $this->ob_invalidtime = !$this->_secondsInDayIsValid();
-
- if ($this->tz->inDaylightTimeStandard(array($pn_day, $pn_month,
- $pn_year, Date_Calc::secondsPastMidnight($pn_hour, $pn_minute,
- $pn_second) + $pn_partsecond))) {
-
- // Calculate local time:
- //
- list($this->year,
- $this->month,
- $this->day,
- $this->hour,
- $this->minute,
- $this->second,
- $this->partsecond) =
- $this->_addOffset($this->tz->getDSTSavings(),
- $pn_day,
- $pn_month,
- $pn_year,
- $pn_hour,
- $pn_minute,
- $pn_second,
- $pn_partsecond);
- } else {
- // Time is already local time:
- //
- $this->day = $pn_day;
- $this->month = $pn_month;
- $this->year = $pn_year;
- $this->hour = $pn_hour;
- $this->minute = $pn_minute;
- $this->second = $pn_second;
- $this->partsecond = $pn_partsecond;
- }
- }
-
-
- // }}}
- // {{{ setYear()
-
- /**
- * Sets the year field of the date object
- *
- * If specified year forms an invalid date, then PEAR error will be
- * returned, unless the validation is over-ridden using the second
- * parameter.
- *
- * @param int $y the year
- * @param bool $pb_validate whether to check that the new date is valid
- *
- * @return void
- * @access public
- * @see Date::setDayMonthYear(), Date::setDateTime()
- */
- function setYear($y, $pb_validate = DATE_VALIDATE_DATE_BY_DEFAULT)
- {
- if ($pb_validate && !Date_Calc::isValidDate($this->day, $this->month, $y)) {
- return PEAR::raiseError("'" .
- Date_Calc::dateFormat($this->day,
- $this->month,
- $y,
- "%Y-%m-%d") .
- "' is invalid calendar date",
- DATE_ERROR_INVALIDDATE);
- } else {
- $this->setLocalTime($this->day,
- $this->month,
- $y,
- $this->hour,
- $this->minute,
- $this->second,
- $this->partsecond);
- }
- }
-
-
- // }}}
- // {{{ setMonth()
-
- /**
- * Sets the month field of the date object
- *
- * If specified year forms an invalid date, then PEAR error will be
- * returned, unless the validation is over-ridden using the second
- * parameter.
- *
- * @param int $m the month
- * @param bool $pb_validate whether to check that the new date is valid
- *
- * @return void
- * @access public
- * @see Date::setDayMonthYear(), Date::setDateTime()
- */
- function setMonth($m, $pb_validate = DATE_VALIDATE_DATE_BY_DEFAULT)
- {
- if ($pb_validate && !Date_Calc::isValidDate($this->day, $m, $this->year)) {
- return PEAR::raiseError("'" .
- Date_Calc::dateFormat($this->day,
- $m,
- $this->year,
- "%Y-%m-%d") .
- "' is invalid calendar date",
- DATE_ERROR_INVALIDDATE);
- } else {
- $this->setLocalTime($this->day,
- $m,
- $this->year,
- $this->hour,
- $this->minute,
- $this->second,
- $this->partsecond);
- }
- }
-
-
- // }}}
- // {{{ setDay()
-
- /**
- * Sets the day field of the date object
- *
- * If specified year forms an invalid date, then PEAR error will be
- * returned, unless the validation is over-ridden using the second
- * parameter.
- *
- * @param int $d the day
- * @param bool $pb_validate whether to check that the new date is valid
- *
- * @return void
- * @access public
- * @see Date::setDayMonthYear(), Date::setDateTime()
- */
- function setDay($d, $pb_validate = DATE_VALIDATE_DATE_BY_DEFAULT)
- {
- if ($pb_validate && !Date_Calc::isValidDate($d, $this->month, $this->year)) {
- return PEAR::raiseError("'" .
- Date_Calc::dateFormat($d,
- $this->month,
- $this->year,
- "%Y-%m-%d") .
- "' is invalid calendar date",
- DATE_ERROR_INVALIDDATE);
- } else {
- $this->setLocalTime($d,
- $this->month,
- $this->year,
- $this->hour,
- $this->minute,
- $this->second,
- $this->partsecond);
- }
- }
-
-
- // }}}
- // {{{ setDayMonthYear()
-
- /**
- * Sets the day, month and year fields of the date object
- *
- * If specified year forms an invalid date, then PEAR error will be
- * returned. Note that setting each of these fields separately
- * may unintentionally return a PEAR error if a transitory date is
- * invalid between setting these fields.
- *
- * @param int $d the day
- * @param int $m the month
- * @param int $y the year
- *
- * @return void
- * @access public
- * @see Date::setDateTime()
- * @since Method available since Release 1.5.0
- */
- function setDayMonthYear($d, $m, $y)
- {
- if (!Date_Calc::isValidDate($d, $m, $y)) {
- return PEAR::raiseError("'" .
- Date_Calc::dateFormat($d,
- $m,
- $y,
- "%Y-%m-%d") .
- "' is invalid calendar date",
- DATE_ERROR_INVALIDDATE);
- } else {
- $this->setLocalTime($d,
- $m,
- $y,
- $this->hour,
- $this->minute,
- $this->second,
- $this->partsecond);
- }
- }
-
-
- // }}}
- // {{{ setHour()
-
- /**
- * Sets the hour field of the date object
- *
- * Expects an hour in 24-hour format.
- *
- * @param int $h the hour
- * @param bool $pb_repeatedhourdefault whether to assume Summer time if a
- * repeated hour is specified (defaults
- * to false)
- *
- * @return void
- * @access public
- * @see Date::setHourMinuteSecond(), Date::setDateTime()
- */
- function setHour($h, $pb_repeatedhourdefault = false)
- {
- if ($h > 23 || $h < 0) {
- return PEAR::raiseError("Invalid hour value '$h'");
- } else {
- $ret = $this->setHourMinuteSecond($h,
- $this->minute,
- $this->partsecond == 0.0 ?
- $this->second :
- $this->second + $this->partsecond,
- $pb_repeatedhourdefault);
-
- if (PEAR::isError($ret))
- return $ret;
- }
- }
-
-
- // }}}
- // {{{ setMinute()
-
- /**
- * Sets the minute field of the date object
- *
- * @param int $m the minute
- * @param bool $pb_repeatedhourdefault whether to assume Summer time if a
- * repeated hour is specified (defaults
- * to false)
- *
- * @return void
- * @access public
- * @see Date::setHourMinuteSecond(), Date::setDateTime()
- */
- function setMinute($m, $pb_repeatedhourdefault = false)
- {
- if ($m > 59 || $m < 0) {
- return PEAR::raiseError("Invalid minute value '$m'");
- } else {
- $ret = $this->setHourMinuteSecond($this->hour,
- $m,
- $this->partsecond == 0.0 ?
- $this->second :
- $this->second + $this->partsecond,
- $pb_repeatedhourdefault);
-
- if (PEAR::isError($ret))
- return $ret;
- }
- }
-
-
- // }}}
- // {{{ setSecond()
-
- /**
- * Sets the second field of the date object
- *
- * @param mixed $s the second as integer or float
- * @param bool $pb_repeatedhourdefault whether to assume Summer time if a
- * repeated hour is specified
- * (defaults to false)
- *
- * @return void
- * @access public
- * @see Date::setHourMinuteSecond(), Date::setDateTime()
- */
- function setSecond($s, $pb_repeatedhourdefault = false)
- {
- if ($s > 60 || // Leap seconds possible
- $s < 0) {
- return PEAR::raiseError("Invalid second value '$s'");
- } else {
- $ret = $this->setHourMinuteSecond($this->hour,
- $this->minute,
- $s,
- $pb_repeatedhourdefault);
-
- if (PEAR::isError($ret))
- return $ret;
- }
- }
-
-
- // }}}
- // {{{ setPartSecond()
-
- /**
- * Sets the part-second field of the date object
- *
- * @param float $pn_ps the part-second
- * @param bool $pb_repeatedhourdefault whether to assume Summer time if a
- * repeated hour is specified (defaults
- * to false)
- *
- * @return void
- * @access protected
- * @see Date::setHourMinuteSecond(), Date::setDateTime()
- * @since Method available since Release 1.5.0
- */
- function setPartSecond($pn_ps, $pb_repeatedhourdefault = false)
- {
- if ($pn_ps >= 1 || $pn_ps < 0) {
- return PEAR::raiseError("Invalid part-second value '$pn_ps'");
- } else {
- $ret = $this->setHourMinuteSecond($this->hour,
- $this->minute,
- $this->second + $pn_ps,
- $pb_repeatedhourdefault);
-
- if (PEAR::isError($ret))
- return $ret;
- }
- }
-
-
- // }}}
- // {{{ setHourMinuteSecond()
-
- /**
- * Sets the hour, minute, second and part-second fields of the date object
- *
- * N.B. if the repeated hour, due to the clocks going back, is specified,
- * the default is to assume local standard time.
- *
- * @param int $h the hour
- * @param int $m the minute
- * @param mixed $s the second as integer or float
- * @param bool $pb_repeatedhourdefault whether to assume Summer time if a
- * repeated hour is specified
- * (defaults to false)
- *
- * @return void
- * @access public
- * @see Date::setDateTime()
- * @since Method available since Release 1.5.0
- */
- function setHourMinuteSecond($h, $m, $s, $pb_repeatedhourdefault = false)
- {
- // Split second into integer and part-second:
- //
- if (is_float($s)) {
- $hn_second = intval($s);
- $hn_partsecond = $s - $hn_second;
- } else {
- $hn_second = (int) $s;
- $hn_partsecond = 0.0;
- }
-
- $this->setLocalTime($this->day,
- $this->month,
- $this->year,
- $h,
- $m,
- $hn_second,
- $hn_partsecond,
- $pb_repeatedhourdefault);
- }
-
-
- // }}}
- // {{{ setDateTime()
-
- /**
- * Sets all the fields of the date object (day, month, year, hour, minute
- * and second)
- *
- * If specified year forms an invalid date, then PEAR error will be
- * returned. Note that setting each of these fields separately
- * may unintentionally return a PEAR error if a transitory date is
- * invalid between setting these fields.
- *
- * N.B. if the repeated hour, due to the clocks going back, is specified,
- * the default is to assume local standard time.
- *
- * @param int $pn_day the day
- * @param int $pn_month the month
- * @param int $pn_year the year
- * @param int $pn_hour the hour
- * @param int $pn_minute the minute
- * @param mixed $pm_second the second as integer or float
- * @param bool $pb_repeatedhourdefault whether to assume Summer time if a
- * repeated hour is specified
- * (defaults to false)
- *
- * @return void
- * @access public
- * @see Date::setDayMonthYear(), Date::setHourMinuteSecond()
- * @since Method available since Release 1.5.0
- */
- function setDateTime($pn_day,
- $pn_month,
- $pn_year,
- $pn_hour,
- $pn_minute,
- $pm_second,
- $pb_repeatedhourdefault = false)
- {
- if (!Date_Calc::isValidDate($d, $m, $y)) {
- return PEAR::raiseError("'" .
- Date_Calc::dateFormat($d,
- $m,
- $y,
- "%Y-%m-%d") .
- "' is invalid calendar date",
- DATE_ERROR_INVALIDDATE);
- } else {
- // Split second into integer and part-second:
- //
- if (is_float($pm_second)) {
- $hn_second = intval($pm_second);
- $hn_partsecond = $pm_second - $hn_second;
- } else {
- $hn_second = (int) $pm_second;
- $hn_partsecond = 0.0;
- }
-
- $this->setLocalTime($d,
- $m,
- $y,
- $h,
- $m,
- $hn_second,
- $hn_partsecond,
- $pb_repeatedhourdefault);
- }
- }
-
-
- // }}}
-
-}
-
-// }}}
-
-/*
- * Local variables:
- * mode: php
- * tab-width: 4
- * c-basic-offset: 4
- * c-hanging-comment-ender-p: nil
- * End:
- */
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */
-
-// {{{ Header
-
-/**
- * Calculates, manipulates and retrieves dates
- *
- * It does not rely on 32-bit system time stamps, so it works dates
- * before 1970 and after 2038.
- *
- * PHP versions 4 and 5
- *
- * LICENSE:
- *
- * Copyright (c) 1999-2007 Monte Ohrt, Pierre-Alain Joye, Daniel Convissor,
- * C.A. Woodcock
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted under the terms of the BSD License.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
- * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
- * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- *
- * @category Date and Time
- * @package Date
- * @author Monte Ohrt <monte@ispi.net>
- * @author Pierre-Alain Joye <pajoye@php.net>
- * @author Daniel Convissor <danielc@php.net>
- * @author C.A. Woodcock <c01234@netcomuk.co.uk>
- * @copyright 1999-2007 Monte Ohrt, Pierre-Alain Joye, Daniel Convissor, C.A. Woodcock
- * @license http://www.opensource.org/licenses/bsd-license.php
- * BSD License
- * @version CVS: $Id: Calc.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- * @link http://pear.php.net/package/Date
- * @since File available since Release 1.2
- */
-
-
-// }}}
-// {{{ General constants:
-
-if (!defined('DATE_CALC_BEGIN_WEEKDAY')) {
- /**
- * Defines what day starts the week
- *
- * Monday (1) is the international standard.
- * Redefine this to 0 if you want weeks to begin on Sunday.
- */
- define('DATE_CALC_BEGIN_WEEKDAY', 1);
-}
-
-if (!defined('DATE_CALC_FORMAT')) {
- /**
- * The default value for each method's $format parameter
- *
- * The default is '%Y%m%d'. To override this default, define
- * this constant before including Calc.php.
- *
- * @since Constant available since Release 1.4.4
- */
- define('DATE_CALC_FORMAT', '%Y%m%d');
-}
-
-
-// {{{ Date precision constants (used in 'round()' and 'trunc()'):
-
-define('DATE_PRECISION_YEAR', -2);
-define('DATE_PRECISION_MONTH', -1);
-define('DATE_PRECISION_DAY', 0);
-define('DATE_PRECISION_HOUR', 1);
-define('DATE_PRECISION_10MINUTES', 2);
-define('DATE_PRECISION_MINUTE', 3);
-define('DATE_PRECISION_10SECONDS', 4);
-define('DATE_PRECISION_SECOND', 5);
-
-
-// }}}
-// {{{ Class: Date_Calc
-
-/**
- * Calculates, manipulates and retrieves dates
- *
- * It does not rely on 32-bit system time stamps, so it works dates
- * before 1970 and after 2038.
- *
- * @category Date and Time
- * @package Date
- * @author Monte Ohrt <monte@ispi.net>
- * @author Daniel Convissor <danielc@php.net>
- * @author C.A. Woodcock <c01234@netcomuk.co.uk>
- * @copyright 1999-2007 Monte Ohrt, Pierre-Alain Joye, Daniel Convissor, C.A. Woodcock
- * @license http://www.opensource.org/licenses/bsd-license.php
- * BSD License
- * @version Release: 1.5.0a1
- * @link http://pear.php.net/package/Date
- * @since Class available since Release 1.2
- */
-class Date_Calc
-{
-
- // {{{ dateFormat()
-
- /**
- * Formats the date in the given format, much like strfmt()
- *
- * This function is used to alleviate the problem with 32-bit numbers for
- * dates pre 1970 or post 2038, as strfmt() has on most systems.
- * Most of the formatting options are compatible.
- *
- * Formatting options:
- * <pre>
- * %a abbreviated weekday name (Sun, Mon, Tue)
- * %A full weekday name (Sunday, Monday, Tuesday)
- * %b abbreviated month name (Jan, Feb, Mar)
- * %B full month name (January, February, March)
- * %d day of month (range 00 to 31)
- * %e day of month, single digit (range 0 to 31)
- * %E number of days since unspecified epoch (integer)
- * (%E is useful for passing a date in a URL as
- * an integer value. Then simply use
- * daysToDate() to convert back to a date.)
- * %j day of year (range 001 to 366)
- * %m month as decimal number (range 1 to 12)
- * %n newline character (\n)
- * %t tab character (\t)
- * %w weekday as decimal (0 = Sunday)
- * %U week number of current year, first sunday as first week
- * %y year as decimal (range 00 to 99)
- * %Y year as decimal including century (range 0000 to 9999)
- * %% literal '%'
- * </pre>
- *
- * @param int $day the day of the month
- * @param int $month the month
- * @param int $year the year. Use the complete year instead of the
- * abbreviated version. E.g. use 2005, not 05.
- * @param string $format the format string
- *
- * @return string the date in the desired format
- * @access public
- * @static
- */
- function dateFormat($day, $month, $year, $format)
- {
- if (!Date_Calc::isValidDate($day, $month, $year)) {
- $year = Date_Calc::dateNow('%Y');
- $month = Date_Calc::dateNow('%m');
- $day = Date_Calc::dateNow('%d');
- }
-
- $output = '';
-
- for ($strpos = 0; $strpos < strlen($format); $strpos++) {
- $char = substr($format, $strpos, 1);
- if ($char == '%') {
- $nextchar = substr($format, $strpos + 1, 1);
- switch($nextchar) {
- case 'a':
- $output .= Date_Calc::getWeekdayAbbrname($day, $month, $year);
- break;
- case 'A':
- $output .= Date_Calc::getWeekdayFullname($day, $month, $year);
- break;
- case 'b':
- $output .= Date_Calc::getMonthAbbrname($month);
- break;
- case 'B':
- $output .= Date_Calc::getMonthFullname($month);
- break;
- case 'd':
- $output .= sprintf('%02d', $day);
- break;
- case 'e':
- $output .= $day;
- break;
- case 'E':
- $output .= Date_Calc::dateToDays($day, $month, $year);
- break;
- case 'j':
- $output .= Date_Calc::dayOfYear($day, $month, $year);
- break;
- case 'm':
- $output .= sprintf('%02d', $month);
- break;
- case 'n':
- $output .= "\n";
- break;
- case 't':
- $output .= "\t";
- break;
- case 'w':
- $output .= Date_Calc::dayOfWeek($day, $month, $year);
- break;
- case 'U':
- $output .= Date_Calc::weekOfYear($day, $month, $year);
- break;
- case 'y':
- $output .= sprintf('%0' .
- ($year < 0 ? '3' : '2') .
- 'd',
- $year % 100);
- break;
- case "Y":
- $output .= sprintf('%0' .
- ($year < 0 ? '5' : '4') .
- 'd',
- $year);
- break;
- case '%':
- $output .= '%';
- break;
- default:
- $output .= $char.$nextchar;
- }
- $strpos++;
- } else {
- $output .= $char;
- }
- }
- return $output;
- }
-
-
- // }}}
- // {{{ dateNow()
-
- /**
- * Returns the current local date
- *
- * NOTE: This function retrieves the local date using strftime(),
- * which may or may not be 32-bit safe on your system.
- *
- * @param string $format the string indicating how to format the output
- *
- * @return string the current date in the specified format
- * @access public
- * @static
- */
- function dateNow($format = DATE_CALC_FORMAT)
- {
- return strftime($format, time());
- }
-
-
- // }}}
- // {{{ getYear()
-
- /**
- * Returns the current local year in format CCYY
- *
- * @return string the current year in four digit format
- * @access public
- * @static
- */
- function getYear()
- {
- return Date_Calc::dateNow('%Y');
- }
-
-
- // }}}
- // {{{ getMonth()
-
- /**
- * Returns the current local month in format MM
- *
- * @return string the current month in two digit format
- * @access public
- * @static
- */
- function getMonth()
- {
- return Date_Calc::dateNow('%m');
- }
-
-
- // }}}
- // {{{ getDay()
-
- /**
- * Returns the current local day in format DD
- *
- * @return string the current day of the month in two digit format
- * @access public
- * @static
- */
- function getDay()
- {
- return Date_Calc::dateNow('%d');
- }
-
-
- // }}}
- // {{{ defaultCentury()
-
- /**
- * Turns a two digit year into a four digit year
- *
- * Return value depends on current year; the century chosen
- * will be the one which forms the year that is closest
- * to the current year. If the two possibilities are
- * equidistant to the current year (i.e. 50 years in the past
- * and 50 years in the future), then the past year is chosen.
- *
- * For example, if the current year is 2007:
- * 03 - returns 2003
- * 09 - returns 2009
- * 56 - returns 2056 (closer to 2007 than 1956)
- * 57 - returns 1957 (1957 and 2007 are equidistant, so previous century
- * chosen)
- * 58 - returns 1958
- *
- * @param int $year the 2 digit year
- *
- * @return int the 4 digit year
- * @access public
- * @static
- */
- function defaultCentury($year)
- {
- $hn_century = intval(($hn_currentyear = date("Y")) / 100);
- $hn_currentyear = $hn_currentyear % 100;
-
- if ($year < 0 || $year >= 100)
- $year = $year % 100;
-
- if ($year - $hn_currentyear < -50)
- return ($hn_century + 1) * 100 + $year;
- else if ($year - $hn_currentyear < 50)
- return $hn_century * 100 + $year;
- else
- return ($hn_century - 1) * 100 + $year;
- }
-
-
- // }}}
- // {{{ getSecondsInYear()
-
- /**
- * Returns the total number of seconds in the given year
- *
- * This takes into account leap seconds.
- *
- * @param int $pn_year the year in four digit format
- *
- * @return int
- * @access public
- * @static
- * @since Method available since Release 1.5.0
- */
- function getSecondsInYear($pn_year)
- {
- $pn_year = intval($pn_year);
-
- static $ha_leapseconds;
- if (!isset($ha_leapseconds)) {
- $ha_leapseconds = array(1972 => 2,
- 1973 => 1,
- 1974 => 1,
- 1975 => 1,
- 1976 => 1,
- 1977 => 1,
- 1978 => 1,
- 1979 => 1,
- 1981 => 1,
- 1982 => 1,
- 1983 => 1,
- 1985 => 1,
- 1987 => 1,
- 1989 => 1,
- 1990 => 1,
- 1992 => 1,
- 1993 => 1,
- 1994 => 1,
- 1995 => 1,
- 1997 => 1,
- 1998 => 1,
- 2005 => 1);
- }
-
- $ret = Date_Calc::daysInYear($pn_year) * 86400;
-
- if (isset($ha_leapseconds[$pn_year])) {
- return $ret + $ha_leapseconds[$pn_year];
- } else {
- return $ret;
- }
- }
-
-
- // }}}
- // {{{ getSecondsInMonth()
-
- /**
- * Returns the total number of seconds in the given month
- *
- * This takes into account leap seconds.
- *
- * @param int $pn_month the month
- * @param int $pn_year the year in four digit format
- *
- * @return int
- * @access public
- * @static
- * @since Method available since Release 1.5.0
- */
- function getSecondsInMonth($pn_month, $pn_year)
- {
- $pn_month = intval($pn_month);
- $pn_year = intval($pn_year);
-
- static $ha_leapseconds;
- if (!isset($ha_leapseconds)) {
- $ha_leapseconds = array(1972 => array(6 => 1,
- 12 => 1),
- 1973 => array(12 => 1),
- 1974 => array(12 => 1),
- 1975 => array(12 => 1),
- 1976 => array(12 => 1),
- 1977 => array(12 => 1),
- 1978 => array(12 => 1),
- 1979 => array(12 => 1),
- 1981 => array(6 => 1),
- 1982 => array(6 => 1),
- 1983 => array(6 => 1),
- 1985 => array(6 => 1),
- 1987 => array(12 => 1),
- 1989 => array(12 => 1),
- 1990 => array(12 => 1),
- 1992 => array(6 => 1),
- 1993 => array(6 => 1),
- 1994 => array(6 => 1),
- 1995 => array(12 => 1),
- 1997 => array(6 => 1),
- 1998 => array(12 => 1),
- 2005 => array(12 => 1));
- }
-
- $ret = Date_Calc::daysInMonth($pn_month, $pn_year) * 86400;
-
- if (isset($ha_leapseconds[$pn_year][$pn_month])) {
- return $ret + $ha_leapseconds[$pn_year][$pn_month];
- } else {
- return $ret;
- }
- }
-
-
- // }}}
- // {{{ getSecondsInDay()
-
- /**
- * Returns the total number of seconds in the day of the given date
- *
- * This takes into account leap seconds.
- *
- * @param int $pn_day the day of the month
- * @param int $pn_month the month
- * @param int $pn_year the year in four digit format
- *
- * @return int
- * @access public
- * @static
- * @since Method available since Release 1.5.0
- */
- function getSecondsInDay($pn_day, $pn_month, $pn_year)
- {
- // Note to developers:
- //
- // The leap seconds listed here are a matter of historical fact,
- // that is, it is known on which exact day they occurred.
- // However, the implementation of the class as a whole depends
- // on the fact that they always occur at the end of the month
- // (although it is assumed that they could occur in any month,
- // even though practically they only occur in June or December).
- //
- // Do not define a leap second on a day of the month other than
- // the last day without altering the implementation of the
- // functions that depend on this one.
- //
- // It is possible, though, to define an un-leap second (i.e. a skipped
- // second (I do not know what they are called), or a number of
- // consecutive leap seconds).
-
- $pn_day = intval($pn_day);
- $pn_month = intval($pn_month);
- $pn_year = intval($pn_year);
-
- static $ha_leapseconds;
- if (!isset($ha_leapseconds)) {
- $ha_leapseconds = array(1972 => array(6 => array(30 => 1),
- 12 => array(31 => 1)),
- 1973 => array(12 => array(31 => 1)),
- 1974 => array(12 => array(31 => 1)),
- 1975 => array(12 => array(31 => 1)),
- 1976 => array(12 => array(31 => 1)),
- 1977 => array(12 => array(31 => 1)),
- 1978 => array(12 => array(31 => 1)),
- 1979 => array(12 => array(31 => 1)),
- 1981 => array(6 => array(30 => 1)),
- 1982 => array(6 => array(30 => 1)),
- 1983 => array(6 => array(30 => 1)),
- 1985 => array(6 => array(30 => 1)),
- 1987 => array(12 => array(31 => 1)),
- 1989 => array(12 => array(31 => 1)),
- 1990 => array(12 => array(31 => 1)),
- 1992 => array(6 => array(30 => 1)),
- 1993 => array(6 => array(30 => 1)),
- 1994 => array(6 => array(30 => 1)),
- 1995 => array(12 => array(31 => 1)),
- 1997 => array(6 => array(30 => 1)),
- 1998 => array(12 => array(31 => 1)),
- 2005 => array(12 => array(31 => 1)));
- }
-
- if (isset($ha_leapseconds[$pn_year][$pn_month][$pn_day])) {
- return 86400 + $ha_leapseconds[$pn_year][$pn_month][$pn_day];
- } else {
- return 86400;
- }
- }
-
-
- // }}}
- // {{{ getSecondsInHour()
-
- /**
- * Returns the total number of seconds in the hour of the given date
- *
- * This takes into account leap seconds.
- *
- * @param int $pn_day the day of the month
- * @param int $pn_month the month
- * @param int $pn_year the year in four digit format
- * @param int $pn_hour the hour
- *
- * @return int
- * @access public
- * @static
- */
- function getSecondsInHour($pn_day, $pn_month, $pn_year, $pn_hour)
- {
- if ($pn_hour < 23)
- return 3600;
- else
- return Date_Calc::getSecondsInDay($pn_day, $pn_month, $pn_year) -
- 82800;
- }
-
-
- // }}}
- // {{{ getSecondsInMinute()
-
- /**
- * Returns the total number of seconds in the minute of the given hour
- *
- * This takes into account leap seconds.
- *
- * @param int $pn_day the day of the month
- * @param int $pn_month the month
- * @param int $pn_year the year in four digit format
- * @param int $pn_hour the hour
- * @param int $pn_minute the minute
- *
- * @return int
- * @access public
- * @static
- * @since Method available since Release 1.5.0
- */
- function getSecondsInMinute($pn_day,
- $pn_month,
- $pn_year,
- $pn_hour,
- $pn_minute)
- {
- if ($pn_hour < 23 || $pn_minute < 59)
- return 60;
- else
- return Date_Calc::getSecondsInDay($pn_day, $pn_month, $pn_year) -
- 86340;
- }
-
-
- // }}}
- // {{{ secondsPastMidnight()
-
- /**
- * Returns the no of seconds since midnight (0-86399)
- *
- * @param int $pn_hour the hour of the day
- * @param int $pn_minute the minute
- * @param mixed $pn_second the second as integer or float
- *
- * @return mixed integer or float from 0-86399
- * @access public
- * @static
- * @since Method available since Release 1.5.0
- */
- function secondsPastMidnight($pn_hour, $pn_minute, $pn_second)
- {
- return 3600 * $pn_hour + 60 * $pn_minute + $pn_second;
- }
-
-
- // }}}
- // {{{ secondsPastMidnightToTime()
-
- /**
- * Returns the time as an array (i.e. hour, minute, second)
- *
- * @param mixed $pn_seconds the no of seconds since midnight (0-86399)
- *
- * @return mixed array of hour, minute (both as integers), second (as
- * integer or float, depending on parameter)
- * @access public
- * @static
- * @since Method available since Release 1.5.0
- */
- function secondsPastMidnightToTime($pn_seconds)
- {
- if ($pn_seconds >= 86400) {
- return array(23, 59, $pn_seconds - 86340);
- }
-
- $hn_hour = intval($pn_seconds / 3600);
- $hn_minute = intval(($pn_seconds - $hn_hour * 3600) / 60);
- $hn_second = is_float($pn_seconds) ?
- fmod($pn_seconds, 60) :
- $pn_seconds % 60;
-
- return array($hn_hour, $hn_minute, $hn_second);
- }
-
-
- // }}}
- // {{{ secondsPastTheHour()
-
- /**
- * Returns the no of seconds since the last hour o'clock (0-3599)
- *
- * @param int $pn_minute the minute
- * @param mixed $pn_second the second as integer or float
- *
- * @return mixed integer or float from 0-3599
- * @access public
- * @static
- * @since Method available since Release 1.5.0
- */
- function secondsPastTheHour($pn_minute, $pn_second)
- {
- return 60 * $pn_minute + $pn_second;
- }
-
-
- // }}}
- // {{{ addHours()
-
- /**
- * Returns the date the specified no of hours from the given date
- *
- * To subtract hours use a negative value for the '$pn_hours' parameter
- *
- * @param int $pn_hours hours to add
- * @param int $pn_day the day of the month
- * @param int $pn_month the month
- * @param int $pn_year the year
- * @param int $pn_hour the hour
- *
- * @return array array of year, month, day, hour
- * @access public
- * @static
- * @since Method available since Release 1.5.0
- */
- function addHours($pn_hours, $pn_day, $pn_month, $pn_year, $pn_hour)
- {
- if ($pn_hours == 0)
- return array((int) $pn_year,
- (int) $pn_month,
- (int) $pn_day,
- (int) $pn_hour);
-
- $hn_days = intval($pn_hours / 24);
- $hn_hour = $pn_hour + $pn_hours % 24;
-
- if ($hn_hour >= 24) {
- ++$hn_days;
- $hn_hour -= 24;
- } else if ($hn_hour < 0) {
- --$hn_days;
- $hn_hour += 24;
- }
-
- if ($hn_days == 0) {
- $hn_year = $pn_year;
- $hn_month = $pn_month;
- $hn_day = $pn_day;
- } else {
- list($hn_year, $hn_month, $hn_day) =
- explode(" ",
- Date_Calc::addDays($hn_days,
- $pn_day,
- $pn_month,
- $pn_year,
- "%Y %m %d"));
- }
-
- return array((int) $hn_year, (int) $hn_month, (int) $hn_day, $hn_hour);
- }
-
-
- // }}}
- // {{{ addMinutes()
-
- /**
- * Returns the date the specified no of minutes from the given date
- *
- * To subtract minutes use a negative value for the '$pn_minutes' parameter
- *
- * @param int $pn_minutes minutes to add
- * @param int $pn_day the day of the month
- * @param int $pn_month the month
- * @param int $pn_year the year
- * @param int $pn_hour the hour
- * @param int $pn_minute the minute
- *
- * @return array array of year, month, day, hour, minute
- * @access public
- * @static
- * @since Method available since Release 1.5.0
- */
- function addMinutes($pn_minutes,
- $pn_day,
- $pn_month,
- $pn_year,
- $pn_hour,
- $pn_minute)
- {
- if ($pn_minutes == 0)
- return array((int) $pn_year,
- (int) $pn_month,
- (int) $pn_day,
- (int) $pn_hour,
- (int) $pn_minute);
-
- $hn_hours = intval($pn_minutes / 60);
- $hn_minute = $pn_minute + $pn_minutes % 60;
-
- if ($hn_minute >= 60) {
- ++$hn_hours;
- $hn_minute -= 60;
- } else if ($hn_minute < 0) {
- --$hn_hours;
- $hn_minute += 60;
- }
-
- if ($hn_hours == 0) {
- $hn_year = $pn_year;
- $hn_month = $pn_month;
- $hn_day = $pn_day;
- $hn_hour = $pn_hour;
- } else {
- list($hn_year, $hn_month, $hn_day, $hn_hour) =
- Date_Calc::addHours($hn_hours,
- $pn_day,
- $pn_month,
- $pn_year,
- $pn_hour);
- }
-
- return array($hn_year, $hn_month, $hn_day, $hn_hour, $hn_minute);
- }
-
-
- // }}}
- // {{{ addSeconds()
-
- /**
- * Returns the date the specified no of seconds from the given date
- *
- * If leap seconds are specified to be counted, the passed time must be UTC.
- * To subtract seconds use a negative value for the '$pn_seconds' parameter.
- *
- * N.B. the return type of the second part of the date is float if
- * either '$pn_seconds' or '$pn_second' is a float; otherwise, it
- * is integer.
- *
- * @param mixed $pn_seconds seconds to add as integer or float
- * @param int $pn_day the day of the month
- * @param int $pn_month the month
- * @param int $pn_year the year
- * @param int $pn_hour the hour
- * @param int $pn_minute the minute
- * @param mixed $pn_second the second as integer or float
- * @param bool $pb_countleap whether to count leap seconds (defaults to
- * DATE_COUNT_LEAP_SECONDS)
- *
- * @return array array of year, month, day, hour, minute, second
- * @access public
- * @static
- * @since Method available since Release 1.5.0
- */
- function addSeconds($pn_seconds,
- $pn_day,
- $pn_month,
- $pn_year,
- $pn_hour,
- $pn_minute,
- $pn_second,
- $pb_countleap = DATE_COUNT_LEAP_SECONDS)
- {
- if ($pn_seconds == 0)
- return array((int) $pn_year,
- (int) $pn_month,
- (int) $pn_day,
- (int) $pn_hour,
- (int) $pn_minute,
- $pn_second);
-
- if ($pb_countleap) {
- $hn_seconds = $pn_seconds;
-
- $hn_day = (int) $pn_day;
- $hn_month = (int) $pn_month;
- $hn_year = (int) $pn_year;
- $hn_hour = (int) $pn_hour;
- $hn_minute = (int) $pn_minute;
- $hn_second = $pn_second;
-
- $hn_days = Date_Calc::dateToDays($pn_day,
- $pn_month,
- $pn_year);
- $hn_secondsofmonth = 86400 * ($hn_days -
- Date_Calc::firstDayOfMonth($pn_month,
- $pn_year)) +
- Date_Calc::secondsPastMidnight($pn_hour,
- $pn_minute,
- $pn_second);
-
- if ($hn_seconds > 0) {
- // Advance to end of month:
- //
- if ($hn_secondsofmonth != 0 &&
- $hn_secondsofmonth + $hn_seconds >=
- ($hn_secondsinmonth =
- Date_Calc::getSecondsInMonth($hn_month, $hn_year))) {
-
- $hn_seconds -= $hn_secondsinmonth - $hn_secondsofmonth;
- $hn_secondsofmonth = 0;
- list($hn_year, $hn_month) =
- Date_Calc::nextMonth($hn_month, $hn_year);
- $hn_day = Date_Calc::getFirstDayOfMonth($hn_month,
- $hn_year);
- $hn_hour = $hn_minute = $hn_second = 0;
- }
-
- // Advance to end of year:
- //
- if ($hn_secondsofmonth == 0 &&
- $hn_month != Date_Calc::getFirstMonthOfYear($hn_year)) {
-
- while ($hn_year == $pn_year &&
- $hn_seconds >= ($hn_secondsinmonth =
- Date_Calc::getSecondsInMonth($hn_month,
- $hn_year))) {
- $hn_seconds -= $hn_secondsinmonth;
- list($hn_year, $hn_month) =
- Date_Calc::nextMonth($hn_month, $hn_year);
- $hn_day = Date_Calc::getFirstDayOfMonth($hn_month,
- $hn_year);
- }
- }
-
- if ($hn_secondsofmonth == 0) {
- // Add years:
- //
- if ($hn_month == Date_Calc::getFirstMonthOfYear($hn_year)) {
- while ($hn_seconds >= ($hn_secondsinyear =
- Date_Calc::getSecondsInYear($hn_year))) {
- $hn_seconds -= $hn_secondsinyear;
- $hn_month = Date_Calc::getFirstMonthOfYear(++$hn_year);
- $hn_day = Date_Calc::getFirstDayOfMonth($hn_month,
- $hn_year);
- }
- }
-
- // Add months:
- //
- while ($hn_seconds >= ($hn_secondsinmonth =
- Date_Calc::getSecondsInMonth($hn_month, $hn_year))) {
- $hn_seconds -= $hn_secondsinmonth;
- list($hn_year, $hn_month) =
- Date_Calc::nextMonth($hn_month, $hn_year);
- $hn_day = Date_Calc::getFirstDayOfMonth($hn_month, $hn_year);
- }
- }
- } else {
- //
- // (if $hn_seconds < 0)
-
- // Go back to start of month:
- //
- if ($hn_secondsofmonth != 0 &&
- -$hn_seconds >= $hn_secondsofmonth) {
-
- $hn_seconds += $hn_secondsofmonth;
- $hn_secondsofmonth = 0;
- $hn_day = Date_Calc::getFirstDayOfMonth($hn_month,
- $hn_year);
- $hn_hour = $hn_minute = $hn_second = 0;
- }
-
- // Go back to start of year:
- //
- if ($hn_secondsofmonth == 0) {
- while ($hn_month !=
- Date_Calc::getFirstMonthOfYear($hn_year)) {
-
- list($hn_year, $hn_prevmonth) =
- Date_Calc::prevMonth($hn_month, $hn_year);
-
- if (-$hn_seconds >= ($hn_secondsinmonth =
- Date_Calc::getSecondsInMonth($hn_prevmonth,
- $hn_year))) {
- $hn_seconds += $hn_secondsinmonth;
- $hn_month = $hn_prevmonth;
- $hn_day = Date_Calc::getFirstDayOfMonth($hn_month,
- $hn_year);
- } else {
- break;
- }
- }
- }
-
- if ($hn_secondsofmonth == 0) {
- // Subtract years:
- //
- if ($hn_month == Date_Calc::getFirstMonthOfYear($hn_year)) {
- while (-$hn_seconds >= ($hn_secondsinyear =
- Date_Calc::getSecondsInYear($hn_year - 1))) {
- $hn_seconds += $hn_secondsinyear;
- $hn_month = Date_Calc::getFirstMonthOfYear(--$hn_year);
- $hn_day = Date_Calc::getFirstDayOfMonth($hn_month,
- $hn_year);
- }
- }
-
- // Subtract months:
- //
- list($hn_pmyear, $hn_prevmonth) =
- Date_Calc::prevMonth($hn_month, $hn_year);
- while (-$hn_seconds >= ($hn_secondsinmonth =
- Date_Calc::getSecondsInMonth($hn_prevmonth,
- $hn_pmyear))) {
- $hn_seconds += $hn_secondsinmonth;
- $hn_year = $hn_pmyear;
- $hn_month = $hn_prevmonth;
- $hn_day = Date_Calc::getFirstDayOfMonth($hn_month,
- $hn_year);
- list($hn_pmyear, $hn_prevmonth) =
- Date_Calc::prevMonth($hn_month, $hn_year);
- }
- }
- }
-
- if ($hn_seconds < 0 && $hn_secondsofmonth == 0) {
- list($hn_year, $hn_month) =
- Date_Calc::prevMonth($hn_month, $hn_year);
- $hn_day = Date_Calc::getFirstDayOfMonth($hn_month, $hn_year);
- $hn_seconds += Date_Calc::getSecondsInMonth($hn_month, $hn_year);
- }
-
- $hn_seconds += Date_Calc::secondsPastMidnight($hn_hour,
- $hn_minute,
- $hn_second);
- if ($hn_seconds < 0) {
- $hn_daysadd = intval($hn_seconds / 86400) - 1;
- } else if ($hn_seconds < 86400) {
- $hn_daysadd = 0;
- } else {
- $hn_daysadd = intval($hn_seconds / 86400) - 1;
- }
-
- if ($hn_daysadd != 0) {
- list($hn_year, $hn_month, $hn_day) =
- explode(" ",
- Date_Calc::addDays($hn_daysadd,
- $hn_day,
- $hn_month,
- $hn_year,
- "%Y %m %d"));
- $hn_seconds -= $hn_daysadd * 86400;
- }
-
- $hn_secondsinday = Date_Calc::getSecondsInDay($hn_day,
- $hn_month,
- $hn_year);
- if ($hn_seconds >= $hn_secondsinday) {
- list($hn_year, $hn_month, $hn_day) =
- explode(" ",
- Date_Calc::addDays(1,
- $hn_day,
- $hn_month,
- $hn_year,
- "%Y %m %d"));
- $hn_seconds -= $hn_secondsinday;
- }
-
- list($hn_hour, $hn_minute, $hn_second) =
- Date_Calc::secondsPastMidnightToTime($hn_seconds);
-
- return array((int) $hn_year,
- (int) $hn_month,
- (int) $hn_day,
- $hn_hour,
- $hn_minute,
- $hn_second);
- } else {
- // Assume every day has 86400 seconds exactly (ignore leap seconds):
- //
- $hn_minutes = intval($pn_seconds / 60);
-
- if (is_float($pn_seconds)) {
- $hn_second = $pn_second + fmod($pn_seconds, 60);
- } else {
- $hn_second = $pn_second + $pn_seconds % 60;
- }
-
- if ($hn_second >= 60) {
- ++$hn_minutes;
- $hn_second -= 60;
- } else if ($hn_second < 0) {
- --$hn_minutes;
- $hn_second += 60;
- }
-
- if ($hn_minutes == 0) {
- $hn_year = $pn_year;
- $hn_month = $pn_month;
- $hn_day = $pn_day;
- $hn_hour = $pn_hour;
- $hn_minute = $pn_minute;
- } else {
- list($hn_year, $hn_month, $hn_day, $hn_hour, $hn_minute) =
- Date_Calc::addMinutes($hn_minutes,
- $pn_day,
- $pn_month,
- $pn_year,
- $pn_hour,
- $pn_minute);
- }
-
- return array($hn_year,
- $hn_month,
- $hn_day,
- $hn_hour,
- $hn_minute,
- $hn_second);
- }
- }
-
-
- // }}}
- // {{{ dateToDays()
-
- /**
- * Converts a date in the proleptic Gregorian calendar to the no of days
- * since 24th November, 4714 B.C.
- *
- * Returns the no of days since Monday, 24th November, 4714 B.C. in the
- * proleptic Gregorian calendar (which is 24th November, -4713 using
- * 'Astronomical' year numbering, and 1st January, 4713 B.C. in the
- * proleptic Julian calendar). This is also the first day of the 'Julian
- * Period' proposed by Joseph Scaliger in 1583, and the number of days
- * since this date is known as the 'Julian Day'. (It is not directly
- * to do with the Julian calendar, although this is where the name
- * is derived from.)
- *
- * The algorithm is valid for all years (positive and negative), and
- * also for years preceding 4714 B.C.
- *
- * @param int $day the day of the month
- * @param int $month the month
- * @param int $year the year (using 'Astronomical' year numbering)
- *
- * @return int the number of days since 24th November, 4714 B.C.
- * @access public
- * @static
- */
- function dateToDays($day, $month, $year)
- {
- if ($month > 2) {
- // March = 0, April = 1, ..., December = 9,
- // January = 10, February = 11
- $month -= 3;
- } else {
- $month += 9;
- --$year;
- }
-
- $hb_negativeyear = $year < 0;
- $century = intval($year / 100);
- $year = $year % 100;
-
- if ($hb_negativeyear) {
- // Subtract 1 because year 0 is a leap year;
- // And N.B. that we must treat the leap years as occurring
- // one year earlier than they do, because for the purposes
- // of calculation, the year starts on 1st March:
- //
- return intval((14609700 * $century + ($year == 0 ? 1 : 0)) / 400) +
- intval((1461 * $year + 1) / 4) +
- intval((153 * $month + 2) / 5) +
- $day + 1721118;
- } else {
- return intval(146097 * $century / 4) +
- intval(1461 * $year / 4) +
- intval((153 * $month + 2) / 5) +
- $day + 1721119;
- }
- }
-
-
- // }}}
- // {{{ daysToDate()
-
- /**
- * Converts no of days since 24th November, 4714 B.C. (in the proleptic
- * Gregorian calendar, which is year -4713 using 'Astronomical' year
- * numbering) to Gregorian calendar date
- *
- * Returned date belongs to the proleptic Gregorian calendar, using
- * 'Astronomical' year numbering.
- *
- * The algorithm is valid for all years (positive and negative), and
- * also for years preceding 4714 B.C. (i.e. for negative 'Julian Days'),
- * and so the only limitation is platform-dependent (for 32-bit systems
- * the maximum year would be something like about 1,465,190 A.D.).
- *
- * N.B. Monday, 24th November, 4714 B.C. is Julian Day '0'.
- *
- * @param int $days the number of days since 24th November, 4714 B.C.
- * @param string $format the string indicating how to format the output
- *
- * @return string the date in the desired format
- * @access public
- * @static
- */
- function daysToDate($days, $format = DATE_CALC_FORMAT)
- {
- $days = intval($days);
-
- $days -= 1721119;
- $century = floor((4 * $days - 1) / 146097);
- $days = floor(4 * $days - 1 - 146097 * $century);
- $day = floor($days / 4);
-
- $year = floor((4 * $day + 3) / 1461);
- $day = floor(4 * $day + 3 - 1461 * $year);
- $day = floor(($day + 4) / 4);
-
- $month = floor((5 * $day - 3) / 153);
- $day = floor(5 * $day - 3 - 153 * $month);
- $day = floor(($day + 5) / 5);
-
- $year = $century * 100 + $year;
- if ($month < 10) {
- $month +=3;
- } else {
- $month -=9;
- ++$year;
- }
-
- return Date_Calc::dateFormat($day, $month, $year, $format);
- }
-
-
- // }}}
- // {{{ getMonths()
-
- /**
- * Returns array of the month numbers, in order, for the given year
- *
- * @param int $pn_year the year (using 'Astronomical' year numbering)
- *
- * @return array array of integer month numbers, in order
- * @access public
- * @static
- * @since Method available since Release 1.5.0
- */
- function getMonths($pn_year)
- {
- // N.B. Month numbers can be skipped but not duplicated:
- //
- return array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);
- }
-
-
- // }}}
- // {{{ getMonthNames()
-
- /**
- * Returns an array of month names
- *
- * Used to take advantage of the setlocale function to return
- * language specific month names.
- *
- * TODO: cache values to some global array to avoid performance
- * hits when called more than once.
- *
- * @param int $pb_abbreviated whether to return the abbreviated form of the
- * months
- *
- * @return array associative array of integer month numbers, in
- * order, to month names
- * @access public
- * @static
- */
- function getMonthNames($pb_abbreviated = false)
- {
- $ret = array();
- foreach (Date_Calc::getMonths(2001) as $i) {
- $ret[$i] = strftime($pb_abbreviated ? '%b' : '%B',
- mktime(0, 0, 0, $i, 1, 2001));
- }
- return $ret;
- }
-
-
- // }}}
- // {{{ prevMonth()
-
- /**
- * Returns month and year of previous month
- *
- * @param int $pn_month the month
- * @param int $pn_year the year (using 'Astronomical' year numbering)
- *
- * @return array array of year, month as integers
- * @access public
- * @static
- * @since Method available since Release 1.5.0
- */
- function prevMonth($pn_month, $pn_year)
- {
- $ha_months = Date_Calc::getMonths($pn_year);
- $hn_monthkey = array_search($pn_month, $ha_months);
- if (array_key_exists($hn_monthkey - 1, $ha_months)) {
- return array((int) $pn_year, $ha_months[$hn_monthkey - 1]);
- } else {
- $ha_months = Date_Calc::getMonths($pn_year - 1);
- return array($pn_year - 1, end($ha_months));
- }
- }
-
-
- // }}}
- // {{{ nextMonth()
-
- /**
- * Returns month and year of next month
- *
- * @param int $pn_month the month
- * @param int $pn_year the year (using 'Astronomical' year numbering)
- *
- * @return array array of year, month as integers
- * @access public
- * @static
- * @since Method available since Release 1.5.0
- */
- function nextMonth($pn_month, $pn_year)
- {
- $ha_months = Date_Calc::getMonths($pn_year);
- $hn_monthkey = array_search($pn_month, $ha_months);
- if (array_key_exists($hn_monthkey + 1, $ha_months)) {
- return array((int) $pn_year, $ha_months[$hn_monthkey + 1]);
- } else {
- $ha_months = Date_Calc::getMonths($pn_year + 1);
- return array($pn_year + 1, $ha_months[0]);
- }
- }
-
-
- // }}}
- // {{{ addMonthsToDays()
-
- /**
- * Returns 'Julian Day' of the date the specified no of months
- * from the given date
- *
- * To subtract months use a negative value for the '$pn_months'
- * parameter
- *
- * @param int $pn_months months to add
- * @param int $pn_days 'Julian Day', i.e. the no of days since 1st
- * January, 4713 B.C.
- *
- * @return int 'Julian Day', i.e. the no of days since 1st January,
- * 4713 B.C.
- * @access public
- * @static
- * @since Method available since Release 1.5.0
- */
- function addMonthsToDays($pn_months, $pn_days)
- {
- if ($pn_months == 0)
- return (int) $pn_days;
-
- list($hn_year, $hn_month, $hn_day) =
- explode(" ", Date_Calc::daysToDate($pn_days, "%Y %m %d"));
-
- $hn_retmonth = $hn_month + $pn_months % 12;
- $hn_retyear = $hn_year + intval($pn_months / 12);
- if ($hn_retmonth < 1) {
- $hn_retmonth += 12;
- --$hn_retyear;
- } else if ($hn_retmonth > 12) {
- $hn_retmonth -= 12;
- ++$hn_retyear;
- }
-
- if (Date_Calc::isValidDate($hn_day, $hn_retmonth, $hn_retyear))
- return Date_Calc::dateToDays($hn_day, $hn_retmonth, $hn_retyear);
-
- // Calculate days since first of month:
- //
- $hn_dayoffset = $pn_days -
- Date_Calc::firstDayOfMonth($hn_month, $hn_year);
-
- $hn_retmonthfirstday = Date_Calc::firstDayOfMonth($hn_retmonth,
- $hn_retyear);
- $hn_retmonthlastday = Date_Calc::lastDayOfMonth($hn_retmonth,
- $hn_retyear);
-
- if ($hn_dayoffset > $hn_retmonthlastday - $hn_retmonthfirstday) {
- return $hn_retmonthlastday;
- } else {
- return $hn_retmonthfirstday + $hn_dayoffset;
- }
- }
-
-
- // }}}
- // {{{ addMonths()
-
- /**
- * Returns the date the specified no of months from the given date
- *
- * To subtract months use a negative value for the '$pn_months'
- * parameter
- *
- * @param int $pn_months months to add
- * @param int $pn_day the day of the month, default is current local
- * day
- * @param int $pn_month the month, default is current local month
- * @param int $pn_year the year in four digit format, default is
- * current local year
- * @param string $ps_format string specifying how to format the output
- *
- * @return string the date in the desired format
- * @access public
- * @static
- * @since Method available since Release 1.5.0
- */
- function addMonths($pn_months,
- $pn_day,
- $pn_month,
- $pn_year,
- $ps_format = DATE_CALC_FORMAT)
- {
- if (is_null($pn_year)) {
- $pn_year = Date_Calc::dateNow('%Y');
- }
- if (empty($pn_month)) {
- $pn_month = Date_Calc::dateNow('%m');
- }
- if (empty($pn_day)) {
- $pn_day = Date_Calc::dateNow('%d');
- }
-
- if ($pn_months == 0)
- return Date_Calc::dateFormat($pn_day,
- $pn_month,
- $pn_year,
- $ps_format);
-
- $hn_days = Date_Calc::dateToDays($pn_day, $pn_month, $pn_year);
- return Date_Calc::daysToDate(Date_Calc::addMonthsToDays($pn_months,
- $hn_days),
- $ps_format);
- }
-
-
- // }}}
- // {{{ addYearsToDays()
-
- /**
- * Returns 'Julian Day' of the date the specified no of years
- * from the given date
- *
- * To subtract years use a negative value for the '$pn_years'
- * parameter
- *
- * @param int $pn_years years to add
- * @param int $pn_days 'Julian Day', i.e. the no of days since 1st January,
- * 4713 B.C.
- *
- * @return int 'Julian Day', i.e. the no of days since 1st January,
- * 4713 B.C.
- * @access public
- * @static
- * @since Method available since Release 1.5.0
- */
- function addYearsToDays($pn_years, $pn_days)
- {
- if ($pn_years == 0)
- return (int) $pn_days;
-
- list($hn_year, $hn_month, $hn_day) =
- explode(" ", Date_Calc::daysToDate($pn_days, "%Y %m %d"));
-
- $hn_retyear = $hn_year + $pn_years;
- if (Date_Calc::isValidDate($hn_day, $hn_month, $hn_retyear))
- return Date_Calc::dateToDays($hn_day, $hn_month, $hn_retyear);
-
- $ha_months = Date_Calc::getMonths($hn_retyear);
- if (in_array($hn_month, $ha_months)) {
- $hn_retmonth = $hn_month;
-
- // Calculate days since first of month:
- //
- $hn_dayoffset = $pn_days - Date_Calc::firstDayOfMonth($hn_month,
- $hn_year);
-
- $hn_retmonthfirstday = Date_Calc::firstDayOfMonth($hn_retmonth,
- $hn_retyear);
- $hn_retmonthlastday = Date_Calc::lastDayOfMonth($hn_retmonth,
- $hn_retyear);
-
- if ($hn_dayoffset > $hn_retmonthlastday - $hn_retmonthfirstday) {
- return $hn_retmonthlastday;
- } else {
- return $hn_retmonthfirstday + $hn_dayoffset;
- }
- } else {
- // Calculate days since first of year:
- //
- $hn_dayoffset = $pn_days - Date_Calc::firstDayOfYear($hn_year);
-
- $hn_retyearfirstday = Date_Calc::firstDayOfYear($hn_retyear);
- $hn_retyearlastday = Date_Calc::lastDayOfYear($hn_retyear);
-
- if ($hn_dayoffset > $hn_retyearlastday - $hn_retyearfirstday) {
- return $hn_retyearlastday;
- } else {
- return $hn_retyearfirstday + $hn_dayoffset;
- }
- }
- }
-
-
- // }}}
- // {{{ addYears()
-
- /**
- * Returns the date the specified no of years from the given date
- *
- * To subtract years use a negative value for the '$pn_years'
- * parameter
- *
- * @param int $pn_years years to add
- * @param int $pn_day the day of the month, default is current local
- * day
- * @param int $pn_month the month, default is current local month
- * @param int $pn_year the year in four digit format, default is
- * current local year
- * @param string $ps_format string specifying how to format the output
- *
- * @return string the date in the desired format
- * @access public
- * @static
- * @since Method available since Release 1.5.0
- */
- function addYears($pn_years,
- $pn_day,
- $pn_month,
- $pn_year,
- $ps_format = DATE_CALC_FORMAT)
- {
- if (is_null($pn_year)) {
- $pn_year = Date_Calc::dateNow('%Y');
- }
- if (empty($pn_month)) {
- $pn_month = Date_Calc::dateNow('%m');
- }
- if (empty($pn_day)) {
- $pn_day = Date_Calc::dateNow('%d');
- }
-
- if ($pn_years == 0)
- return Date_Calc::dateFormat($pn_day,
- $pn_month,
- $pn_year,
- $ps_format);
-
- $hn_days = Date_Calc::dateToDays($pn_day, $pn_month, $pn_year);
- return Date_Calc::daysToDate(Date_Calc::addYearsToDays($pn_years,
- $hn_days),
- $ps_format);
- }
-
-
- // }}}
- // {{{ addDays()
-
- /**
- * Returns the date the specified no of days from the given date
- *
- * To subtract days use a negative value for the '$pn_days' parameter
- *
- * @param int $pn_days days to add
- * @param int $pn_day the day of the month, default is current local
- * day
- * @param int $pn_month the month, default is current local month
- * @param int $pn_year the year in four digit format, default is
- * current local year
- * @param string $ps_format string specifying how to format the output
- *
- * @return string the date in the desired format
- * @access public
- * @static
- * @since Method available since Release 1.5.0
- */
- function addDays($pn_days,
- $pn_day,
- $pn_month,
- $pn_year,
- $ps_format = DATE_CALC_FORMAT)
- {
- if (is_null($pn_year)) {
- $pn_year = Date_Calc::dateNow('%Y');
- }
- if (empty($pn_month)) {
- $pn_month = Date_Calc::dateNow('%m');
- }
- if (empty($pn_day)) {
- $pn_day = Date_Calc::dateNow('%d');
- }
-
- if ($pn_days == 0)
- return Date_Calc::dateFormat($pn_day,
- $pn_month,
- $pn_year,
- $ps_format);
-
- return Date_Calc::daysToDate(Date_Calc::dateToDays($pn_day,
- $pn_month,
- $pn_year) +
- $pn_days,
- $ps_format);
- }
-
-
- // }}}
- // {{{ getFirstDayOfMonth()
-
- /**
- * Returns first day of the specified month of specified year as integer
- *
- * @param int $pn_month the month
- * @param int $pn_year the year (using 'Astronomical' year numbering)
- *
- * @return int number of first day of month
- * @access public
- * @static
- * @since Method available since Release 1.5.0
- */
- function getFirstDayOfMonth($pn_month, $pn_year)
- {
- return 1;
- }
-
-
- // }}}
- // {{{ getLastDayOfMonth()
-
- /**
- * Returns last day of the specified month of specified year as integer
- *
- * @param int $pn_month the month
- * @param int $pn_year the year (using 'Astronomical' year numbering)
- *
- * @return int number of last day of month
- * @access public
- * @static
- * @since Method available since Release 1.5.0
- */
- function getLastDayOfMonth($pn_month, $pn_year)
- {
- return Date_Calc::daysInMonth($pn_month, $pn_year);
- }
-
-
- // }}}
- // {{{ firstDayOfMonth()
-
- /**
- * Returns the Julian Day of the first day of the month of the specified
- * year (i.e. the no of days since 24th November, 4714 B.C.)
- *
- * @param int $pn_month the month
- * @param int $pn_year the year (using 'Astronomical' year numbering)
- *
- * @return integer the number of days since 24th November, 4714 B.C.
- * @access public
- * @static
- * @since Method available since Release 1.5.0
- */
- function firstDayOfMonth($pn_month, $pn_year)
- {
- return Date_Calc::dateToDays(Date_Calc::getFirstDayOfMonth($pn_month,
- $pn_year),
- $pn_month,
- $pn_year);
- }
-
-
- // }}}
- // {{{ lastDayOfMonth()
-
- /**
- * Returns the Julian Day of the last day of the month of the specified
- * year (i.e. the no of days since 24th November, 4714 B.C.)
- *
- * @param int $pn_month the month
- * @param int $pn_year the year (using 'Astronomical' year numbering)
- *
- * @return integer the number of days since 24th November, 4714 B.C.
- * @access public
- * @static
- * @since Method available since Release 1.5.0
- */
- function lastDayOfMonth($pn_month, $pn_year)
- {
- list($hn_nmyear, $hn_nextmonth) = Date_Calc::nextMonth($pn_month,
- $pn_year);
- return Date_Calc::firstDayOfMonth($hn_nextmonth, $hn_nmyear) - 1;
- }
-
-
- // }}}
- // {{{ getFirstMonthOfYear()
-
- /**
- * Returns first month of specified year as integer
- *
- * @param int $pn_year the year (using 'Astronomical' year numbering)
- *
- * @return int number of first month of year
- * @access public
- * @static
- * @since Method available since Release 1.5.0
- */
- function getFirstMonthOfYear($pn_year)
- {
- $ha_months = Date_Calc::getMonths($pn_year);
- return $ha_months[0];
- }
-
-
- // }}}
- // {{{ firstDayOfYear()
-
- /**
- * Returns the Julian Day of the first day of the year (i.e. the no of
- * days since 24th November, 4714 B.C.)
- *
- * @param int $pn_year the year (using 'Astronomical' year numbering)
- *
- * @return integer the number of days since 24th November, 4714 B.C.
- * @access public
- * @static
- * @since Method available since Release 1.5.0
- */
- function firstDayOfYear($pn_year)
- {
- return Date_Calc::firstDayOfMonth(Date_Calc::getFirstMonthOfYear($pn_year),
- $pn_year);
- }
-
-
- // }}}
- // {{{ lastDayOfYear()
-
- /**
- * Returns the Julian Day of the last day of the year (i.e. the no of
- * days since 24th November, 4714 B.C.)
- *
- * @param int $pn_year the year (using 'Astronomical' year numbering)
- *
- * @return integer the number of days since 24th November, 4714 B.C.
- * @access public
- * @static
- * @since Method available since Release 1.5.0
- */
- function lastDayOfYear($pn_year)
- {
- return Date_Calc::firstDayOfYear($pn_year + 1) - 1;
- }
-
-
- // }}}
- // {{{ dateToDaysJulian()
-
- /**
- * Converts a date in the proleptic Julian calendar to the no of days
- * since 1st January, 4713 B.C.
- *
- * Returns the no of days since Monday, 1st January, 4713 B.C. in the
- * proleptic Julian calendar (which is 1st January, -4712 using
- * 'Astronomical' year numbering, and 24th November, 4713 B.C. in the
- * proleptic Gregorian calendar). This is also the first day of the 'Julian
- * Period' proposed by Joseph Scaliger in 1583, and the number of days
- * since this date is known as the 'Julian Day'. (It is not directly
- * to do with the Julian calendar, although this is where the name
- * is derived from.)
- *
- * The algorithm is valid for all years (positive and negative), and
- * also for years preceding 4713 B.C.
- *
- * @param int $day the day of the month
- * @param int $month the month
- * @param int $year the year (using 'Astronomical' year numbering)
- *
- * @return int the number of days since 1st January, 4713 B.C.
- * @access public
- * @static
- * @since Method available since Release 1.5.0
- */
- function dateToDaysJulian($day, $month, $year)
- {
- if ($month > 2) {
- // March = 0, April = 1, ..., December = 9,
- // January = 10, February = 11
- $month -= 3;
- } else {
- $month += 9;
- --$year;
- }
-
- $hb_negativeyear = $year < 0;
-
- if ($hb_negativeyear) {
- // Subtract 1 because year 0 is a leap year;
- // And N.B. that we must treat the leap years as occurring
- // one year earlier than they do, because for the purposes
- // of calculation, the year starts on 1st March:
- //
- return intval((1461 * $year + 1) / 4) +
- intval((153 * $month + 2) / 5) +
- $day + 1721116;
- } else {
- return intval(1461 * $year / 4) +
- floor((153 * $month + 2) / 5) +
- $day + 1721117;
- }
- }
-
-
- // }}}
- // {{{ daysToDateJulian()
-
- /**
- * Converts no of days since 1st January, 4713 B.C. (in the proleptic
- * Julian calendar, which is year -4712 using 'Astronomical' year
- * numbering) to Julian calendar date
- *
- * Returned date belongs to the proleptic Julian calendar, using
- * 'Astronomical' year numbering.
- *
- * @param int $days the number of days since 1st January, 4713 B.C.
- * @param string $format the string indicating how to format the output
- *
- * @return string the date in the desired format
- * @access public
- * @static
- * @since Method available since Release 1.5.0
- */
- function daysToDateJulian($days, $format = DATE_CALC_FORMAT)
- {
- $days = intval($days);
-
- $days -= 1721117;
- $days = floor(4 * $days - 1);
- $day = floor($days / 4);
-
- $year = floor((4 * $day + 3) / 1461);
- $day = floor(4 * $day + 3 - 1461 * $year);
- $day = floor(($day + 4) / 4);
-
- $month = floor((5 * $day - 3) / 153);
- $day = floor(5 * $day - 3 - 153 * $month);
- $day = floor(($day + 5) / 5);
-
- if ($month < 10) {
- $month +=3;
- } else {
- $month -=9;
- ++$year;
- }
-
- return Date_Calc::dateFormat($day, $month, $year, $format);
- }
-
-
- // }}}
- // {{{ isoWeekDate()
-
- /**
- * Returns array defining the 'ISO Week Date' as defined in ISO 8601
- *
- * Expects a date in the proleptic Gregorian calendar using 'Astronomical'
- * year numbering, that is, with a year 0. Algorithm is valid for all
- * years (positive and negative).
- *
- * N.B. the ISO week day no for Sunday is defined as 7, whereas this
- * class and its related functions defines Sunday as 0.
- *
- * @param int $pn_day the day of the month
- * @param int $pn_month the month
- * @param int $pn_year the year
- *
- * @return array array of ISO Year, ISO Week No, ISO Day No as
- * integers
- * @access public
- * @static
- * @since Method available since Release 1.5.0
- */
- function isoWeekDate($pn_day = 0, $pn_month = 0, $pn_year = null)
- {
- if (is_null($pn_year)) {
- $pn_year = Date_Calc::dateNow('%Y');
- }
- if (empty($pn_month)) {
- $pn_month = Date_Calc::dateNow('%m');
- }
- if (empty($pn_day)) {
- $pn_day = Date_Calc::dateNow('%d');
- }
-
- $hn_jd = Date_Calc::dateToDays($pn_day, $pn_month, $pn_year);
- $hn_wd = Date_Calc::daysToDayOfWeek($hn_jd);
- if ($hn_wd == 0)
- $hn_wd = 7;
-
- $hn_jd1 = Date_Calc::firstDayOfYear($pn_year);
- $hn_day = $hn_jd - $hn_jd1 + 1;
-
- if ($hn_wd <= $hn_jd - Date_Calc::lastDayOfYear($pn_year) + 3) {
- // ISO week is the first week of the next ISO year:
- //
- $hn_year = $pn_year + 1;
- $hn_isoweek = 1;
- } else {
- switch ($hn_wd1 = Date_Calc::daysToDayOfWeek($hn_jd1)) {
- case 1:
- case 2:
- case 3:
- case 4:
- // Monday - Thursday:
- //
- $hn_year = $pn_year;
- $hn_isoweek = floor(($hn_day + $hn_wd1 - 2) / 7) + 1;
- break;
- case 0:
- $hn_wd1 = 7;
- case 5:
- case 6:
- // Friday - Sunday:
- //
- if ($hn_day <= 8 - $hn_wd1) {
- // ISO week is the last week of the previous ISO year:
- //
- list($hn_year, $hn_lastmonth, $hn_lastday) =
- explode(" ",
- Date_Calc::daysToDate($hn_jd1 - 1, "%Y %m %d"));
- list($hn_year, $hn_isoweek, $hn_pisoday) =
- Date_Calc::isoWeekDate($hn_lastday,
- $hn_lastmonth,
- $hn_year);
- } else {
- $hn_year = $pn_year;
- $hn_isoweek = floor(($hn_day + $hn_wd1 - 9) / 7) + 1;
- }
-
- break;
- }
- }
-
- return array((int) $hn_year, (int) $hn_isoweek, (int) $hn_wd);
- }
-
-
- // }}}
- // {{{ gregorianToISO()
-
- /**
- * Converts from Gregorian Year-Month-Day to ISO Year-WeekNumber-WeekDay
- *
- * Uses ISO 8601 definitions.
- *
- * @param int $day the day of the month
- * @param int $month the month
- * @param int $year the year. Use the complete year instead of the
- * abbreviated version. E.g. use 2005, not 05.
- *
- * @return string the date in ISO Year-WeekNumber-WeekDay format
- * @access public
- * @static
- */
- function gregorianToISO($day, $month, $year)
- {
- list($yearnumber, $weeknumber, $weekday) =
- Date_Calc::isoWeekDate($day, $month, $year);
- return sprintf("%04d", $yearnumber) .
- '-' .
- sprintf("%02d", $weeknumber) .
- '-' .
- $weekday;
- }
-
-
- // }}}
- // {{{ weekOfYear4th()
-
- /**
- * Returns week of the year counting week 1 as the week that contains 4th
- * January
- *
- * Week 1 is determined to be the week that includes the 4th January, and
- * therefore can be defined as the first week of the year that has at least
- * 4 days. The previous week is counted as week 52 or 53 of the previous
- * year. Note that this definition depends on which day is the first day of
- * the week, and that if this is not passed as the '$pn_firstdayofweek'
- * parameter, the default is assumed.
- *
- * Note also that the last day week of the year is likely to extend into
- * the following year, except in the case that the last day of the week
- * falls on 31st December.
- *
- * Also note that this is very similar to the ISO week returned by
- * 'isoWeekDate()', the difference being that the ISO week always has
- * 7 days, and if the 4th of January is a Friday, for example,
- * ISO week 1 would start on Monday, 31st December in the previous year,
- * whereas the week defined by this function would start on 1st January,
- * but would be only 6 days long. Of course you can also set the day
- * of the week, whereas the ISO week starts on a Monday by definition.
- *
- * Returned week is an integer from 1 to 53.
- *
- * @param int $pn_day the day of the month, default is current
- * local day
- * @param int $pn_month the month, default is current local month
- * @param int $pn_year the year in four digit format, default is
- * current local year
- * @param int $pn_firstdayofweek optional integer specifying the first day
- * of the week
- *
- * @return array array of year, week no as integers
- * @access public
- * @static
- * @since Method available since Release 1.5.0
- */
- function weekOfYear4th($pn_day = 0,
- $pn_month = 0,
- $pn_year = null,
- $pn_firstdayofweek = DATE_CALC_BEGIN_WEEKDAY)
- {
- if (is_null($pn_year)) {
- $pn_year = Date_Calc::dateNow('%Y');
- }
- if (empty($pn_month)) {
- $pn_month = Date_Calc::dateNow('%m');
- }
- if (empty($pn_day)) {
- $pn_day = Date_Calc::dateNow('%d');
- }
-
- $hn_wd1 = Date_Calc::daysToDayOfWeek(Date_Calc::firstDayOfYear($pn_year));
- $hn_day = Date_Calc::dayOfYear($pn_day, $pn_month, $pn_year);
- $hn_week = floor(($hn_day +
- (10 + $hn_wd1 - $pn_firstdayofweek) % 7 +
- 3) / 7);
-
- if ($hn_week > 0) {
- $hn_year = $pn_year;
- } else {
- // Week number is the last week of the previous year:
- //
- list($hn_year, $hn_lastmonth, $hn_lastday) =
- explode(" ",
- Date_Calc::daysToDate(Date_Calc::lastDayOfYear($pn_year - 1),
- "%Y %m %d"));
- list($hn_year, $hn_week) =
- Date_Calc::weekOfYear4th($hn_lastday,
- $hn_lastmonth,
- $hn_year,
- $pn_firstdayofweek);
- }
-
- return array((int) $hn_year, (int) $hn_week);
- }
-
-
- // }}}
- // {{{ weekOfYear7th()
-
- /**
- * Returns week of the year counting week 1 as the week that contains 7th
- * January
- *
- * Week 1 is determined to be the week that includes the 7th January, and
- * therefore can be defined as the first full week of the year. The
- * previous week is counted as week 52 or 53 of the previous year. Note
- * that this definition depends on which day is the first day of the week,
- * and that if this is not passed as the '$pn_firstdayofweek' parameter, the
- * default is assumed.
- *
- * Note also that the last day week of the year is likely to extend into
- * the following year, except in the case that the last day of the week
- * falls on 31st December.
- *
- * Returned week is an integer from 1 to 53.
- *
- * @param int $pn_day the day of the month, default is current
- * local day
- * @param int $pn_month the month, default is current local month
- * @param int $pn_year the year in four digit format, default is
- * current local year
- * @param int $pn_firstdayofweek optional integer specifying the first day
- * of the week
- *
- * @return array array of year, week no as integers
- * @access public
- * @static
- * @since Method available since Release 1.5.0
- */
- function weekOfYear7th($pn_day = 0,
- $pn_month = 0,
- $pn_year = null,
- $pn_firstdayofweek = DATE_CALC_BEGIN_WEEKDAY)
- {
- if (is_null($pn_year)) {
- $pn_year = Date_Calc::dateNow('%Y');
- }
- if (empty($pn_month)) {
- $pn_month = Date_Calc::dateNow('%m');
- }
- if (empty($pn_day)) {
- $pn_day = Date_Calc::dateNow('%d');
- }
-
- $hn_wd1 = Date_Calc::daysToDayOfWeek(Date_Calc::firstDayOfYear($pn_year));
- $hn_day = Date_Calc::dayOfYear($pn_day, $pn_month, $pn_year);
- $hn_week = floor(($hn_day + (6 + $hn_wd1 - $pn_firstdayofweek) % 7) / 7);
-
- if ($hn_week > 0) {
- $hn_year = $pn_year;
- } else {
- // Week number is the last week of the previous ISO year:
- //
- list($hn_year, $hn_lastmonth, $hn_lastday) = explode(" ", Date_Calc::daysToDate(Date_Calc::lastDayOfYear($pn_year - 1), "%Y %m %d"));
- list($hn_year, $hn_week) = Date_Calc::weekOfYear7th($hn_lastday, $hn_lastmonth, $hn_year, $pn_firstdayofweek);
- }
-
- return array((int) $hn_year, (int) $hn_week);
- }
-
-
- // }}}
- // {{{ dateSeason()
-
- /**
- * Determines julian date of the given season
- *
- * Adapted from previous work in Java by James Mark Hamilton.
- *
- * @param string $season the season to get the date for: VERNALEQUINOX,
- * SUMMERSOLSTICE, AUTUMNALEQUINOX,
- * or WINTERSOLSTICE
- * @param string $year the year in four digit format. Must be between
- * -1000 B.C. and 3000 A.D.
- *
- * @return float the julian date the season starts on
- * @access public
- * @static
- */
- function dateSeason($season, $year = 0)
- {
- if ($year == '') {
- $year = Date_Calc::dateNow('%Y');
- }
- if (($year >= -1000) && ($year <= 1000)) {
- $y = $year / 1000.0;
- switch ($season) {
- case 'VERNALEQUINOX':
- $juliandate = (((((((-0.00071 * $y) - 0.00111) * $y) + 0.06134) * $y) + 365242.1374) * $y) + 1721139.29189;
- break;
- case 'SUMMERSOLSTICE':
- $juliandate = (((((((0.00025 * $y) + 0.00907) * $y) - 0.05323) * $y) + 365241.72562) * $y) + 1721233.25401;
- break;
- case 'AUTUMNALEQUINOX':
- $juliandate = (((((((0.00074 * $y) - 0.00297) * $y) - 0.11677) * $y) + 365242.49558) * $y) + 1721325.70455;
- break;
- case 'WINTERSOLSTICE':
- default:
- $juliandate = (((((((-0.00006 * $y) - 0.00933) * $y) - 0.00769) * $y) + 365242.88257) * $y) + 1721414.39987;
- }
- } elseif (($year > 1000) && ($year <= 3000)) {
- $y = ($year - 2000) / 1000;
- switch ($season) {
- case 'VERNALEQUINOX':
- $juliandate = (((((((-0.00057 * $y) - 0.00411) * $y) + 0.05169) * $y) + 365242.37404) * $y) + 2451623.80984;
- break;
- case 'SUMMERSOLSTICE':
- $juliandate = (((((((-0.0003 * $y) + 0.00888) * $y) + 0.00325) * $y) + 365241.62603) * $y) + 2451716.56767;
- break;
- case 'AUTUMNALEQUINOX':
- $juliandate = (((((((0.00078 * $y) + 0.00337) * $y) - 0.11575) * $y) + 365242.01767) * $y) + 2451810.21715;
- break;
- case 'WINTERSOLSTICE':
- default:
- $juliandate = (((((((0.00032 * $y) - 0.00823) * $y) - 0.06223) * $y) + 365242.74049) * $y) + 2451900.05952;
- }
- }
- return $juliandate;
- }
-
-
- // }}}
- // {{{ dayOfYear()
-
- /**
- * Returns number of days since 31 December of year before given date
- *
- * @param int $pn_day the day of the month, default is current local day
- * @param int $pn_month the month, default is current local month
- * @param int $pn_year the year in four digit format, default is current
- * local year
- *
- * @return int
- * @access public
- * @static
- * @since Method available since Release 1.5.0
- */
- function dayOfYear($pn_day = 0, $pn_month = 0, $pn_year = null)
- {
- if (is_null($pn_year)) {
- $pn_year = Date_Calc::dateNow('%Y');
- }
- if (empty($pn_month)) {
- $pn_month = Date_Calc::dateNow('%m');
- }
- if (empty($pn_day)) {
- $pn_day = Date_Calc::dateNow('%d');
- }
-
- $hn_jd = Date_Calc::dateToDays($pn_day, $pn_month, $pn_year);
- $hn_jd1 = Date_Calc::firstDayOfYear($pn_year);
- return $hn_jd - $hn_jd1 + 1;
- }
-
-
- // }}}
- // {{{ julianDate()
-
- /**
- * Returns number of days since 31 December of year before given date
- *
- * @param int $pn_day the day of the month, default is current local day
- * @param int $pn_month the month, default is current local month
- * @param int $pn_year the year in four digit format, default is current
- * local year
- *
- * @return int
- * @access public
- * @static
- * @deprecated Method deprecated in Release 1.5.0
- */
- function julianDate($pn_day = 0, $pn_month = 0, $pn_year = null)
- {
- return Date_Calc::dayOfYear($pn_day, $pn_month, $pn_year);
- }
-
-
- // }}}
- // {{{ getWeekdayFullname()
-
- /**
- * Returns the full weekday name for the given date
- *
- * @param int $pn_day the day of the month, default is current local day
- * @param int $pn_month the month, default is current local month
- * @param int $pn_year the year in four digit format, default is current
- * local year
- *
- * @return string the full name of the day of the week
- * @access public
- * @static
- */
- function getWeekdayFullname($pn_day = 0, $pn_month = 0, $pn_year = null)
- {
- if (is_null($pn_year)) {
- $pn_year = Date_Calc::dateNow('%Y');
- }
- if (empty($pn_month)) {
- $pn_month = Date_Calc::dateNow('%m');
- }
- if (empty($pn_day)) {
- $pn_day = Date_Calc::dateNow('%d');
- }
-
- $weekday_names = Date_Calc::getWeekDays();
- $weekday = Date_Calc::dayOfWeek($pn_day, $pn_month, $pn_year);
- return $weekday_names[$weekday];
- }
-
-
- // }}}
- // {{{ getWeekdayAbbrname()
-
- /**
- * Returns the abbreviated weekday name for the given date
- *
- * @param int $pn_day the day of the month, default is current local day
- * @param int $pn_month the month, default is current local month
- * @param int $pn_year the year in four digit format, default is current
- * local year
- * @param int $length the length of abbreviation
- *
- * @return string the abbreviated name of the day of the week
- * @access public
- * @static
- * @see Date_Calc::getWeekdayFullname()
- */
- function getWeekdayAbbrname($pn_day = 0,
- $pn_month = 0,
- $pn_year = null,
- $length = 3)
- {
- if (is_null($pn_year)) {
- $pn_year = Date_Calc::dateNow('%Y');
- }
- if (empty($pn_month)) {
- $pn_month = Date_Calc::dateNow('%m');
- }
- if (empty($pn_day)) {
- $pn_day = Date_Calc::dateNow('%d');
- }
-
- $weekday_names = Date_Calc::getWeekDays(true);
- $weekday = Date_Calc::dayOfWeek($pn_day, $pn_month, $pn_year);
- return $weekday_names[$weekday];
- }
-
-
- // }}}
- // {{{ getMonthFullname()
-
- /**
- * Returns the full month name for the given month
- *
- * @param int $month the month
- *
- * @return string the full name of the month
- * @access public
- * @static
- */
- function getMonthFullname($month)
- {
- $month = (int)$month;
- if (empty($month)) {
- $month = (int)Date_Calc::dateNow('%m');
- }
-
- $month_names = Date_Calc::getMonthNames();
- return $month_names[$month];
- }
-
-
- // }}}
- // {{{ getMonthAbbrname()
-
- /**
- * Returns the abbreviated month name for the given month
- *
- * @param int $month the month
- * @param int $length the length of abbreviation
- *
- * @return string the abbreviated name of the month
- * @access public
- * @static
- * @see Date_Calc::getMonthFullname
- */
- function getMonthAbbrname($month, $length = 3)
- {
- $month = (int)$month;
- if (empty($month)) {
- $month = Date_Calc::dateNow('%m');
- }
-
- $month_names = Date_Calc::getMonthNames(true);
- return $month_names[$month];
- }
-
-
- // }}}
- // {{{ getMonthFromFullname()
-
- /**
- * Returns the numeric month from the month name or an abreviation
- *
- * Both August and Aug would return 8.
- *
- * @param string $month the name of the month to examine.
- * Case insensitive.
- *
- * @return int the month's number
- * @access public
- * @static
- */
- function getMonthFromFullName($month)
- {
- $month = strtolower($month);
- $months = Date_Calc::getMonthNames();
- while (list($id, $name) = each($months)) {
- if (ereg($month, strtolower($name))) {
- return $id;
- }
- }
- return 0;
- }
-
-
- // }}}
- // {{{ getWeekDays()
-
- /**
- * Returns an array of week day names
- *
- * Used to take advantage of the setlocale function to return language
- * specific week days.
- *
- * @param int $pb_abbreviated whether to return the abbreviated form of the
- * days
- *
- * @return array an array of week-day names
- * @access public
- * @static
- */
- function getWeekDays($pb_abbreviated = false)
- {
- for ($i = 0; $i < 7; $i++) {
- $weekdays[$i] = strftime($pb_abbreviated ? '%a' : '%A',
- mktime(0, 0, 0, 1, $i, 2001));
- }
- return $weekdays;
- }
-
-
- // }}}
- // {{{ daysToDayOfWeek()
-
- /**
- * Returns day of week for specified 'Julian Day'
- *
- * The algorithm is valid for all years (positive and negative), and
- * also for years preceding 4714 B.C. (i.e. for negative 'Julian Days'),
- * and so the only limitation is platform-dependent (for 32-bit systems
- * the maximum year would be something like about 1,465,190 A.D.).
- *
- * N.B. Monday, 24th November, 4714 B.C. is Julian Day '0'.
- *
- * @param int $pn_days the number of days since 24th November, 4714 B.C.
- *
- * @return int integer from 0 to 7 where 0 represents Sunday
- * @access public
- * @static
- * @since Method available since Release 1.5.0
- */
- function daysToDayOfWeek($pn_days)
- {
- // On Julian day 0 the day is Monday (PHP day 1):
- //
- $ret = ($pn_days + 1) % 7;
- return $ret < 0 ? $ret + 7 : $ret;
- }
-
-
- // }}}
- // {{{ dayOfWeek()
-
- /**
- * Returns day of week for given date (0 = Sunday)
- *
- * The algorithm is valid for all years (positive and negative).
- *
- * @param int $day the day of the month, default is current local day
- * @param int $month the month, default is current local month
- * @param int $year the year in four digit format, default is current
- * local year
- *
- * @return int the number of the day in the week
- * @access public
- * @static
- */
- function dayOfWeek($day = null, $month = null, $year = null)
- {
- if (is_null($year)) {
- $year = Date_Calc::dateNow('%Y');
- }
- if (empty($month)) {
- $month = Date_Calc::dateNow('%m');
- }
- if (empty($day)) {
- $day = Date_Calc::dateNow('%d');
- }
-
- // if ($month <= 2) {
- // $month += 12;
- // --$year;
- // }
-
- // $wd = ($day +
- // intval((13 * $month + 3) / 5) +
- // $year +
- // floor($year / 4) -
- // floor($year / 100) +
- // floor($year / 400) +
- // 1) % 7;
-
- // return (int) ($wd < 0 ? $wd + 7 : $wd);
-
- return Date_Calc::daysToDayOfWeek(Date_Calc::dateToDays($day,
- $month,
- $year));
- }
-
-
- // }}}
- // {{{ weekOfYearAbsolute()
-
- /**
- * Returns week of the year counting week 1 as 1st-7th January,
- * regardless of what day 1st January falls on
- *
- * Returned value is an integer from 1 to 53. Week 53 will start on
- * 31st December and have only one day, except in a leap year, in
- * which it will start a day earlier and contain two days.
- *
- * @param int $pn_day the day of the month, default is current local day
- * @param int $pn_month the month, default is current local month
- * @param int $pn_year the year in four digit format, default is current
- * local year
- *
- * @return int integer from 1 to 53
- * @access public
- * @static
- * @since Method available since Release 1.5.0
- */
- function weekOfYearAbsolute($pn_day = 0, $pn_month = 0, $pn_year = null)
- {
- if (is_null($pn_year)) {
- $pn_year = Date_Calc::dateNow('%Y');
- }
- if (empty($pn_month)) {
- $pn_month = Date_Calc::dateNow('%m');
- }
- if (empty($pn_day)) {
- $pn_day = Date_Calc::dateNow('%d');
- }
-
- $hn_day = Date_Calc::dayOfYear($pn_day, $pn_month, $pn_year);
- return intval(($hn_day + 6) / 7);
- }
-
-
- // }}}
- // {{{ weekOfYear1st()
-
- /**
- * Returns week of the year counting week 1 as the week that contains 1st
- * January
- *
- * Week 1 is determined to be the week that includes the 1st January, even
- * if this week extends into the previous year, in which case the week will
- * only contain between 1 and 6 days of the current year. Note that this
- * definition depends on which day is the first day of the week, and that if
- * this is not passed as the '$pn_firstdayofweek' parameter, the default is
- * assumed.
- *
- * Note also that the last day week of the year is also likely to contain
- * less than seven days, except in the case that the last day of the week
- * falls on 31st December.
- *
- * Returned value is an integer from 1 to 54. The year will only contain
- * 54 weeks in the case of a leap year in which 1st January is the last day
- * of the week, and 31st December is the first day of the week. In this
- * case, both weeks 1 and 54 will contain one day only.
- *
- * @param int $pn_day the day of the month, default is current
- * local day
- * @param int $pn_month the month, default is current local month
- * @param int $pn_year the year in four digit format, default is
- * current local year
- * @param int $pn_firstdayofweek optional integer specifying the first day
- * of the week
- *
- * @return int integer from 1 to 54
- * @access public
- * @static
- * @since Method available since Release 1.5.0
- */
- function weekOfYear1st($pn_day = 0,
- $pn_month = 0,
- $pn_year = null,
- $pn_firstdayofweek = DATE_CALC_BEGIN_WEEKDAY)
- {
- if (is_null($pn_year)) {
- $pn_year = Date_Calc::dateNow('%Y');
- }
- if (empty($pn_month)) {
- $pn_month = Date_Calc::dateNow('%m');
- }
- if (empty($pn_day)) {
- $pn_day = Date_Calc::dateNow('%d');
- }
-
- $hn_wd1 = Date_Calc::daysToDayOfWeek(Date_Calc::firstDayOfYear($pn_year));
- $hn_day = Date_Calc::dayOfYear($pn_day, $pn_month, $pn_year);
- return floor(($hn_day + (7 + $hn_wd1 - $pn_firstdayofweek) % 7 + 6) / 7);
- }
-
-
- // }}}
- // {{{ weekOfYear()
-
- /**
- * Returns week of the year, where first Sunday is first day of first week
- *
- * N.B. this function is equivalent to calling:
- *
- * <code>Date_Calc::weekOfYear7th($day, $month, $year, 0)</code>
- *
- * Returned week is an integer from 1 to 53.
- *
- * @param int $pn_day the day of the month, default is current local day
- * @param int $pn_month the month, default is current local month
- * @param int $pn_year the year in four digit format, default is current
- * local year
- *
- * @return int integer from 1 to 53
- * @access public
- * @static
- * @see Date_Calc::weekOfYear7th
- * @deprecated Method deprecated in Release 1.5.0
- */
- function weekOfYear($pn_day = 0, $pn_month = 0, $pn_year = null)
- {
- $ha_week = Date_Calc::weekOfYear7th($pn_day, $pn_month, $pn_year, 0);
- return $ha_week[1];
- }
-
-
- // }}}
- // {{{ weekOfMonthAbsolute()
-
- /**
- * Returns week of the month counting week 1 as 1st-7th of the month,
- * regardless of what day the 1st falls on
- *
- * Returned value is an integer from 1 to 5. Week 5 will start on
- * the 29th of the month and have between 1 and 3 days, except
- * in February in a non-leap year, when there will be 4 weeks only.
- *
- * @param int $pn_day the day of the month, default is current local day
- *
- * @return int integer from 1 to 5
- * @access public
- * @static
- * @since Method available since Release 1.5.0
- */
- function weekOfMonthAbsolute($pn_day = 0)
- {
- if (empty($pn_day)) {
- $pn_day = Date_Calc::dateNow('%d');
- }
- return intval(($pn_day + 6) / 7);
- }
-
-
- // }}}
- // {{{ weekOfMonth()
-
- /**
- * Alias for 'weekOfMonthAbsolute()'
- *
- * @param int $pn_day the day of the month, default is current local day
- *
- * @return int integer from 1 to 5
- * @access public
- * @static
- * @since Method available since Release 1.5.0
- */
- function weekOfMonth($pn_day = 0)
- {
- return Date_Calc::weekOfMonthAbsolute($pn_day);
- }
-
-
- // }}}
- // {{{ quarterOfYear()
-
- /**
- * Returns quarter of the year for given date
- *
- * @param int $day the day of the month, default is current local day
- * @param int $month the month, default is current local month
- * @param int $year the year in four digit format, default is current
- * local year
- *
- * @return int the number of the quarter in the year
- * @access public
- * @static
- */
- function quarterOfYear($day = 0, $month = 0, $year = null)
- {
- if (empty($month)) {
- $month = Date_Calc::dateNow('%m');
- }
- return intval(($month - 1) / 3 + 1);
- }
-
-
- // }}}
- // {{{ daysInMonth()
-
- /**
- * Returns the number of days in the given month
- *
- * @param int $month the month, default is current local month
- * @param int $year the year in four digit format, default is current
- * local year
- *
- * @return int the number of days the month has
- * @access public
- * @static
- */
- function daysInMonth($month = 0, $year = null)
- {
- if (is_null($year)) {
- $year = Date_Calc::dateNow('%Y');
- }
- if (empty($month)) {
- $month = Date_Calc::dateNow('%m');
- }
-
- return Date_Calc::lastDayOfMonth($month, $year) -
- Date_Calc::firstDayOfMonth($month, $year) +
- 1;
- }
-
-
- // }}}
- // {{{ daysInYear()
-
- /**
- * Returns the number of days in the given year
- *
- * @param int $year the year in four digit format, default is current local
- * year
- *
- * @return int the number of days the year has
- * @access public
- * @static
- */
- function daysInYear($year = null)
- {
- if (is_null($year)) {
- $year = Date_Calc::dateNow('%Y');
- }
-
- return Date_Calc::firstDayOfYear($year + 1) -
- Date_Calc::firstDayOfYear($year);
- }
-
-
- // }}}
- // {{{ weeksInMonth()
-
- /**
- * Returns the number of rows on a calendar month
- *
- * Useful for determining the number of rows when displaying a typical
- * month calendar.
- *
- * @param int $month the month, default is current local month
- * @param int $year the year in four digit format, default is current
- * local year
- *
- * @return int the number of weeks the month has
- * @access public
- * @static
- */
- function weeksInMonth($month = 0, $year = null)
- {
- if (is_null($year)) {
- $year = Date_Calc::dateNow('%Y');
- }
- if (empty($month)) {
- $month = Date_Calc::dateNow('%m');
- }
- $FDOM = Date_Calc::firstOfMonthWeekday($month, $year);
- if (DATE_CALC_BEGIN_WEEKDAY==1 && $FDOM==0) {
- $first_week_days = 7 - $FDOM + DATE_CALC_BEGIN_WEEKDAY;
- $weeks = 1;
- } elseif (DATE_CALC_BEGIN_WEEKDAY==0 && $FDOM == 6) {
- $first_week_days = 7 - $FDOM + DATE_CALC_BEGIN_WEEKDAY;
- $weeks = 1;
- } else {
- $first_week_days = DATE_CALC_BEGIN_WEEKDAY - $FDOM;
- $weeks = 0;
- }
- $first_week_days %= 7;
- return ceil((Date_Calc::daysInMonth($month, $year)
- - $first_week_days) / 7) + $weeks;
- }
-
-
- // }}}
- // {{{ getCalendarWeek()
-
- /**
- * Return an array with days in week
- *
- * @param int $day the day of the month, default is current local day
- * @param int $month the month, default is current local month
- * @param int $year the year in four digit format, default is current
- * local year
- * @param string $format the string indicating how to format the output
- *
- * @return array $week[$weekday]
- * @access public
- * @static
- */
- function getCalendarWeek($day = 0, $month = 0, $year = null,
- $format = DATE_CALC_FORMAT)
- {
- if (is_null($year)) {
- $year = Date_Calc::dateNow('%Y');
- }
- if (empty($month)) {
- $month = Date_Calc::dateNow('%m');
- }
- if (empty($day)) {
- $day = Date_Calc::dateNow('%d');
- }
-
- $week_array = array();
-
- // date for the column of week
-
- $curr_day = Date_Calc::beginOfWeek($day, $month, $year, '%E');
-
- for ($counter = 0; $counter <= 6; $counter++) {
- $week_array[$counter] = Date_Calc::daysToDate($curr_day, $format);
- $curr_day++;
- }
- return $week_array;
- }
-
-
- // }}}
- // {{{ getCalendarMonth()
-
- /**
- * Return a set of arrays to construct a calendar month for the given date
- *
- * @param int $month the month, default is current local month
- * @param int $year the year in four digit format, default is current
- * local year
- * @param string $format the string indicating how to format the output
- *
- * @return array $month[$row][$col]
- * @access public
- * @static
- */
- function getCalendarMonth($month = 0, $year = null,
- $format = DATE_CALC_FORMAT)
- {
- if (is_null($year)) {
- $year = Date_Calc::dateNow('%Y');
- }
- if (empty($month)) {
- $month = Date_Calc::dateNow('%m');
- }
-
- $month_array = array();
-
- // date for the first row, first column of calendar month
- if (DATE_CALC_BEGIN_WEEKDAY == 1) {
- if (Date_Calc::firstOfMonthWeekday($month, $year) == 0) {
- $curr_day = Date_Calc::firstDayOfMonth($month, $year) - 6;
- } else {
- $curr_day = Date_Calc::firstDayOfMonth($month, $year)
- - Date_Calc::firstOfMonthWeekday($month, $year) + 1;
- }
- } else {
- $curr_day = (Date_Calc::firstDayOfMonth($month, $year)
- - Date_Calc::firstOfMonthWeekday($month, $year));
- }
-
- // number of days in this month
- $daysInMonth = Date_Calc::daysInMonth($month, $year);
-
- $weeksInMonth = Date_Calc::weeksInMonth($month, $year);
- for ($row_counter = 0; $row_counter < $weeksInMonth; $row_counter++) {
- for ($column_counter = 0; $column_counter <= 6; $column_counter++) {
- $month_array[$row_counter][$column_counter] =
- Date_Calc::daysToDate($curr_day, $format);
- $curr_day++;
- }
- }
-
- return $month_array;
- }
-
-
- // }}}
- // {{{ getCalendarYear()
-
- /**
- * Return a set of arrays to construct a calendar year for the given date
- *
- * @param int $year the year in four digit format, default current
- * local year
- * @param string $format the string indicating how to format the output
- *
- * @return array $year[$month][$row][$col]
- * @access public
- * @static
- */
- function getCalendarYear($year = null, $format = DATE_CALC_FORMAT)
- {
- if (is_null($year)) {
- $year = Date_Calc::dateNow('%Y');
- }
-
- $year_array = array();
-
- for ($curr_month = 0; $curr_month <= 11; $curr_month++) {
- $year_array[$curr_month] =
- Date_Calc::getCalendarMonth($curr_month + 1,
- $year, $format);
- }
-
- return $year_array;
- }
-
-
- // }}}
- // {{{ prevDay()
-
- /**
- * Returns date of day before given date
- *
- * @param int $day the day of the month, default is current local day
- * @param int $month the month, default is current local month
- * @param int $year the year in four digit format, default is current
- * local year
- * @param string $format the string indicating how to format the output
- *
- * @return string the date in the desired format
- * @access public
- * @static
- */
- function prevDay($day = 0, $month = 0, $year = null,
- $format = DATE_CALC_FORMAT)
- {
- if (is_null($year)) {
- $year = Date_Calc::dateNow('%Y');
- }
- if (empty($month)) {
- $month = Date_Calc::dateNow('%m');
- }
- if (empty($day)) {
- $day = Date_Calc::dateNow('%d');
- }
-
- return Date_Calc::addDays(-1, $day, $month, $year, $format);
- }
-
-
- // }}}
- // {{{ nextDay()
-
- /**
- * Returns date of day after given date
- *
- * @param int $day the day of the month, default is current local day
- * @param int $month the month, default is current local month
- * @param int $year the year in four digit format, default is current
- * local year
- * @param string $format the string indicating how to format the output
- *
- * @return string the date in the desired format
- * @access public
- * @static
- */
- function nextDay($day = 0,
- $month = 0,
- $year = null,
- $format = DATE_CALC_FORMAT)
- {
- if (is_null($year)) {
- $year = Date_Calc::dateNow('%Y');
- }
- if (empty($month)) {
- $month = Date_Calc::dateNow('%m');
- }
- if (empty($day)) {
- $day = Date_Calc::dateNow('%d');
- }
-
- return Date_Calc::addDays(1, $day, $month, $year, $format);
- }
-
-
- // }}}
- // {{{ prevWeekday()
-
- /**
- * Returns date of the previous weekday, skipping from Monday to Friday
- *
- * @param int $day the day of the month, default is current local day
- * @param int $month the month, default is current local month
- * @param int $year the year in four digit format, default is current
- * local year
- * @param string $format the string indicating how to format the output
- *
- * @return string the date in the desired format
- * @access public
- * @static
- */
- function prevWeekday($day = 0, $month = 0, $year = null,
- $format = DATE_CALC_FORMAT)
- {
- if (is_null($year)) {
- $year = Date_Calc::dateNow('%Y');
- }
- if (empty($month)) {
- $month = Date_Calc::dateNow('%m');
- }
- if (empty($day)) {
- $day = Date_Calc::dateNow('%d');
- }
-
- $days = Date_Calc::dateToDays($day, $month, $year);
- if (Date_Calc::dayOfWeek($day, $month, $year) == 1) {
- $days -= 3;
- } elseif (Date_Calc::dayOfWeek($day, $month, $year) == 0) {
- $days -= 2;
- } else {
- $days -= 1;
- }
-
- return Date_Calc::daysToDate($days, $format);
- }
-
-
- // }}}
- // {{{ nextWeekday()
-
- /**
- * Returns date of the next weekday of given date, skipping from
- * Friday to Monday
- *
- * @param int $day the day of the month, default is current local day
- * @param int $month the month, default is current local month
- * @param int $year the year in four digit format, default is current
- * local year
- * @param string $format the string indicating how to format the output
- *
- * @return string the date in the desired format
- * @access public
- * @static
- */
- function nextWeekday($day = 0, $month = 0, $year = null,
- $format = DATE_CALC_FORMAT)
- {
- if (is_null($year)) {
- $year = Date_Calc::dateNow('%Y');
- }
- if (empty($month)) {
- $month = Date_Calc::dateNow('%m');
- }
- if (empty($day)) {
- $day = Date_Calc::dateNow('%d');
- }
-
- $days = Date_Calc::dateToDays($day, $month, $year);
- if (Date_Calc::dayOfWeek($day, $month, $year) == 5) {
- $days += 3;
- } elseif (Date_Calc::dayOfWeek($day, $month, $year) == 6) {
- $days += 2;
- } else {
- $days += 1;
- }
-
- return Date_Calc::daysToDate($days, $format);
- }
-
-
- // }}}
- // {{{ daysToPrevDayOfWeek()
-
- /**
- * Returns 'Julian Day' of the previous specific day of the week
- * from the given date.
- *
- * @param int $dow the day of the week (0 = Sunday)
- * @param int $days 'Julian Day', i.e. the no of days since 1st
- * January, 4713 B.C.
- * @param bool $onorbefore if true and days are same, returns current day
- *
- * @return int 'Julian Day', i.e. the no of days since 1st January,
- * 4713 B.C.
- * @access public
- * @static
- * @since Method available since Release 1.5.0
- */
- function daysToPrevDayOfWeek($dow, $days, $onorbefore = false)
- {
- $curr_weekday = Date_Calc::daysToDayOfWeek($days);
- if ($curr_weekday == $dow) {
- if ($onorbefore) {
- return $days;
- } else {
- return $days - 7;
- }
- } else if ($curr_weekday < $dow) {
- return $days - 7 + $dow - $curr_weekday;
- } else {
- return $days - $curr_weekday + $dow;
- }
- }
-
-
- // }}}
- // {{{ prevDayOfWeek()
-
- /**
- * Returns date of the previous specific day of the week
- * from the given date
- *
- * @param int $dow the day of the week (0 = Sunday)
- * @param int $day the day of the month, default is current local
- * day
- * @param int $month the month, default is current local month
- * @param int $year the year in four digit format, default is
- * current local year
- * @param string $format the string indicating how to format the output
- * @param bool $onorbefore if true and days are same, returns current day
- *
- * @return string the date in the desired format
- * @access public
- * @static
- */
- function prevDayOfWeek($dow,
- $day = 0,
- $month = 0,
- $year = null,
- $format = DATE_CALC_FORMAT,
- $onorbefore = false)
- {
- if (is_null($year)) {
- $year = Date_Calc::dateNow('%Y');
- }
- if (empty($month)) {
- $month = Date_Calc::dateNow('%m');
- }
- if (empty($day)) {
- $day = Date_Calc::dateNow('%d');
- }
-
- $days = Date_Calc::dateToDays($day, $month, $year);
- $days = Date_Calc::daysToPrevDayOfWeek($dow, $days, $onorbefore);
- return Date_Calc::daysToDate($days, $format);
- }
-
-
- // }}}
- // {{{ daysToNextDayOfWeek()
-
- /**
- * Returns 'Julian Day' of the next specific day of the week
- * from the given date.
- *
- * @param int $dow the day of the week (0 = Sunday)
- * @param int $days 'Julian Day', i.e. the no of days since 1st
- * January, 4713 B.C.
- * @param bool $onorafter if true and days are same, returns current day
- *
- * @return int 'Julian Day', i.e. the no of days since 1st January,
- * 4713 B.C.
- * @access public
- * @static
- * @since Method available since Release 1.5.0
- */
- function daysToNextDayOfWeek($dow, $days, $onorafter = false)
- {
- $curr_weekday = Date_Calc::daysToDayOfWeek($days);
- if ($curr_weekday == $dow) {
- if ($onorafter) {
- return $days;
- } else {
- return $days + 7;
- }
- } else if ($curr_weekday > $dow) {
- return $days + 7 - $curr_weekday + $dow;
- } else {
- return $days + $dow - $curr_weekday;
- }
- }
-
-
- // }}}
- // {{{ nextDayOfWeek()
-
- /**
- * Returns date of the next specific day of the week
- * from the given date
- *
- * @param int $dow the day of the week (0 = Sunday)
- * @param int $day the day of the month, default is current local
- * day
- * @param int $month the month, default is current local month
- * @param int $year the year in four digit format, default is
- * current local year
- * @param string $format the string indicating how to format the output
- * @param bool $onorafter if true and days are same, returns current day
- *
- * @return string the date in the desired format
- * @access public
- * @static
- */
- function nextDayOfWeek($dow,
- $day = 0,
- $month = 0,
- $year = null,
- $format = DATE_CALC_FORMAT,
- $onorafter = false)
- {
- if (is_null($year)) {
- $year = Date_Calc::dateNow('%Y');
- }
- if (empty($month)) {
- $month = Date_Calc::dateNow('%m');
- }
- if (empty($day)) {
- $day = Date_Calc::dateNow('%d');
- }
-
- $days = Date_Calc::dateToDays($day, $month, $year);
- $days = Date_Calc::daysToNextDayOfWeek($dow, $days, $onorafter);
- return Date_Calc::daysToDate($days, $format);
- }
-
-
- // }}}
- // {{{ prevDayOfWeekOnOrBefore()
-
- /**
- * Returns date of the previous specific day of the week
- * on or before the given date
- *
- * @param int $dow the day of the week (0 = Sunday)
- * @param int $day the day of the month, default is current local day
- * @param int $month the month, default is current local month
- * @param int $year the year in four digit format, default is current
- * local year
- * @param string $format the string indicating how to format the output
- *
- * @return string the date in the desired format
- * @access public
- * @static
- */
- function prevDayOfWeekOnOrBefore($dow,
- $day = 0,
- $month = 0,
- $year = null,
- $format = DATE_CALC_FORMAT)
- {
- return Date_Calc::prevDayOfWeek($dow,
- $day,
- $month,
- $year,
- $format,
- true);
- }
-
-
- // }}}
- // {{{ nextDayOfWeekOnOrAfter()
-
- /**
- * Returns date of the next specific day of the week
- * on or after the given date
- *
- * @param int $dow the day of the week (0 = Sunday)
- * @param int $day the day of the month, default is current local day
- * @param int $month the month, default is current local month
- * @param int $year the year in four digit format, default is current
- * local year
- * @param string $format the string indicating how to format the output
- *
- * @return string the date in the desired format
- * @access public
- * @static
- */
- function nextDayOfWeekOnOrAfter($dow,
- $day = 0,
- $month = 0,
- $year = null,
- $format = DATE_CALC_FORMAT)
- {
- return Date_Calc::nextDayOfWeek($dow,
- $day,
- $month,
- $year,
- $format,
- true);
- }
-
-
- // }}}
- // {{{ beginOfWeek()
-
- /**
- * Find the month day of the beginning of week for given date,
- * using DATE_CALC_BEGIN_WEEKDAY
- *
- * Can return weekday of prev month.
- *
- * @param int $day the day of the month, default is current local day
- * @param int $month the month, default is current local month
- * @param int $year the year in four digit format, default is current
- * local year
- * @param string $format the string indicating how to format the output
- *
- * @return string the date in the desired format
- * @access public
- * @static
- */
- function beginOfWeek($day = 0, $month = 0, $year = null,
- $format = DATE_CALC_FORMAT)
- {
- if (is_null($year)) {
- $year = Date_Calc::dateNow('%Y');
- }
- if (empty($month)) {
- $month = Date_Calc::dateNow('%m');
- }
- if (empty($day)) {
- $day = Date_Calc::dateNow('%d');
- }
-
- $hn_days = Date_Calc::dateToDays($day, $month, $year);
- $this_weekday = Date_Calc::daysToDayOfWeek($hn_days);
- $interval = (7 - DATE_CALC_BEGIN_WEEKDAY + $this_weekday) % 7;
- return Date_Calc::daysToDate($hn_days - $interval, $format);
- }
-
-
- // }}}
- // {{{ endOfWeek()
-
- /**
- * Find the month day of the end of week for given date,
- * using DATE_CALC_BEGIN_WEEKDAY
- *
- * Can return weekday of following month.
- *
- * @param int $day the day of the month, default is current local day
- * @param int $month the month, default is current local month
- * @param int $year the year in four digit format, default is current
- * local year
- * @param string $format the string indicating how to format the output
- *
- * @return string the date in the desired format
- * @access public
- * @static
- */
- function endOfWeek($day = 0, $month = 0, $year = null,
- $format = DATE_CALC_FORMAT)
- {
- if (is_null($year)) {
- $year = Date_Calc::dateNow('%Y');
- }
- if (empty($month)) {
- $month = Date_Calc::dateNow('%m');
- }
- if (empty($day)) {
- $day = Date_Calc::dateNow('%d');
- }
-
- $hn_days = Date_Calc::dateToDays($day, $month, $year);
- $this_weekday = Date_Calc::daysToDayOfWeek($hn_days);
- $interval = (6 + DATE_CALC_BEGIN_WEEKDAY - $this_weekday) % 7;
- return Date_Calc::daysToDate($hn_days + $interval, $format);
- }
-
-
- // }}}
- // {{{ beginOfPrevWeek()
-
- /**
- * Find the month day of the beginning of week before given date,
- * using DATE_CALC_BEGIN_WEEKDAY
- *
- * Can return weekday of prev month.
- *
- * @param int $day the day of the month, default is current local day
- * @param int $month the month, default is current local month
- * @param int $year the year in four digit format, default is current
- * local year
- * @param string $format the string indicating how to format the output
- *
- * @return string the date in the desired format
- * @access public
- * @static
- */
- function beginOfPrevWeek($day = 0, $month = 0, $year = null,
- $format = DATE_CALC_FORMAT)
- {
- if (is_null($year)) {
- $year = Date_Calc::dateNow('%Y');
- }
- if (empty($month)) {
- $month = Date_Calc::dateNow('%m');
- }
- if (empty($day)) {
- $day = Date_Calc::dateNow('%d');
- }
-
- list($hn_pwyear, $hn_pwmonth, $hn_pwday) =
- explode(" ", Date_Calc::daysToDate(Date_Calc::dateToDays($day,
- $month,
- $year) - 7,
- '%Y %m %d'));
- return Date_Calc::beginOfWeek($hn_pwday,
- $hn_pwmonth,
- $hn_pwyear,
- $format);
- }
-
-
- // }}}
- // {{{ beginOfNextWeek()
-
- /**
- * Find the month day of the beginning of week after given date,
- * using DATE_CALC_BEGIN_WEEKDAY
- *
- * Can return weekday of prev month.
- *
- * @param int $day the day of the month, default is current local day
- * @param int $month the month, default is current local month
- * @param int $year the year in four digit format, default is current
- * local year
- * @param string $format the string indicating how to format the output
- *
- * @return string the date in the desired format
- * @access public
- * @static
- */
- function beginOfNextWeek($day = 0, $month = 0, $year = null,
- $format = DATE_CALC_FORMAT)
- {
- if (is_null($year)) {
- $year = Date_Calc::dateNow('%Y');
- }
- if (empty($month)) {
- $month = Date_Calc::dateNow('%m');
- }
- if (empty($day)) {
- $day = Date_Calc::dateNow('%d');
- }
-
- list($hn_pwyear, $hn_pwmonth, $hn_pwday) =
- explode(" ",
- Date_Calc::daysToDate(Date_Calc::dateToDays($day,
- $month,
- $year) + 7,
- '%Y %m %d'));
- return Date_Calc::beginOfWeek($hn_pwday,
- $hn_pwmonth,
- $hn_pwyear,
- $format);
- }
-
-
- // }}}
- // {{{ beginOfMonth()
-
- /**
- * Return date of first day of month of given date
- *
- * @param int $month the month, default is current local month
- * @param int $year the year in four digit format, default is current
- * local year
- * @param string $format the string indicating how to format the output
- *
- * @return string the date in the desired format
- * @access public
- * @static
- * @see Date_Calc::beginOfMonthBySpan()
- * @deprecated Method deprecated in Release 1.4.4
- */
- function beginOfMonth($month = 0, $year = null, $format = DATE_CALC_FORMAT)
- {
- if (is_null($year)) {
- $year = Date_Calc::dateNow('%Y');
- }
- if (empty($month)) {
- $month = Date_Calc::dateNow('%m');
- }
-
- return Date_Calc::dateFormat(Date_Calc::getFirstDayOfMonth($month,
- $year),
- $month,
- $year,
- $format);
- }
-
-
- // }}}
- // {{{ endOfMonth()
-
- /**
- * Return date of last day of month of given date
- *
- * @param int $month the month, default is current local month
- * @param int $year the year in four digit format, default is current
- * local year
- * @param string $format the string indicating how to format the output
- *
- * @return string the date in the desired format
- * @access public
- * @static
- * @see Date_Calc::beginOfMonthBySpan()
- * @since Method available since Release 1.5.0
- * @deprecated Method deprecated in Release 1.5.0
- */
- function endOfMonth($month = 0, $year = null, $format = DATE_CALC_FORMAT)
- {
- if (is_null($year)) {
- $year = Date_Calc::dateNow('%Y');
- }
- if (empty($month)) {
- $month = Date_Calc::dateNow('%m');
- }
-
- return Date_Calc::daysToDate(Date_Calc::lastDayOfMonth($month, $year),
- $format);
- }
-
-
- // }}}
- // {{{ beginOfPrevMonth()
-
- /**
- * Returns date of the first day of previous month of given date
- *
- * @param mixed $dummy irrelevant parameter
- * @param int $month the month, default is current local month
- * @param int $year the year in four digit format, default is current
- * local year
- * @param string $format the string indicating how to format the output
- *
- * @return string the date in the desired format
- * @access public
- * @static
- * @see Date_Calc::beginOfMonthBySpan()
- * @deprecated Method deprecated in Release 1.4.4
- */
- function beginOfPrevMonth($dummy = null,
- $month = 0,
- $year = null,
- $format = DATE_CALC_FORMAT)
- {
- if (is_null($year)) {
- $year = Date_Calc::dateNow('%Y');
- }
- if (empty($month)) {
- $month = Date_Calc::dateNow('%m');
- }
-
- list($hn_pmyear, $hn_prevmonth) = Date_Calc::prevMonth($month, $year);
- return Date_Calc::dateFormat(Date_Calc::getFirstDayOfMonth($hn_prevmonth,
- $hn_pmyear),
- $hn_prevmonth,
- $hn_pmyear,
- $format);
- }
-
-
- // }}}
- // {{{ endOfPrevMonth()
-
- /**
- * Returns date of the last day of previous month for given date
- *
- * @param mixed $dummy irrelevant parameter
- * @param int $month the month, default is current local month
- * @param int $year the year in four digit format, default is current
- * local year
- * @param string $format the string indicating how to format the output
- *
- * @return string the date in the desired format
- * @access public
- * @static
- * @see Date_Calc::endOfMonthBySpan()
- * @deprecated Method deprecated in Release 1.4.4
- */
- function endOfPrevMonth($dummy = null,
- $month = 0,
- $year = null,
- $format = DATE_CALC_FORMAT)
- {
- if (is_null($year)) {
- $year = Date_Calc::dateNow('%Y');
- }
- if (empty($month)) {
- $month = Date_Calc::dateNow('%m');
- }
-
- return Date_Calc::daysToDate(Date_Calc::firstDayOfMonth($month,
- $year) - 1,
- $format);
- }
-
-
- // }}}
- // {{{ beginOfNextMonth()
-
- /**
- * Returns date of begin of next month of given date
- *
- * @param mixed $dummy irrelevant parameter
- * @param int $month the month, default is current local month
- * @param int $year the year in four digit format, default is current
- * local year
- * @param string $format the string indicating how to format the output
- *
- * @return string the date in the desired format
- * @access public
- * @static
- * @see Date_Calc::beginOfMonthBySpan()
- * @deprecated Method deprecated in Release 1.4.4
- */
- function beginOfNextMonth($dummy = null,
- $month = 0,
- $year = null,
- $format = DATE_CALC_FORMAT)
- {
- if (is_null($year)) {
- $year = Date_Calc::dateNow('%Y');
- }
- if (empty($month)) {
- $month = Date_Calc::dateNow('%m');
- }
-
- list($hn_nmyear, $hn_nextmonth) = Date_Calc::nextMonth($month, $year);
- return Date_Calc::dateFormat(Date_Calc::getFirstDayOfMonth($hn_nextmonth,
- $hn_nmyear),
- $hn_nextmonth,
- $hn_nmyear,
- $format);
- }
-
-
- // }}}
- // {{{ endOfNextMonth()
-
- /**
- * Returns date of the last day of next month of given date
- *
- * @param mixed $dummy irrelevant parameter
- * @param int $month the month, default is current local month
- * @param int $year the year in four digit format, default is current
- * local year
- * @param string $format the string indicating how to format the output
- *
- * @return string the date in the desired format
- * @access public
- * @static
- * @see Date_Calc::endOfMonthBySpan()
- * @deprecated Method deprecated in Release 1.4.4
- */
- function endOfNextMonth($dummy = null,
- $month = 0,
- $year = null,
- $format = DATE_CALC_FORMAT)
- {
- if (is_null($year)) {
- $year = Date_Calc::dateNow('%Y');
- }
- if (empty($month)) {
- $month = Date_Calc::dateNow('%m');
- }
-
- list($hn_nmyear, $hn_nextmonth) = Date_Calc::nextMonth($month, $year);
- return Date_Calc::daysToDate(Date_Calc::lastDayOfMonth($hn_nextmonth,
- $hn_nmyear),
- $format);
- }
-
-
- // }}}
- // {{{ beginOfMonthBySpan()
-
- /**
- * Returns date of the first day of the month in the number of months
- * from the given date
- *
- * @param int $months the number of months from the date provided.
- * Positive numbers go into the future.
- * Negative numbers go into the past.
- * 0 is the month presented in $month.
- * @param string $month the month, default is current local month
- * @param string $year the year in four digit format, default is the
- * current local year
- * @param string $format the string indicating how to format the output
- *
- * @return string the date in the desired format
- * @access public
- * @static
- * @since Method available since Release 1.4.4
- */
- function beginOfMonthBySpan($months = 0,
- $month = 0,
- $year = null,
- $format = DATE_CALC_FORMAT)
- {
- if (is_null($year)) {
- $year = Date_Calc::dateNow('%Y');
- }
- if (empty($month)) {
- $month = Date_Calc::dateNow('%m');
- }
-
- return Date_Calc::addMonths($months,
- Date_Calc::getFirstDayOfMonth($month, $year),
- $month,
- $year,
- $format);
- }
-
-
- // }}}
- // {{{ endOfMonthBySpan()
-
- /**
- * Returns date of the last day of the month in the number of months
- * from the given date
- *
- * @param int $months the number of months from the date provided.
- * Positive numbers go into the future.
- * Negative numbers go into the past.
- * 0 is the month presented in $month.
- * @param string $month the month, default is current local month
- * @param string $year the year in four digit format, default is the
- * current local year
- * @param string $format the string indicating how to format the output
- *
- * @return string the date in the desired format
- * @access public
- * @static
- * @since Method available since Release 1.4.4
- */
- function endOfMonthBySpan($months = 0,
- $month = 0,
- $year = null,
- $format = DATE_CALC_FORMAT)
- {
- if (is_null($year)) {
- $year = Date_Calc::dateNow('%Y');
- }
- if (empty($month)) {
- $month = Date_Calc::dateNow('%m');
- }
-
- $hn_days = Date_Calc::addMonthsToDays($months + 1,
- Date_Calc::firstDayOfMonth($month, $year)) - 1;
- return Date_Calc::daysToDate($hn_days, $format);
- }
-
-
- // }}}
- // {{{ firstOfMonthWeekday()
-
- /**
- * Find the day of the week for the first of the month of given date
- *
- * @param int $month the month, default is current local month
- * @param int $year the year in four digit format, default is current
- * local year
- *
- * @return int number of weekday for the first day, 0=Sunday
- * @access public
- * @static
- */
- function firstOfMonthWeekday($month = 0, $year = null)
- {
- if (is_null($year)) {
- $year = Date_Calc::dateNow('%Y');
- }
- if (empty($month)) {
- $month = Date_Calc::dateNow('%m');
- }
- return Date_Calc::daysToDayOfWeek(Date_Calc::firstDayOfMonth($month,
- $year));
- }
-
-
- // }}}
- // {{{ nWeekdayOfMonth()
-
- /**
- * Calculates the date of the Nth weekday of the month,
- * such as the second Saturday of January 2000
- *
- * @param int $week the number of the week to get
- * (1 = first, etc. Also can be 'last'.)
- * @param int $dow the day of the week (0 = Sunday)
- * @param int $month the month
- * @param int $year the year. Use the complete year instead of the
- * abbreviated version. E.g. use 2005, not 05.
- * @param string $format the string indicating how to format the output
- *
- * @return string the date in the desired format
- * @access public
- * @static
- */
- function nWeekdayOfMonth($week, $dow, $month, $year,
- $format = DATE_CALC_FORMAT)
- {
- if (is_numeric($week)) {
- $DOW1day = ($week - 1) * 7 + 1;
- $DOW1 = Date_Calc::dayOfWeek($DOW1day, $month, $year);
- $wdate = ($week - 1) * 7 + 1 + (7 + $dow - $DOW1) % 7;
- if ($wdate > Date_Calc::daysInMonth($month, $year)) {
- return -1;
- } else {
- return Date_Calc::dateFormat($wdate, $month, $year, $format);
- }
- } elseif ($week == 'last' && $dow < 7) {
- $lastday = Date_Calc::daysInMonth($month, $year);
- $lastdow = Date_Calc::dayOfWeek($lastday, $month, $year);
- $diff = $dow - $lastdow;
- if ($diff > 0) {
- return Date_Calc::dateFormat($lastday - (7 - $diff), $month,
- $year, $format);
- } else {
- return Date_Calc::dateFormat($lastday + $diff, $month,
- $year, $format);
- }
- } else {
- return -1;
- }
- }
-
-
- // }}}
- // {{{ isValidDate()
-
- /**
- * Returns true for valid date, false for invalid date
- *
- * Uses the proleptic Gregorian calendar, with the year 0 (1 B.C.)
- * assumed to be valid and also assumed to be a leap year.
- *
- * @param int $day the day of the month
- * @param int $month the month
- * @param int $year the year. Use the complete year instead of the
- * abbreviated version. E.g. use 2005, not 05.
- *
- * @return bool
- * @access public
- * @static
- */
- function isValidDate($day, $month, $year)
- {
- if ($day < 1 || $month < 1 || $month > 12)
- return false;
- if ($month == 2) {
- if (Date_Calc::isLeapYearGregorian($year)) {
- return $day <= 29;
- } else {
- return $day <= 28;
- }
- } elseif ($month == 4 || $month == 6 || $month == 9 || $month == 11) {
- return $day <= 30;
- } else {
- return $day <= 31;
- }
- }
-
-
- // }}}
- // {{{ isLeapYearGregorian()
-
- /**
- * Returns true for a leap year, else false
- *
- * Uses the proleptic Gregorian calendar. The year 0 (1 B.C.) is
- * assumed in this algorithm to be a leap year. The function is
- * valid for all years, positive and negative.
- *
- * @param int $year the year. Use the complete year instead of the
- * abbreviated version. E.g. use 2005, not 05.
- *
- * @return bool
- * @access public
- * @static
- * @since Method available since Release 1.5.0
- */
- function isLeapYearGregorian($year = null)
- {
- if (is_null($year)) {
- $year = Date_Calc::dateNow('%Y');
- }
- return (($year % 4 == 0) &&
- ($year % 100 != 0)) ||
- ($year % 400 == 0);
- }
-
-
- // }}}
- // {{{ isLeapYearJulian()
-
- /**
- * Returns true for a leap year, else false
- *
- * Uses the proleptic Julian calendar. The year 0 (1 B.C.) is
- * assumed in this algorithm to be a leap year. The function is
- * valid for all years, positive and negative.
- *
- * @param int $year the year. Use the complete year instead of the
- * abbreviated version. E.g. use 2005, not 05.
- *
- * @return boolean
- * @access public
- * @static
- * @since Method available since Release 1.5.0
- */
- function isLeapYearJulian($year = null)
- {
- if (is_null($year)) {
- $year = Date_Calc::dateNow('%Y');
- }
- return $year % 4 == 0;
- }
-
-
- // }}}
- // {{{ isLeapYear()
-
- /**
- * Returns true for a leap year, else false
- *
- * @param int $year the year. Use the complete year instead of the
- * abbreviated version. E.g. use 2005, not 05.
- *
- * @return boolean
- * @access public
- * @static
- */
- function isLeapYear($year = null)
- {
- if (is_null($year)) {
- $year = Date_Calc::dateNow('%Y');
- }
- if ($year < 1582) {
- // pre Gregorio XIII - 1582
- return Date_Calc::isLeapYearJulian($year);
- } else {
- // post Gregorio XIII - 1582
- return Date_Calc::isLeapYearGregorian($year);
- }
- }
-
-
- // }}}
- // {{{ isFutureDate()
-
- /**
- * Determines if given date is a future date from now
- *
- * @param int $day the day of the month
- * @param int $month the month
- * @param int $year the year. Use the complete year instead of the
- * abbreviated version. E.g. use 2005, not 05.
- *
- * @return bool
- * @access public
- * @static
- */
- function isFutureDate($day, $month, $year)
- {
- $this_year = Date_Calc::dateNow('%Y');
- $this_month = Date_Calc::dateNow('%m');
- $this_day = Date_Calc::dateNow('%d');
-
- if ($year > $this_year) {
- return true;
- } elseif ($year == $this_year) {
- if ($month > $this_month) {
- return true;
- } elseif ($month == $this_month) {
- if ($day > $this_day) {
- return true;
- }
- }
- }
- return false;
- }
-
-
- // }}}
- // {{{ isPastDate()
-
- /**
- * Determines if given date is a past date from now
- *
- * @param int $day the day of the month
- * @param int $month the month
- * @param int $year the year. Use the complete year instead of the
- * abbreviated version. E.g. use 2005, not 05.
- *
- * @return boolean
- * @access public
- * @static
- */
- function isPastDate($day, $month, $year)
- {
- $this_year = Date_Calc::dateNow('%Y');
- $this_month = Date_Calc::dateNow('%m');
- $this_day = Date_Calc::dateNow('%d');
-
- if ($year < $this_year) {
- return true;
- } elseif ($year == $this_year) {
- if ($month < $this_month) {
- return true;
- } elseif ($month == $this_month) {
- if ($day < $this_day) {
- return true;
- }
- }
- }
- return false;
- }
-
-
- // }}}
- // {{{ dateDiff()
-
- /**
- * Returns number of days between two given dates
- *
- * @param int $day1 the day of the month
- * @param int $month1 the month
- * @param int $year1 the year. Use the complete year instead of the
- * abbreviated version. E.g. use 2005, not 05.
- * @param int $day2 the day of the month
- * @param int $month2 the month
- * @param int $year2 the year. Use the complete year instead of the
- * abbreviated version. E.g. use 2005, not 05.
- *
- * @return int the absolute number of days between the two dates.
- * If an error occurs, -1 is returned.
- * @access public
- * @static
- */
- function dateDiff($day1, $month1, $year1, $day2, $month2, $year2)
- {
- if (!Date_Calc::isValidDate($day1, $month1, $year1)) {
- return -1;
- }
- if (!Date_Calc::isValidDate($day2, $month2, $year2)) {
- return -1;
- }
- return abs(Date_Calc::dateToDays($day1, $month1, $year1)
- - Date_Calc::dateToDays($day2, $month2, $year2));
- }
-
-
- // }}}
- // {{{ compareDates()
-
- /**
- * Compares two dates
- *
- * @param int $day1 the day of the month
- * @param int $month1 the month
- * @param int $year1 the year. Use the complete year instead of the
- * abbreviated version. E.g. use 2005, not 05.
- * @param int $day2 the day of the month
- * @param int $month2 the month
- * @param int $year2 the year. Use the complete year instead of the
- * abbreviated version. E.g. use 2005, not 05.
- *
- * @return int 0 if the dates are equal. 1 if date 1 is later, -1
- * if date 1 is earlier.
- * @access public
- * @static
- */
- function compareDates($day1, $month1, $year1, $day2, $month2, $year2)
- {
- $ndays1 = Date_Calc::dateToDays($day1, $month1, $year1);
- $ndays2 = Date_Calc::dateToDays($day2, $month2, $year2);
- if ($ndays1 == $ndays2) {
- return 0;
- }
- return ($ndays1 > $ndays2) ? 1 : -1;
- }
-
-
- // }}}
- // {{{ round()
-
- /**
- * Rounds the date according to the specified precision
- *
- * The precision parameter must be one of the following constants:
- *
- * <code>DATE_PRECISION_YEAR</code>
- * <code>DATE_PRECISION_MONTH</code>
- * <code>DATE_PRECISION_DAY</code>
- * <code>DATE_PRECISION_HOUR</code>
- * <code>DATE_PRECISION_10MINUTES</code>
- * <code>DATE_PRECISION_MINUTE</code>
- * <code>DATE_PRECISION_10SECONDS</code>
- * <code>DATE_PRECISION_SECOND</code>
- *
- * The precision can also be specified as an integral offset from
- * one of these constants, where the offset reflects a precision
- * of 10 to the power of the offset greater than the constant.
- * For example:
- *
- * <code>DATE_PRECISION_YEAR - 1</code> rounds the date to the nearest 10
- * years
- * <code>DATE_PRECISION_YEAR - 3</code> rounds the date to the nearest 1000
- * years
- * <code>DATE_PRECISION_SECOND + 1</code> rounds the date to 1 decimal
- * point of a second
- * <code>DATE_PRECISION_SECOND + 1</code> rounds the date to 3 decimal
- * points of a second
- * <code>DATE_PRECISION_SECOND + 1</code> rounds the date to the nearest 10
- * seconds (thus it is equivalent to
- * DATE_PRECISION_10SECONDS)
- *
- * N.B. This function requires a time in UTC if both the precision is at
- * least DATE_PRECISION_SECOND and leap seconds are being counted, otherwise
- * any local time is acceptable.
- *
- * @param int $pn_precision a 'DATE_PRECISION_*' constant
- * @param int $pn_day the day of the month
- * @param int $pn_month the month
- * @param int $pn_year the year
- * @param int $pn_hour the hour
- * @param int $pn_minute the minute
- * @param mixed $pn_second the second as integer or float
- * @param bool $pb_countleap whether to count leap seconds (defaults to
- * DATE_COUNT_LEAP_SECONDS)
- *
- * @return array array of year, month, day, hour, minute, second
- * @access public
- * @static
- * @since Method available since Release 1.5.0
- */
- function round($pn_precision,
- $pn_day,
- $pn_month,
- $pn_year,
- $pn_hour = 0,
- $pn_minute = 0,
- $pn_second = 0,
- $pb_countleap = DATE_COUNT_LEAP_SECONDS)
- {
- if ($pn_precision <= DATE_PRECISION_YEAR) {
- $hn_month = 0;
- $hn_day = 0;
- $hn_hour = 0;
- $hn_minute = 0;
- $hn_second = 0;
-
- if ($pn_precision < DATE_PRECISION_YEAR) {
- $hn_year = round($pn_year, $pn_precision - DATE_PRECISION_YEAR);
- } else {
- // Check part-year:
- //
- $hn_midyear = (Date_Calc::firstDayOfYear($pn_year + 1) -
- Date_Calc::firstDayOfYear($pn_year)) / 2;
- if (($hn_days = Date_Calc::dayOfYear($pn_day,
- $pn_month,
- $pn_year)) <=
- $hn_midyear - 1) {
- $hn_year = $pn_year;
- } else if ($hn_days >= $hn_midyear) {
- // Round up:
- //
- $hn_year = $pn_year + 1;
- } else {
- // Take time into account:
- //
- $hn_partday = Date_Calc::secondsPastMidnight($pn_hour,
- $pn_minute,
- $pn_second) /
- 86400;
- if ($hn_partday >= $hn_midyear - $hn_days) {
- // Round up:
- //
- $hn_year = $pn_year + 1;
- } else {
- $hn_year = $pn_year;
- }
- }
- }
- } else if ($pn_precision == DATE_PRECISION_MONTH) {
- $hn_year = $pn_year;
- $hn_day = 0;
- $hn_hour = 0;
- $hn_minute = 0;
- $hn_second = 0;
-
- $hn_firstofmonth = Date_Calc::firstDayOfMonth($pn_month, $pn_year);
- $hn_midmonth = (Date_Calc::lastDayOfMonth($pn_month, $pn_year) +
- 1 -
- $hn_firstofmonth) / 2;
- if (($hn_days = Date_Calc::dateToDays($pn_day,
- $pn_month,
- $pn_year) -
- $hn_firstofmonth) <= $hn_midmonth - 1) {
- $hn_month = $pn_month;
- } else if ($hn_days >= $hn_midmonth) {
- // Round up:
- //
- list($hn_year, $hn_month) = Date_Calc::nextMonth($pn_month,
- $pn_year);
- } else {
- // Take time into account:
- //
- $hn_partday = Date_Calc::secondsPastMidnight($pn_hour,
- $pn_minute,
- $pn_second) /
- 86400;
- if ($hn_partday >= $hn_midmonth - $hn_days) {
- // Round up:
- //
- list($hn_year, $hn_month) = Date_Calc::nextMonth($pn_month,
- $pn_year);
- } else {
- $hn_month = $pn_month;
- }
- }
- } else if ($pn_precision == DATE_PRECISION_DAY) {
- $hn_year = $pn_year;
- $hn_month = $pn_month;
- $hn_hour = 0;
- $hn_minute = 0;
- $hn_second = 0;
-
- if (Date_Calc::secondsPastMidnight($pn_hour,
- $pn_minute,
- $pn_second) >= 43200) {
- // Round up:
- //
- list($hn_year, $hn_month, $hn_day) =
- explode(" ", Date_Calc::nextDay($pn_day,
- $pn_month,
- $pn_year,
- "%Y %m %d"));
- } else {
- $hn_day = $pn_day;
- }
- } else if ($pn_precision == DATE_PRECISION_HOUR) {
- $hn_year = $pn_year;
- $hn_month = $pn_month;
- $hn_day = $pn_day;
- $hn_minute = 0;
- $hn_second = 0;
-
- if (Date_Calc::secondsPastTheHour($pn_minute, $pn_second) >= 1800) {
- // Round up:
- //
- list($hn_year, $hn_month, $hn_day, $hn_hour) =
- Date_Calc::addHours(1,
- $pn_day,
- $pn_month,
- $pn_year,
- $pn_hour);
- } else {
- $hn_hour = $pn_hour;
- }
- } else if ($pn_precision <= DATE_PRECISION_MINUTE) {
- $hn_year = $pn_year;
- $hn_month = $pn_month;
- $hn_day = $pn_day;
- $hn_hour = $pn_hour;
- $hn_second = 0;
-
- if ($pn_precision < DATE_PRECISION_MINUTE) {
- $hn_minute = round($pn_minute,
- $pn_precision - DATE_PRECISION_MINUTE);
- } else {
- // Check seconds:
- //
- if ($pn_second >= 30) {
- // Round up:
- //
- list($hn_year,
- $hn_month,
- $hn_day,
- $hn_hour,
- $hn_minute) =
- Date_Calc::addMinutes(1,
- $pn_day,
- $pn_month,
- $pn_year,
- $pn_hour,
- $pn_minute);
- } else {
- $hn_minute = $pn_minute;
- }
- }
- } else {
- // Precision is at least (DATE_PRECISION_SECOND - 1):
- //
- $hn_year = $pn_year;
- $hn_month = $pn_month;
- $hn_day = $pn_day;
- $hn_hour = $pn_hour;
- $hn_minute = $pn_minute;
-
- $hn_second = round($pn_second,
- $pn_precision - DATE_PRECISION_SECOND);
-
- if (fmod($hn_second, 1) == 0.0) {
- $hn_second = (int) $hn_second;
-
- if ($hn_second != intval($pn_second)) {
- list($hn_year,
- $hn_month,
- $hn_day,
- $hn_hour,
- $hn_minute,
- $hn_second) =
- Date_Calc::addSeconds($hn_second - intval($pn_second),
- $pn_day,
- $pn_month,
- $pn_year,
- $pn_hour,
- $pn_minute,
- intval($pn_second),
- $pn_precision >=
- DATE_PRECISION_SECOND &&
- $pb_countleap);
- //
- // (N.B. if rounded to nearest 10 seconds,
- // user does not expect seconds to be '60')
- }
- }
- }
-
- return array((int) $hn_year,
- (int) $hn_month,
- (int) $hn_day,
- (int) $hn_hour,
- (int) $hn_minute,
- $hn_second);
- }
-
-
- // }}}
- // {{{ roundSeconds()
-
- /**
- * Rounds seconds up or down to the nearest specified unit
- *
- * @param int $pn_precision number of digits after the decimal point
- * @param int $pn_day the day of the month
- * @param int $pn_month the month
- * @param int $pn_year the year
- * @param int $pn_hour the hour
- * @param int $pn_minute the minute
- * @param mixed $pn_second the second as integer or float
- * @param bool $pb_countleap whether to count leap seconds (defaults to
- * DATE_COUNT_LEAP_SECONDS)
- *
- * @return array array of year, month, day, hour, minute, second
- * @access public
- * @static
- * @since Method available since Release 1.5.0
- */
- function roundSeconds($pn_precision,
- $pn_day,
- $pn_month,
- $pn_year,
- $pn_hour,
- $pn_minute,
- $pn_second,
- $pb_countleap = DATE_COUNT_LEAP_SECONDS)
- {
- return Date_Calc::round(DATE_PRECISION_SECOND + $pn_precision,
- $pn_day,
- $pn_month,
- $pn_year,
- $pn_hour,
- $pn_minute,
- $pn_second);
- }
-
-
- // }}}
-
-}
-
-// }}}
-
-
-/*
- * Local variables:
- * mode: php
- * tab-width: 4
- * c-basic-offset: 4
- * c-hanging-comment-ender-p: nil
- * End:
- */
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */
-
-// {{{ Header
-
-/**
- * Class to convert date strings between Gregorian and Human calendar formats
- *
- * The Human Calendar format has been proposed by Scott Flansburg and can be
- * explained as follows:
- * The year is made up of 13 months
- * Each month has 28 days
- * Counting of months starts from 0 (zero) so the months will run from 0 to 12
- * New Years day (00) is a monthless day
- * Note: Leap Years are not yet accounted for in the Human Calendar system
- *
- * PHP versions 4 and 5
- *
- * LICENSE:
- *
- * Copyright (c) 1997-2006 Allan Kent
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted under the terms of the BSD License.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
- * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
- * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- *
- * @category Date and Time
- * @package Date
- * @author Allan Kent <allan@lodestone.co.za>
- * @copyright 1997-2006 Allan Kent
- * @license http://www.opensource.org/licenses/bsd-license.php
- * BSD License
- * @version CVS: $Id: Human.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- * @link http://pear.php.net/package/Date
- * @since File available since Release 1.3
- */
-
-// }}}
-// {{{ Class: Date_Human
-
-/**
- * Class to convert date strings between Gregorian and Human calendar formats
- *
- * The Human Calendar format has been proposed by Scott Flansburg and can be
- * explained as follows:
- * The year is made up of 13 months
- * Each month has 28 days
- * Counting of months starts from 0 (zero) so the months will run from 0 to 12
- * New Years day (00) is a monthless day
- * Note: Leap Years are not yet accounted for in the Human Calendar system
- *
- * @category Date and Time
- * @package Date
- * @author Allan Kent <allan@lodestone.co.za>
- * @copyright 1997-2005 Allan Kent
- * @license http://www.opensource.org/licenses/bsd-license.php
- * BSD License
- * @version Release: 1.5.0a1
- * @link http://pear.php.net/package/Date
- * @since Class available since Release 1.3
- */
-class Date_Human
-{
- // {{{ gregorianToHuman()
-
- /**
- * Returns an associative array containing the converted date information
- * in 'Human Calendar' format.
- *
- * If the day is New Years Day, the function will return
- * "hdom" => 0
- * "hdow" => 0
- * "hwom" => 0
- * "hwoy" => 0
- * "hmoy" => -1
- * Since 0 is a valid month number under the Human Calendar, I have left
- * the month as -1 for New Years Day.
- *
- * @param int $day in DD format, default current local day
- * @param int $month in MM format, default current local month
- * @param int $year in CCYY format, default to current local year
- *
- * @return associative array(
- * hdom, // Human Day Of Month, starting at 1
- * hdow, // Human Day Of Week, starting at 1
- * hwom, // Human Week of Month, starting at 1
- * hwoy, // Human Week of Year, starting at 1
- * hmoy, // Human Month of Year, starting at 0
- * )
- * @access public
- * @static
- */
- function gregorianToHuman($day = 0, $month = 0, $year = 0)
- {
- /*
- * Check to see if any of the arguments are empty
- * If they are then populate the $dateinfo array
- * Then check to see which arguments are empty and fill
- * those with the current date info
- */
- if ((empty($day) || (empty($month)) || empty($year))) {
- $dateinfo = getdate(time());
- }
- if (empty($day)) {
- $day = $dateinfo["mday"];
- }
- if (empty($month)) {
- $month = $dateinfo["mon"];
- }
- if (empty($year)) {
- $year = $dateinfo["year"];
- }
- /*
- * We need to know how many days into the year we are
- */
- $dateinfo = getdate(mktime(0, 0, 0, $month, $day, $year));
- $dayofyear = $dateinfo["yday"];
- /*
- * Human Calendar starts at 0 for months and the first day of the year
- * is designated 00, so we need to start our day of the year at 0 for
- * these calculations.
- * Also, the day of the month is calculated with a modulus of 28.
- * Because a day is 28 days, the last day of the month would have a
- * remainder of 0 and not 28 as it should be. Decrementing $dayofyear
- * gets around this.
- */
- $dayofyear--;
- /*
- * 28 days in a month...
- */
- $humanMonthOfYear = floor($dayofyear / 28);
- /*
- * If we are in the first month then the day of the month is $dayofyear
- * else we need to find the modulus of 28.
- */
- if ($humanMonthOfYear == 0) {
- $humanDayOfMonth = $dayofyear;
- } else {
- $humanDayOfMonth = ($dayofyear) % 28;
- }
- /*
- * Day of the week is modulus 7
- */
- $humanDayOfWeek = $dayofyear % 7;
- /*
- * We can now increment $dayofyear back to it's correct value for
- * the remainder of the calculations
- */
- $dayofyear++;
- /*
- * $humanDayOfMonth needs to be incremented now - recall that we fudged
- * it a bit by decrementing $dayofyear earlier
- * Same goes for $humanDayOfWeek
- */
- $humanDayOfMonth++;
- $humanDayOfWeek++;
- /*
- * Week of the month is day of the month divided by 7, rounded up
- * Same for week of the year, but use $dayofyear instead $humanDayOfMonth
- */
- $humanWeekOfMonth = ceil($humanDayOfMonth / 7);
- $humanWeekOfYear = ceil($dayofyear / 7);
- /*
- * Return an associative array of the values
- */
- return array("hdom" => $humanDayOfMonth,
- "hdow" => $humanDayOfWeek,
- "hwom" => $humanWeekOfMonth,
- "hwoy" => $humanWeekOfYear,
- "hmoy" => $humanMonthOfYear );
- }
-
- // }}}
- // {{{ humanToGregorian()
-
- /**
- * Returns unix timestamp for a given Human Calendar date
- *
- * @param int $day in DD format
- * @param int $month in MM format
- * @param int $year in CCYY format, default to current local year
- *
- * @return int unix timestamp of date
- * @access public
- * @static
- */
- function humanToGregorian($day, $month, $year = 0)
- {
- /*
- * Check to see if the year has been passed through.
- * If not get current year
- */
- if (empty($year)) {
- $dateinfo = getdate(time());
- $year = $dateinfo["year"];
- }
- /*
- * We need to get the day of the year that we are currently at so that
- * we can work out the Gregorian Month and day
- */
- $DayOfYear = $month * 28;
- $DayOfYear += $day;
- /*
- * Human Calendar starts at 0, so we need to increment $DayOfYear
- * to take into account the day 00
- */
- $DayOfYear++;
- /*
- * the mktime() function will correctly calculate the date for out of
- * range values, so putting $DayOfYear instead of the day of the month
- * will work fine.
- */
- $GregorianTimeStamp = mktime(0, 0, 0, 1, $DayOfYear, $year);
- return $GregorianTimeStamp;
- }
-
- // }}}
-}
-
-// }}}
-
-/*
- * Local variables:
- * mode: php
- * tab-width: 4
- * c-basic-offset: 4
- * c-hanging-comment-ender-p: nil
- * End:
- */
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */
-
-// {{{ Header
-
-/**
- * Generic time span handling class for PEAR
- *
- * PHP versions 4 and 5
- *
- * LICENSE:
- *
- * Copyright (c) 1997-2005 Leandro Lucarella, Pierre-Alain Joye
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted under the terms of the BSD License.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
- * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
- * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- *
- * @category Date and Time
- * @package Date
- * @author Leandro Lucarella <llucax@php.net>
- * @author Pierre-Alain Joye <pajoye@php.net>
- * @copyright 1997-2006 Leandro Lucarella, Pierre-Alain Joye
- * @license http://www.opensource.org/licenses/bsd-license.php
- * BSD License
- * @version CVS: $Id: Span.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- * @link http://pear.php.net/package/Date
- * @since File available since Release 1.4
- */
-
-// }}}
-// {{{ Includes
-
-/**
- * Get the Date class
- */
-require_once 'Date.php';
-
-/**
- * Get the Date_Calc class
- */
-require_once 'Date/Calc.php';
-
-// }}}
-// {{{ Constants
-
-/**
- * Non Numeric Separated Values (NNSV) Input Format
- *
- * Input format guessed from something like this:
- * days<sep>hours<sep>minutes<sep>seconds
- * Where <sep> is any quantity of non numeric chars. If no values are
- * given, time span is set to zero, if one value is given, it's used for
- * hours, if two values are given it's used for hours and minutes and if
- * three values are given, it's used for hours, minutes and seconds.<br>
- * Examples:<br>
- * '' -> 0, 0, 0, 0 (days, hours, minutes, seconds)<br>
- * '12' -> 0, 12, 0, 0
- * '12.30' -> 0, 12, 30, 0<br>
- * '12:30:18' -> 0, 12, 30, 18<br>
- * '3-12-30-18' -> 3, 12, 30, 18<br>
- * '3 days, 12-30-18' -> 3, 12, 30, 18<br>
- * '12:30 with 18 secs' -> 0, 12, 30, 18<br>
- *
- * @const int
- */
-define('DATE_SPAN_INPUT_FORMAT_NNSV', 1);
-
-// }}}
-// {{{ Global Variables
-
-/**
- * Default time format when converting to a string
- *
- * @global string
- */
-$GLOBALS['_DATE_SPAN_FORMAT'] = '%C';
-
-/**
- * Default time format when converting from a string
- *
- * @global mixed
- */
-$GLOBALS['_DATE_SPAN_INPUT_FORMAT'] = DATE_SPAN_INPUT_FORMAT_NNSV;
-
-// }}}
-// {{{ Class: Date_Span
-
-/**
- * Generic time span handling class for PEAR
- *
- * @category Date and Time
- * @package Date
- * @author Leandro Lucarella <llucax@php.net>
- * @author Pierre-Alain Joye <pajoye@php.net>
- * @copyright 1997-2006 Leandro Lucarella, Pierre-Alain Joye
- * @license http://www.opensource.org/licenses/bsd-license.php
- * BSD License
- * @version Release: 1.5.0a1
- * @link http://pear.php.net/package/Date
- * @since Class available since Release 1.4
- */
-class Date_Span
-{
-
- // {{{ Properties
-
- /**
- * The no of days
- *
- * @var int
- * @access private
- * @since Property available since Release 1.0
- */
- var $day;
-
- /**
- * The no of hours (0 to 23)
- *
- * @var int
- * @access private
- * @since Property available since Release 1.0
- */
- var $hour;
-
- /**
- * The no of minutes (0 to 59)
- *
- * @var int
- * @access private
- * @since Property available since Release 1.0
- */
- var $minute;
-
- /**
- * The no of seconds (0 to 59)
- *
- * @var int
- * @access private
- * @since Property available since Release 1.0
- */
- var $second;
-
-
- // }}}
- // {{{ Constructor
-
- /**
- * Constructor
- *
- * Creates the time span object calling the set() method.
- *
- * @param mixed $time time span expression
- * @param mixed $format format string to set it from a string or the
- * second date set it from a date diff
- *
- * @access public
- * @see set()
- */
- function Date_Span($time = 0, $format = null)
- {
- $this->set($time, $format);
- }
-
-
- // }}}
- // {{{ set()
-
- /**
- * Set the time span to a new value in a 'smart' way
- *
- * Sets the time span depending on the argument types, calling
- * to the appropriate setFromXxx() method.
- *
- * @param mixed $time time span expression
- * @param mixed $format format string to set it from a string or the
- * second date set it from a date diff
- *
- * @return bool true on success
- * @access public
- * @see setFromObject(), setFromArray(), setFromString(),
- * setFromSeconds(), setFromDateDiff()
- */
- function set($time = 0, $format = null)
- {
- if (is_a($time, 'date_span')) {
- return $this->copy($time);
- } elseif (is_a($time, 'date') and is_a($format, 'date')) {
- return $this->setFromDateDiff($time, $format);
- } elseif (is_array($time)) {
- return $this->setFromArray($time);
- } elseif (is_string($time)) {
- return $this->setFromString($time, $format);
- } elseif (is_int($time)) {
- return $this->setFromSeconds($time);
- } else {
- return $this->setFromSeconds(0);
- }
- }
-
-
- // }}}
- // {{{ setFromArray()
-
- /**
- * Set the time span from an array
- *
- * Any value can be a float (but it has no sense in seconds), for example:
- *
- * <code>array(23.5, 20, 0)</code>
- *
- * is interpreted as 23 hours, .5*60 + 20 = 50 minutes and 0 seconds.
- *
- * @param array $time items are counted from right to left. First
- * item is for seconds, second for minutes, third
- * for hours and fourth for days. If there are
- * less items than 4, zero (0) is assumed for the
- * absent values.
- *
- * @return bool true on success
- * @access public
- */
- function setFromArray($time)
- {
- if (!is_array($time)) {
- return false;
- }
- $tmp1 = new Date_Span;
- if (!$tmp1->setFromSeconds(@array_pop($time))) {
- return false;
- }
- $tmp2 = new Date_Span;
- if (!$tmp2->setFromMinutes(@array_pop($time))) {
- return false;
- }
- $tmp1->add($tmp2);
- if (!$tmp2->setFromHours(@array_pop($time))) {
- return false;
- }
- $tmp1->add($tmp2);
- if (!$tmp2->setFromDays(@array_pop($time))) {
- return false;
- }
- $tmp1->add($tmp2);
- return $this->copy($tmp1);
- }
-
-
- // }}}
- // {{{ setFromString()
-
- /**
- * Set the time span from a string based on an input format
- *
- * This is some like a mix of format() method and sscanf() PHP function.
- * The error checking and validation of this function is very primitive,
- * so you should be carefull when using it with unknown $time strings.
- * With this method you are assigning day, hour, minute and second
- * values, and the last values are used. This means that if you use
- * something like setFromString('10, 20', '%H, %h') your time span
- * would be 20 hours long. Allways remember that this method sets
- * <b>all</b> the values, so if you had a $time span 30 minutes long
- * and you make $time->setFromString('20 hours', '%H hours'), $time
- * span would be 20 hours long (and not 20 hours and 30 minutes).
- * Input format options:<br>
- * <code>%C</code> Days with time, same as "%D, %H:%M:%S"<br>
- * <code>%d</code> Total days as a float number
- * (2 days, 12 hours = 2.5 days)<br>
- * <code>%D</code> Days as a decimal number<br>
- * <code>%e</code> Total hours as a float number
- * (1 day, 2 hours, 30 minutes = 26.5 hours)<br>
- * <code>%f</code> Total minutes as a float number
- * (2 minutes, 30 seconds = 2.5 minutes)<br>
- * <code>%g</code> Total seconds as a decimal number
- * (2 minutes, 30 seconds = 90 seconds)<br>
- * <code>%h</code> Hours as decimal number<br>
- * <code>%H</code> Hours as decimal number limited to 2 digits<br>
- * <code>%m</code> Minutes as a decimal number<br>
- * <code>%M</code> Minutes as a decimal number limited to 2 digits<br>
- * <code>%n</code> Newline character (\n)<br>
- * <code>%p</code> Either 'am' or 'pm' depending on the time. If 'pm'
- * is detected it adds 12 hours to the resulting time
- * span (without any checks). This is case
- * insensitive.<br>
- * <code>%r</code> Time in am/pm notation, same as "%H:%M:%S %p"<br>
- * <code>%R</code> Time in 24-hour notation, same as "%H:%M"<br>
- * <code>%s</code> Seconds as a decimal number<br>
- * <code>%S</code> Seconds as a decimal number limited to 2 digits<br>
- * <code>%t</code> Tab character (\t)<br>
- * <code>%T</code> Current time equivalent, same as "%H:%M:%S"<br>
- * <code>%%</code> Literal '%'<br>
- *
- * @param string $time string from where to get the time span
- * information
- * @param string $format format string
- *
- * @return bool true on success
- * @access public
- */
- function setFromString($time, $format = null)
- {
- if (is_null($format)) {
- $format = $GLOBALS['_DATE_SPAN_INPUT_FORMAT'];
- }
- // If format is a string, it parses the string format.
- if (is_string($format)) {
- $str = '';
- $vars = array();
- $pm = 'am';
- $day = $hour = $minute = $second = 0;
- for ($i = 0; $i < strlen($format); $i++) {
- $char = $format{$i};
- if ($char == '%') {
- $nextchar = $format{++$i};
- switch ($nextchar) {
- case 'c':
- $str .= '%d, %d:%d:%d';
- array_push($vars,
- 'day',
- 'hour',
- 'minute',
- 'second');
- break;
- case 'C':
- $str .= '%d, %2d:%2d:%2d';
- array_push($vars,
- 'day',
- 'hour',
- 'minute',
- 'second');
- break;
- case 'd':
- $str .= '%f';
- array_push($vars, 'day');
- break;
- case 'D':
- $str .= '%d';
- array_push($vars, 'day');
- break;
- case 'e':
- $str .= '%f';
- array_push($vars, 'hour');
- break;
- case 'f':
- $str .= '%f';
- array_push($vars, 'minute');
- break;
- case 'g':
- $str .= '%f';
- array_push($vars, 'second');
- break;
- case 'h':
- $str .= '%d';
- array_push($vars, 'hour');
- break;
- case 'H':
- $str .= '%2d';
- array_push($vars, 'hour');
- break;
- case 'm':
- $str .= '%d';
- array_push($vars, 'minute');
- break;
- case 'M':
- $str .= '%2d';
- array_push($vars, 'minute');
- break;
- case 'n':
- $str .= "\n";
- break;
- case 'p':
- $str .= '%2s';
- array_push($vars, 'pm');
- break;
- case 'r':
- $str .= '%2d:%2d:%2d %2s';
- array_push($vars,
- 'hour',
- 'minute',
- 'second',
- 'pm');
- break;
- case 'R':
- $str .= '%2d:%2d';
- array_push($vars, 'hour', 'minute');
- break;
- case 's':
- $str .= '%d';
- array_push($vars, 'second');
- break;
- case 'S':
- $str .= '%2d';
- array_push($vars, 'second');
- break;
- case 't':
- $str .= "\t";
- break;
- case 'T':
- $str .= '%2d:%2d:%2d';
- array_push($vars, 'hour', 'minute', 'second');
- break;
- case '%':
- $str .= "%";
- break;
- default:
- $str .= $char . $nextchar;
- }
- } else {
- $str .= $char;
- }
- }
- $vals = sscanf($time, $str);
- foreach ($vals as $i => $val) {
- if (is_null($val)) {
- return false;
- }
- $$vars[$i] = $val;
- }
- if (strcasecmp($pm, 'pm') == 0) {
- $hour += 12;
- } elseif (strcasecmp($pm, 'am') != 0) {
- return false;
- }
- $this->setFromArray(array($day, $hour, $minute, $second));
- } elseif (is_integer($format)) {
- // If format is a integer, it uses a predefined format
- // detection method.
- switch ($format) {
- case DATE_SPAN_INPUT_FORMAT_NNSV:
- $time = preg_split('/\D+/', $time);
- switch (count($time)) {
- case 0:
- return $this->setFromArray(array(0,
- 0,
- 0,
- 0));
- case 1:
- return $this->setFromArray(array(0,
- $time[0],
- 0,
- 0));
- case 2:
- return $this->setFromArray(array(0,
- $time[0],
- $time[1],
- 0));
- case 3:
- return $this->setFromArray(array(0,
- $time[0],
- $time[1],
- $time[2]));
- default:
- return $this->setFromArray($time);
- }
- break;
- }
- }
- return false;
- }
-
-
- // }}}
- // {{{ setFromSeconds()
-
- /**
- * Set the time span from a total number of seconds
- *
- * @param int $seconds total number of seconds
- *
- * @return bool true on success
- * @access public
- */
- function setFromSeconds($seconds)
- {
- if ($seconds < 0) {
- return false;
- }
- $sec = intval($seconds);
- $min = floor($sec / 60);
- $hour = floor($min / 60);
- $day = intval(floor($hour / 24));
-
- $this->second = $sec % 60;
- $this->minute = $min % 60;
- $this->hour = $hour % 24;
- $this->day = $day;
- return true;
- }
-
-
- // }}}
- // {{{ setFromMinutes()
-
- /**
- * Set the time span from a total number of minutes
- *
- * @param float $minutes total number of minutes
- *
- * @return bool true on success
- * @access public
- */
- function setFromMinutes($minutes)
- {
- return $this->setFromSeconds(round($minutes * 60));
- }
-
-
- // }}}
- // {{{ setFromHours()
-
- /**
- * Set the time span from a total number of hours
- *
- * @param float $hours total number of hours
- *
- * @return bool true on success
- * @access public
- */
- function setFromHours($hours)
- {
- return $this->setFromSeconds(round($hours * 3600));
- }
-
-
- // }}}
- // {{{ setFromDays()
-
- /**
- * Set the time span from a total number of days
- *
- * @param float $days total number of days
- *
- * @return bool true on success
- * @access public
- */
- function setFromDays($days)
- {
- return $this->setFromSeconds(round($days * 86400));
- }
-
-
- // }}}
- // {{{ setFromDateDiff()
-
- /**
- * Set the span from the elapsed time between two dates
- *
- * The time span is unsigned, so the date's order is not important.
- *
- * @param object $date1 first Date
- * @param object $date2 second Date
- *
- * @return bool true on success
- * @access public
- */
- function setFromDateDiff($date1, $date2)
- {
- if (!is_a($date1, 'date') or !is_a($date2, 'date')) {
- return false;
- }
- $date1->toUTC();
- $date2->toUTC();
- if ($date1->after($date2)) {
- list($date1, $date2) = array($date2, $date1);
- }
- $days = Date_Calc::dateDiff($date1->getDay(),
- $date1->getMonth(),
- $date1->getYear(),
- $date2->getDay(),
- $date2->getMonth(),
- $date2->getYear());
- $hours = $date2->getHour() - $date1->getHour();
- $mins = $date2->getMinute() - $date1->getMinute();
- $secs = $date2->getSecond() - $date1->getSecond();
- $this->setFromSeconds($days * 86400 +
- $hours * 3600 +
- $mins * 60 + $secs);
- return true;
- }
-
-
- // }}}
- // {{{ copy()
-
- /**
- * Set the time span from another time object
- *
- * @param object $time source time span object
- *
- * @return bool true on success
- * @access public
- */
- function copy($time)
- {
- if (is_a($time, 'date_span')) {
- $this->second = $time->second;
- $this->minute = $time->minute;
- $this->hour = $time->hour;
- $this->day = $time->day;
- return true;
- } else {
- return false;
- }
- }
-
-
- // }}}
- // {{{ format()
-
- /**
- * Time span pretty printing (similar to Date::format())
- *
- * Formats the time span in the given format, similar to
- * strftime() and Date::format().<br>
- * <br>
- * Formatting options:<br>
- * <code>%C</code> Days with time, same as "%D, %H:%M:%S"<br>
- * <code>%d</code> Total days as a float number
- * (2 days, 12 hours = 2.5 days)<br>
- * <code>%D</code> Days as a decimal number<br>
- * <code>%e</code> Total hours as a float number
- * (1 day, 2 hours, 30 minutes = 26.5 hours)<br>
- * <code>%E</code> Total hours as a decimal number
- * (1 day, 2 hours, 40 minutes = 26 hours)<br>
- * <code>%f</code> Total minutes as a float number
- * (2 minutes, 30 seconds = 2.5 minutes)<br>
- * <code>%F</code> Total minutes as a decimal number
- * (1 hour, 2 minutes, 40 seconds = 62 minutes)<br>
- * <code>%g</code> Total seconds as a decimal number
- * (2 minutes, 30 seconds = 90 seconds)<br>
- * <code>%h</code> Hours as decimal number (0 to 23)<br>
- * <code>%H</code> Hours as decimal number (00 to 23)<br>
- * <code>%i</code> Hours as decimal number on 12-hour clock
- * (1 to 12)<br>
- * <code>%I</code> Hours as decimal number on 12-hour clock
- * (01 to 12)<br>
- * <code>%m</code> Minutes as a decimal number (0 to 59)<br>
- * <code>%M</code> Minutes as a decimal number (00 to 59)<br>
- * <code>%n</code> Newline character (\n)<br>
- * <code>%p</code> Either 'am' or 'pm' depending on the time<br>
- * <code>%P</code> Either 'AM' or 'PM' depending on the time<br>
- * <code>%r</code> Time in am/pm notation, same as "%I:%M:%S %p"<br>
- * <code>%R</code> Time in 24-hour notation, same as "%H:%M"<br>
- * <code>%s</code> Seconds as a decimal number (0 to 59)<br>
- * <code>%S</code> Seconds as a decimal number (00 to 59)<br>
- * <code>%t</code> Tab character (\t)<br>
- * <code>%T</code> Current time equivalent, same as "%H:%M:%S"<br>
- * <code>%%</code> Literal '%'<br>
- *
- * @param string $format the format string for returned time span
- *
- * @return string the time span in specified format
- * @access public
- */
- function format($format = null)
- {
- if (is_null($format)) {
- $format = $GLOBALS['_DATE_SPAN_FORMAT'];
- }
- $output = '';
- for ($i = 0; $i < strlen($format); $i++) {
- $char = $format{$i};
- if ($char == '%') {
- $nextchar = $format{++$i};
- switch ($nextchar) {
- case 'C':
- $output .= sprintf('%d, %02d:%02d:%02d',
- $this->day,
- $this->hour,
- $this->minute,
- $this->second);
- break;
- case 'd':
- $output .= $this->toDays();
- break;
- case 'D':
- $output .= $this->day;
- break;
- case 'e':
- $output .= $this->toHours();
- break;
- case 'E':
- $output .= floor($this->toHours());
- break;
- case 'f':
- $output .= $this->toMinutes();
- break;
- case 'F':
- $output .= floor($this->toMinutes());
- break;
- case 'g':
- $output .= $this->toSeconds();
- break;
- case 'h':
- $output .= $this->hour;
- break;
- case 'H':
- $output .= sprintf('%02d', $this->hour);
- break;
- case 'i':
- case 'I':
- $hour = $this->hour + 1 > 12 ?
- $this->hour - 12 :
- $this->hour;
- $output .= $hour == 0 ?
- 12 :
- ($nextchar == "i" ?
- $hour :
- sprintf('%02d', $hour));
- break;
- case 'm':
- $output .= $this->minute;
- break;
- case 'M':
- $output .= sprintf('%02d', $this->minute);
- break;
- case 'n':
- $output .= "\n";
- break;
- case 'p':
- $output .= $this->hour >= 12 ? 'pm' : 'am';
- break;
- case 'P':
- $output .= $this->hour >= 12 ? 'PM' : 'AM';
- break;
- case 'r':
- $hour = $this->hour + 1 > 12 ?
- $this->hour - 12 :
- $this->hour;
- $output .= sprintf('%02d:%02d:%02d %s',
- $hour == 0 ? 12 : $hour,
- $this->minute,
- $this->second,
- $this->hour >= 12 ? 'pm' : 'am');
- break;
- case 'R':
- $output .= sprintf('%02d:%02d',
- $this->hour,
- $this->minute);
- break;
- case 's':
- $output .= $this->second;
- break;
- case 'S':
- $output .= sprintf('%02d', $this->second);
- break;
- case 't':
- $output .= "\t";
- break;
- case 'T':
- $output .= sprintf('%02d:%02d:%02d',
- $this->hour,
- $this->minute,
- $this->second);
- break;
- case '%':
- $output .= "%";
- break;
- default:
- $output .= $char . $nextchar;
- }
- } else {
- $output .= $char;
- }
- }
- return $output;
- }
-
-
- // }}}
- // {{{ toSeconds()
-
- /**
- * Convert time span to seconds
- *
- * @return int time span as an integer number of seconds
- * @access public
- */
- function toSeconds()
- {
- return $this->day * 86400 + $this->hour * 3600 +
- $this->minute * 60 + $this->second;
- }
-
-
- // }}}
- // {{{ toMinutes()
-
- /**
- * Convert time span to minutes
- *
- * @return float time span as a decimal number of minutes
- * @access public
- */
- function toMinutes()
- {
- return $this->day * 1440 + $this->hour * 60 + $this->minute +
- $this->second / 60;
- }
-
-
- // }}}
- // {{{ toHours()
-
- /**
- * Convert time span to hours
- *
- * @return float time span as a decimal number of hours
- * @access public
- */
- function toHours()
- {
- return $this->day * 24 + $this->hour + $this->minute / 60 +
- $this->second / 3600;
- }
-
-
- // }}}
- // {{{ toDays()
-
- /**
- * Convert time span to days
- *
- * @return float time span as a decimal number of days
- * @access public
- */
- function toDays()
- {
- return $this->day + $this->hour / 24 + $this->minute / 1440 +
- $this->second / 86400;
- }
-
-
- // }}}
- // {{{ add()
-
- /**
- * Adds a time span
- *
- * @param object $time time span to add
- *
- * @return void
- * @access public
- */
- function add($time)
- {
- return $this->setFromSeconds($this->toSeconds() +
- $time->toSeconds());
- }
-
-
- // }}}
- // {{{ subtract()
-
- /**
- * Subtracts a time span
- *
- * If the time span to subtract is larger than the original, the result
- * is zero (there's no sense in negative time spans).
- *
- * @param object $time time span to subtract
- *
- * @return void
- * @access public
- */
- function subtract($time)
- {
- $sub = $this->toSeconds() - $time->toSeconds();
- if ($sub < 0) {
- $this->setFromSeconds(0);
- } else {
- $this->setFromSeconds($sub);
- }
- }
-
-
- // }}}
- // {{{ equal()
-
- /**
- * Tells if time span is equal to $time
- *
- * @param object $time time span to compare to
- *
- * @return bool true if the time spans are equal
- * @access public
- */
- function equal($time)
- {
- return $this->toSeconds() == $time->toSeconds();
- }
-
-
- // }}}
- // {{{ greaterEqual()
-
- /**
- * Tells if this time span is greater or equal than $time
- *
- * @param object $time time span to compare to
- *
- * @return bool true if this time span is greater or equal than $time
- * @access public
- */
- function greaterEqual($time)
- {
- return $this->toSeconds() >= $time->toSeconds();
- }
-
-
- // }}}
- // {{{ lowerEqual()
-
- /**
- * Tells if this time span is lower or equal than $time
- *
- * @param object $time time span to compare to
- *
- * @return bool true if this time span is lower or equal than $time
- * @access public
- */
- function lowerEqual($time)
- {
- return $this->toSeconds() <= $time->toSeconds();
- }
-
-
- // }}}
- // {{{ greater()
-
- /**
- * Tells if this time span is greater than $time
- *
- * @param object $time time span to compare to
- *
- * @return bool true if this time span is greater than $time
- * @access public
- */
- function greater($time)
- {
- return $this->toSeconds() > $time->toSeconds();
- }
-
-
- // }}}
- // {{{ lower()
-
- /**
- * Tells if this time span is lower than $time
- *
- * @param object $time time span to compare to
- *
- * @return bool true if this time span is lower than $time
- * @access public
- */
- function lower($time)
- {
- return $this->toSeconds() < $time->toSeconds();
- }
-
-
- // }}}
- // {{{ compare()
-
- /**
- * Compares two time spans
- *
- * Suitable for use in sorting functions.
- *
- * @param object $time1 the first time span
- * @param object $time2 the second time span
- *
- * @return int 0 if the time spans are equal, -1 if time1 is lower
- * than time2, 1 if time1 is greater than time2
- * @access public
- * @static
- */
- function compare($time1, $time2)
- {
- if ($time1->equal($time2)) {
- return 0;
- } elseif ($time1->lower($time2)) {
- return -1;
- } else {
- return 1;
- }
- }
-
-
- // }}}
- // {{{ isEmpty()
-
- /**
- * Tells if the time span is empty (zero length)
- *
- * @return bool true if empty
- * @access public
- */
- function isEmpty()
- {
- return !$this->day && !$this->hour && !$this->minute && !$this->second;
- }
-
-
- // }}}
- // {{{ setDefaultInputFormat()
-
- /**
- * Set the default input format
- *
- * @param mixed $format new default input format
- *
- * @return mixed previous default input format
- * @access public
- * @static
- */
- function setDefaultInputFormat($format)
- {
- $old = $GLOBALS['_DATE_SPAN_INPUT_FORMAT'];
- $GLOBALS['_DATE_SPAN_INPUT_FORMAT'] = $format;
- return $old;
- }
-
-
- // }}}
- // {{{ getDefaultInputFormat()
-
- /**
- * Get the default input format
- *
- * @return mixed default input format
- * @access public
- * @static
- */
- function getDefaultInputFormat()
- {
- return $GLOBALS['_DATE_SPAN_INPUT_FORMAT'];
- }
-
-
- // }}}
- // {{{ setDefaultFormat()
-
- /**
- * Set the default format
- *
- * @param mixed $format new default format
- *
- * @return mixed previous default format
- * @access public
- * @static
- */
- function setDefaultFormat($format)
- {
- $old = $GLOBALS['_DATE_SPAN_FORMAT'];
- $GLOBALS['_DATE_SPAN_FORMAT'] = $format;
- return $old;
- }
-
-
- // }}}
- // {{{ getDefaultFormat()
-
- /**
- * Get the default format
- *
- * @return mixed default format
- * @access public
- * @static
- */
- function getDefaultFormat()
- {
- return $GLOBALS['_DATE_SPAN_FORMAT'];
- }
-
-
- // }}}
-
-}
-
-// }}}
-
-/*
- * Local variables:
- * mode: php
- * tab-width: 4
- * c-basic-offset: 4
- * c-hanging-comment-ender-p: nil
- * End:
- */
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */
-
-
-// {{{ Header
-
-/**
- * TimeZone representation class, along with time zone information data
- *
- * PHP versions 4 and 5
- *
- * LICENSE:
- *
- * Copyright (c) 1997-2007 Baba Buehler, Pierre-Alain Joye, C.A. Woodcock
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted under the terms of the BSD License.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
- * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
- * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- *
- * @category Date and Time
- * @package Date
- * @author Baba Buehler <baba@babaz.com>
- * @author Pierre-Alain Joye <pajoye@php.net>
- * @author C.A. Woodcock <c01234@netcomuk.co.uk>
- * @copyright 1997-2007 Baba Buehler, Pierre-Alain Joye, C.A. Woodcock
- * @license http://www.opensource.org/licenses/bsd-license.php
- * BSD License
- * @version CVS: $Id: TimeZone.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- * @link http://pear.php.net/package/Date
- */
-
-
-// }}}
-// {{{ Class Date_TimeZone
-
-/**
- * TimeZone representation class, along with time zone information data
- *
- * The default timezone is set from the first valid timezone id found
- * in one of the following places, in this order:
- * + global $_DATE_TIMEZONE_DEFAULT
- * + system environment variable PHP_TZ
- * + system environment variable TZ
- * + the result of date('T')
- *
- * If no valid timezone id is found, the default timezone is set to 'UTC'.
- * You may also manually set the default timezone by passing a valid id to
- * Date_TimeZone::setDefault().
- *
- * This class includes time zone data (from zoneinfo) in the form of a
- * global array, $_DATE_TIMEZONE_DATA.
- *
- * @category Date and Time
- * @package Date
- * @author Baba Buehler <baba@babaz.com>
- * @author C.A. Woodcock <c01234@netcomuk.co.uk>
- * @copyright 1997-2007 Baba Buehler, Pierre-Alain Joye, C.A. Woodcock
- * @license http://www.opensource.org/licenses/bsd-license.php
- * BSD License
- * @version Release: 1.5.0a1
- * @link http://pear.php.net/package/Date
- */
-class Date_TimeZone
-{
-
- // {{{ Properties
-
- /**
- * Unique time Zone ID of this time zone
- *
- * @var string
- * @access private
- * @since Property available since Release 1.0
- */
- var $id;
-
- /**
- * Offset, in milliseconds, of this timezone
- *
- * @var int
- * @access private
- * @since Property available since Release 1.0
- */
- var $offset;
-
- /**
- * Short name of this time zone (e.g. "CST")
- *
- * @var string
- * @access private
- * @since Property available since Release 1.0
- */
- var $shortname;
-
- /**
- * DST short name of this timezone (e.g. 'BST')
- *
- * @var string
- * @access private
- * @since Property available since Release 1.0
- */
- var $dstshortname;
-
- /**
- * Long name of this time zone (e.g. "Central Standard Time")
- *
- * N.B. this is not necessarily unique
- *
- * @since 1.0
- * @access private
- * @since Property available since Release 1.0
- */
- var $longname;
-
- /**
- * DST long name of this time zone (e.g. 'British Summer Time')
- *
- * @var string
- * @access private
- * @since Property available since Release 1.0
- */
- var $dstlongname;
-
- /**
- * Whether this time zone observes daylight savings time
- *
- * @var bool
- * @access private
- * @since Property available since Release 1.0
- */
- var $hasdst;
-
- /**
- * Additional offset of Summer time from the standard time of the
- * time zone in milli-seconds
- *
- * The value is usually 3600000, i.e. one hour, and always positive
- *
- * @var int
- * @access private
- * @since Property available since Release 1.5.0
- */
- var $on_summertimeoffset;
-
- /**
- * Month no (1-12) in which Summer time starts (the clocks go forward)
- *
- * @var int
- * @access private
- * @since Property available since Release 1.5.0
- */
- var $on_summertimestartmonth;
-
- /**
- * Definition of when Summer time starts in the specified month
- *
- * Can take one of the following forms:
- *
- * 5 the fifth of the month
- * lastSun the last Sunday in the month
- * lastMon the last Monday in the month
- * Sun>=8 first Sunday on or after the 8th
- * Sun<=25 last Sunday on or before the 25th
- *
- * @var string
- * @access private
- * @since Property available since Release 1.5.0
- */
- var $os_summertimestartday;
-
- /**
- * Time in milli-seconds relative to midnight UTC when
- * Summer time starts (the clocks go forward)
- *
- * @var int
- * @access private
- * @since Property available since Release 1.5.0
- */
- var $on_summertimestarttime;
-
- /**
- * Month no (1-12) in which Summer time ends (the clocks go back)
- *
- * @var int
- * @access private
- * @since Property available since Release 1.5.0
- */
- var $on_summertimeendmonth;
-
- /**
- * Definition of when Summer time ends in the specified month
- *
- * @var string
- * @access private
- * @see Date_TimeZone::$os_summertimestartday
- * @since Property available since Release 1.5.0
- */
- var $os_summertimeendday;
-
- /**
- * Time in milli-seconds relative to midnight UTC when
- * Summer time ends (the clocks go back)
- *
- * @var int
- * @access private
- * @since Property available since Release 1.5.0
- */
- var $on_summertimeendtime;
-
-
- // }}}
- // {{{ Constructor
-
- /**
- * Constructor
- *
- * Creates a new Date::TimeZone object, representing the time zone
- * specified in $id.
- *
- * If the supplied ID is invalid, the created time zone is "UTC".
- *
- * A note about time zones of the form 'Etc/*' (quoted from the public
- * domain 'tz' data-base (see ftp://elsie.nci.nih.gov/pub/tzdata2007i.tar.gz
- * [file 'etcetera']):
- *
- * These entries are mostly present for historical reasons, so that
- * people in areas not otherwise covered by the tz files could use
- * a time zone that was right for their area. These days, the
- * tz files cover almost all the inhabited world, and the only practical
- * need now for the entries that are not on UTC are for ships at sea
- * that cannot use POSIX TZ settings.
- *
- * Etc/GMT (GMT)
- * Etc/UTC (UTC)
- * Etc/UCT (UCT)
- *
- * The following link uses older naming conventions, but it belongs here.
- * We want this to work even on installations that omit the other older
- * names.
- *
- * Etc/GMT (equivalent to GMT)
- *
- * Etc/UTC (equivalent to Etc/Universal)
- * Etc/UTC (equivalent to Etc/Zulu)
- *
- * Etc/GMT (equivalent to Etc/Greenwich)
- * Etc/GMT (equivalent to Etc/GMT-0)
- * Etc/GMT (equivalent to Etc/GMT+0)
- * Etc/GMT (equivalent to Etc/GMT0)
- *
- * We use POSIX-style signs in the Zone names and the output abbreviations,
- * even though this is the opposite of what many people expect.
- * POSIX has positive signs west of Greenwich, but many people expect
- * positive signs east of Greenwich. For example, TZ='Etc/GMT+4' uses
- * the abbreviation "GMT+4" and corresponds to 4 hours behind UTC
- * (i.e. west of Greenwich) even though many people would expect it to
- * mean 4 hours ahead of UTC (i.e. east of Greenwich).
- *
- * In the draft 5 of POSIX 1003.1-200x, the angle bracket notation
- * (which is not yet supported by the tz code) allows for
- * TZ='<GMT-4>+4'; if you want time zone abbreviations conforming to
- * ISO 8601 you can use TZ='<-0400>+4'. Thus the commonly-expected
- * offset is kept within the angle bracket (and is used for display)
- * while the POSIX sign is kept outside the angle bracket (and is used
- * for calculation).
- *
- * Do not use a TZ setting like TZ='GMT+4', which is four hours behind
- * GMT but uses the completely misleading abbreviation "GMT".
- *
- * Earlier incarnations of this package were not POSIX-compliant, and
- * we did not want things to change quietly if someone accustomed to the
- * old way uses the codes from previous versions so we moved the names
- * into the Etc subdirectory.
- *
- * Etc/GMT-14 (14 hours ahead of Greenwich)
- * Etc/GMT-13 (13)
- * Etc/GMT-12 (12)
- * Etc/GMT-11 (11)
- * Etc/GMT-10 (10)
- * Etc/GMT-9 (9)
- * Etc/GMT-8 (8)
- * Etc/GMT-7 (7)
- * Etc/GMT-6 (6)
- * Etc/GMT-5 (5)
- * Etc/GMT-4 (4)
- * Etc/GMT-3 (3)
- * Etc/GMT-2 (2)
- * Etc/GMT-1 (1)
- * Etc/GMT+1 (1 hour behind Greenwich)
- * Etc/GMT+2 (2)
- * Etc/GMT+3 (3)
- * Etc/GMT+4 (4)
- * Etc/GMT+5 (5)
- * Etc/GMT+6 (6)
- * Etc/GMT+7 (7)
- * Etc/GMT+8 (8)
- * Etc/GMT+9 (9)
- * Etc/GMT+10 (10)
- * Etc/GMT+11 (11)
- * Etc/GMT+12 (12)
- *
- * @param string $ps_id the time zone ID
- *
- * @return void
- * @access public
- * @see Date::setTZByID(), Date_TimeZone::isValidID()
- */
- function Date_TimeZone($ps_id)
- {
- $_DATE_TIMEZONE_DATA =& $GLOBALS['_DATE_TIMEZONE_DATA'];
-
- if (isset($GLOBALS['_DATE_TIMEZONE_DATA'][$ps_id])) {
- $this->id = $ps_id;
-
- $this->shortname = $_DATE_TIMEZONE_DATA[$ps_id]['shortname'];
- $this->longname = $_DATE_TIMEZONE_DATA[$ps_id]['longname'];
- $this->offset = $_DATE_TIMEZONE_DATA[$ps_id]['offset'];
- $this->dstshortname =
- array_key_exists("dstshortname",
- $_DATE_TIMEZONE_DATA[$ps_id]) ?
- $_DATE_TIMEZONE_DATA[$ps_id]['dstshortname'] :
- null;
- if ($this->hasdst = !is_null($this->dstshortname)) {
- $this->dstlongname =
- array_key_exists("dstlongname",
- $_DATE_TIMEZONE_DATA[$ps_id]) ?
- $_DATE_TIMEZONE_DATA[$ps_id]['dstlongname'] :
- null;
- if (isset($_DATE_TIMEZONE_DATA[$ps_id]["summertimeoffset"])) {
- $this->on_summertimeoffset = $_DATE_TIMEZONE_DATA[$ps_id]["summertimeoffset"];
- $this->on_summertimestartmonth = $_DATE_TIMEZONE_DATA[$ps_id]["summertimestartmonth"];
- $this->os_summertimestartday = $_DATE_TIMEZONE_DATA[$ps_id]["summertimestartday"];
- $this->on_summertimestarttime = $_DATE_TIMEZONE_DATA[$ps_id]["summertimestarttime"];
- $this->on_summertimeendmonth = $_DATE_TIMEZONE_DATA[$ps_id]["summertimeendmonth"];
- $this->os_summertimeendday = $_DATE_TIMEZONE_DATA[$ps_id]["summertimeendday"];
- $this->on_summertimeendtime = $_DATE_TIMEZONE_DATA[$ps_id]["summertimeendtime"];
- } else {
- $this->on_summertimeoffset = null;
- }
- }
- } else {
- $this->hasdst = false;
-
- if (preg_match('/^UTC([+\-])([0-9]{2,2}):?([0-5][0-9])$/',
- $ps_id,
- $ha_matches)) {
- $this->id = $ps_id;
- $this->offset = ($ha_matches[1] .
- ($ha_matches[2] * 3600 +
- $ha_matches[3] * 60)) * 1000;
-
- if (!($hb_isutc = $this->offset == 0)) {
- $this->id = $ps_id;
- $this->shortname = "UTC" .
- $ha_matches[1] .
- ($ha_matches[3] == "00" ?
- ltrim($ha_matches[2], "0") :
- $ha_matches[2] . $ha_matches[3]);
- $this->longname = "UTC" .
- $ha_matches[1] .
- $ha_matches[2] .
- ":" .
- $ha_matches[3];
- }
- } else if (preg_match('/^UTC([+\-])([0-9]{1,2})$/',
- $ps_id,
- $ha_matches)) {
- $this->id = $ps_id;
- $this->offset = ($ha_matches[1] .
- ($ha_matches[2] * 3600)) * 1000;
-
- if (!($hb_isutc = $this->offset == 0)) {
- $this->shortname = "UTC" .
- $ha_matches[1] .
- ltrim($ha_matches[2], "0");
- $this->longname = "UTC" .
- $ha_matches[1] .
- sprintf("%02d", $ha_matches[2]) .
- ":00";
- }
- } else {
- $this->id = "UTC";
- $hb_isutc = true;
- }
-
- if ($hb_isutc) {
- $this->shortname = $_DATE_TIMEZONE_DATA["UTC"]['shortname'];
- $this->longname = $_DATE_TIMEZONE_DATA["UTC"]['longname'];
- $this->offset = $_DATE_TIMEZONE_DATA["UTC"]['offset'];
- }
- }
- }
-
-
- // }}}
- // {{{ getDefault()
-
- /**
- * Returns a TimeZone object representing the system default time zone
- *
- * The system default time zone is initialized during the loading of
- * this file.
- *
- * @return object Date_TimeZone object of the default time zone
- * @access public
- */
- function getDefault()
- {
- return new Date_TimeZone($GLOBALS['_DATE_TIMEZONE_DEFAULT']);
- }
-
-
- // }}}
- // {{{ setDefault()
-
- /**
- * Sets the system default time zone to the time zone in $id
- *
- * @param string $id the time zone id to use
- *
- * @return void
- * @access public
- */
- function setDefault($id)
- {
- if (Date_TimeZone::isValidID($id)) {
- $GLOBALS['_DATE_TIMEZONE_DEFAULT'] = $id;
- } else {
- return PEAR::raiseError("Invalid time zone ID '$id'");
- }
- }
-
-
- // }}}
- // {{{ isValidID()
-
- /**
- * Tests if given time zone ID (e.g. 'London/Europe') is valid and unique
- *
- * Checks if given ID is either represented in the $_DATE_TIMEZONE_DATA
- * time zone data, or is a UTC offset in one of the following forms,
- * i.e. an offset with no geographical or political base:
- *
- * UTC[+/-][hh]:[mm] - e.g. UTC+03:00
- * UTC[+/-][hh][mm] - e.g. UTC-0530
- * UTC[+/-][hh] - e.g. UTC+03
- * UTC[+/-][h] - e.g. UTC-1 (the last is not ISO 8601
- * standard but is the preferred
- * form)
- *
- * N.B. these are not sanctioned by any ISO standard, but the form of
- * the offset itself, i.e. the part after the characters 'UTC', is the
- * ISO 8601 standard form for representing this part.
- *
- * The form '[+/-][h]' is not ISO conformant, but ISO 8601 only
- * defines the form of the time zone offset of a particular time, that
- * is, it actually defines the form '<time>UTC[+/-][hh]', and its
- * purview does not apparently cover the name of the time zone itself.
- * For this there is no official international standard (or even a non-
- * international standard). The closest thing to a sanctioning body
- * is the 'tz' database (http://www.twinsun.com/tz/tz-link.htm) which
- * is run by volunteers but which is heavily relied upon by various
- * programming languages and the internet community. However they
- * mainly define geographical/political time zone names of the
- * form 'London/Europe' because their main aim is to collate the time
- * zone definitions which are set by individual countries/states, not
- * to prescribe any standard.
- *
- * However it seems that the de facto standard to describe time zones
- * as non-geographically/politically-based areas where the local time
- * on all clocks reads the same seems to be the form 'UTC[+/-][h]'
- * for integral numbers of hours, and 'UTC[+/-][hh]:[mm]' otherwise.
- * (See http://en.wikipedia.org/wiki/List_of_time_zones)
- *
- * N.B. 'GMT' is also commonly used instead of 'UTC', but 'UTC' seems
- * to be technically preferred. GMT-based IDs still exist in the 'tz
- * data-base', but beware of POSIX-style offsets which are the opposite
- * way round to what people normally expect.
- *
- * @param string $ps_id the time zone ID to test
- *
- * @return bool true if the supplied ID is valid
- * @access public
- * @see Date::setTZByID(), Date_TimeZone::Date_TimeZone()
- */
- function isValidID($ps_id)
- {
- if (isset($GLOBALS['_DATE_TIMEZONE_DATA'][$ps_id])) {
- return true;
- } else if (preg_match('/^UTC[+\-]([0-9]{2,2}:?[0-5][0-9]|[0-9]{1,2})$/',
- $ps_id)) {
- return true;
- } else {
- return false;
- }
- }
-
-
- // }}}
- // {{{ isEqual()
-
- /**
- * Is this time zone equal to another
- *
- * Tests to see if this time zone is equal (ids match)
- * to a given Date_TimeZone object.
- *
- * @param object $tz the Date_TimeZone object to test
- *
- * @return bool true if this time zone is equal to the supplied
- * time zone
- * @access public
- */
- function isEqual($tz)
- {
- if (strcasecmp($this->id, $tz->id) == 0) {
- return true;
- } else {
- return false;
- }
- }
-
-
- // }}}
- // {{{ isEquivalent()
-
- /**
- * Is this time zone equivalent to another
- *
- * Tests to see if this time zone is equivalent to a given time zone object.
- * Equivalence in this context consists in the two time zones having:
- *
- * an equal offset from UTC in both standard and Summer time (if
- * the time zones observe Summer time)
- * the same Summer time start and end rules, that is, the two time zones
- * must switch from standard time to Summer time, and vice versa, on the
- * same day and at the same time
- *
- * @param object $pm_tz the Date_TimeZone object to test, or a valid time
- * zone ID
- *
- * @return bool true if this time zone is equivalent to the supplied
- * time zone
- * @access public
- */
- function isEquivalent($pm_tz)
- {
- if (is_a($pm_tz, "Date_TimeZone")) {
- if ($pm_tz->getID() == $this->id) {
- return true;
- }
- } else {
- if (!Date_TimeZone::isValidID($pm_tz)) {
- return PEAR::raiseError("Invalid time zone ID '$pm_tz'",
- DATE_ERROR_INVALIDTIMEZONE);
- }
- if ($pm_tz == $this->id)
- return true;
-
- $pm_tz = new Date_TimeZone($pm_tz);
- }
-
- if ($this->getRawOffset() == $pm_tz->getRawOffset() &&
- $this->hasDaylightTime() == $pm_tz->hasDaylightTime() &&
- $this->getDSTSavings() == $pm_tz->getDSTSavings() &&
- $this->getSummerTimeStartMonth() == $pm_tz->getSummerTimeStartMonth() &&
- $this->getSummerTimeStartDay() == $pm_tz->getSummerTimeStartDay() &&
- $this->getSummerTimeStartTime() == $pm_tz->getSummerTimeStartTime() &&
- $this->getSummerTimeEndMonth() == $pm_tz->getSummerTimeEndMonth() &&
- $this->getSummerTimeEndDay() == $pm_tz->getSummerTimeEndDay() &&
- $this->getSummerTimeEndTime() == $pm_tz->getSummerTimeEndTime()
- ) {
- return true;
- } else {
- return false;
- }
- }
-
-
- // }}}
- // {{{ hasDaylightTime()
-
- /**
- * Returns true if this zone observes daylight savings time
- *
- * @return bool true if this time zone has DST
- * @access public
- */
- function hasDaylightTime()
- {
- return $this->hasdst;
- }
-
-
- // }}}
- // {{{ getSummerTimeLimitDay()
-
- /**
- * Returns day on which Summer time starts or ends for given year
- *
- * The limit (start or end) code can take the following forms:
- * 5 the fifth of the month
- * lastSun the last Sunday in the month
- * lastMon the last Monday in the month
- * Sun>=8 first Sunday on or after the 8th
- * Sun<=25 last Sunday on or before the 25th
- *
- * @param string $ps_summertimelimitcode code which specifies Summer time
- * limit day
- * @param int $pn_month start or end month
- * @param int $pn_year year for which to calculate Summer
- * time limit day
- *
- * @return int
- * @access private
- * @since Method available since Release 1.5.0
- */
- function getSummerTimeLimitDay($ps_summertimelimitcode, $pn_month, $pn_year)
- {
- if (preg_match('/^[0-9]+$/', $ps_summertimelimitcode)) {
- $hn_day = $ps_summertimelimitcode;
- } else {
- if (!isset($ha_daysofweek))
- static $ha_daysofweek = array("Sun" => 0,
- "Mon" => 1,
- "Tue" => 2,
- "Wed" => 3,
- "Thu" => 4,
- "Fri" => 5,
- "Sat" => 6);
-
- if (preg_match('/^last(Sun|Mon|Tue|Wed|Thu|Fri|Sat)$/',
- $ps_summertimelimitcode,
- $ha_matches)) {
- list($hn_nmyear, $hn_nextmonth, $hn_nmday) =
- explode(" ", Date_Calc::beginOfMonthBySpan(1,
- $pn_month,
- $pn_year,
- "%Y %m %d"));
- list($hn_year, $hn_month, $hn_day) =
- explode(" ",
- Date_Calc::prevDayOfWeek($ha_daysofweek[$ha_matches[1]],
- $hn_nmday,
- $hn_nextmonth,
- $hn_nmyear,
- "%Y %m %d",
- false)); // not including
- // this day
-
- if ($hn_month != $pn_month) {
- // This code happen legitimately if the calendar jumped some days
- // e.g. in a calendar switch, or the limit day is badly defined:
- //
- $hn_day = Date_Calc::getFirstDayOfMonth($pn_month, $pn_year);
- }
- } else if (preg_match('/^(Sun|Mon|Tue|Wed|Thu|Fri|Sat)([><]=)([0-9]+)$/',
- $ps_summertimelimitcode,
- $ha_matches)) {
- if ($ha_matches[2] == "<=") {
- list($hn_year, $hn_month, $hn_day) =
- explode(" ",
- Date_Calc::prevDayOfWeek($ha_daysofweek[$ha_matches[1]],
- $ha_matches[3],
- $pn_month,
- $pn_year,
- "%Y %m %d",
- true)); // including
- // this day
-
- if ($hn_month != $pn_month) {
- $hn_day = Date_Calc::getFirstDayOfMonth($pn_month, $pn_year);
- }
- } else {
- list($hn_year, $hn_month, $hn_day) =
- explode(" ",
- Date_Calc::nextDayOfWeek($ha_daysofweek[$ha_matches[1]],
- $ha_matches[3],
- $pn_month,
- $pn_year,
- "%Y %m %d",
- true)); // including
- // this day
-
- if ($hn_month != $pn_month) {
- $hn_day = Date_Calc::daysInMonth($pn_month, $pn_year);
- }
- }
- }
- }
-
- return $hn_day;
- }
-
-
- // }}}
- // {{{ inDaylightTime()
-
- /**
- * Is the given date/time in DST for this time zone
- *
- * Works for all years, positive and negative. Possible problems
- * are that when the clocks go forward, there is an invalid hour
- * which is skipped. If a time in this hour is specified, this
- * function returns an error. When the clocks go back, there is an
- * hour which is repeated, that is, the hour is gone through twice -
- * once in Summer time and once in standard time. If this time
- * is specified, then this function returns '$pb_repeatedhourdefault',
- * because there is no way of knowing which is correct, and
- * both possibilities are equally likely.
- *
- * Also bear in mind that the clocks go forward at the instant of
- * the hour specified in the time-zone array below, and if this
- * exact hour is specified then the clocks have actually changed,
- * and this function reflects this.
- *
- * @param object $pm_date Date object to test or array of
- * day, month, year, seconds past
- * midnight
- * @param bool $pb_repeatedhourdefault value to return if repeated hour is
- * specified (defaults to false)
- *
- * @return bool true if this date is in Summer time for this time
- * zone
- * @access public
- */
- function inDaylightTime($pm_date, $pb_repeatedhourdefault = false)
- {
- if (!$this->hasdst) {
- return false;
- }
-
- if (is_a($pm_date, "Date")) {
- $hn_day = $pm_date->getDay();
- $hn_month = $pm_date->getMonth();
- $hn_year = $pm_date->getYear();
- $hn_seconds = $pm_date->getSecondsPastMidnight();
- } else {
- $hn_day = $pm_date[0];
- $hn_month = $pm_date[1];
- $hn_year = $pm_date[2];
- $hn_seconds = $pm_date[3]; // seconds past midnight
- }
-
- if (($this->on_summertimestartmonth < $this->on_summertimeendmonth &&
- $hn_month >= $this->on_summertimestartmonth &&
- $hn_month <= $this->on_summertimeendmonth) ||
- ($this->on_summertimestartmonth > $this->on_summertimeendmonth &&
- $hn_month >= $this->on_summertimestartmonth &&
- $hn_month <= $this->on_summertimeendmonth)
- ) {
-
- if ($hn_month == $this->on_summertimestartmonth) {
- $hn_startday =
- $this->getSummerTimeLimitDay($this->os_summertimestartday,
- $this->on_summertimestartmonth,
- $hn_year);
-
- if ($hn_day < $hn_startday) {
- return false;
- } else if ($hn_day > $hn_startday) {
- return true;
- } else if (($hn_gmt = $hn_seconds * 1000 - $this->offset) -
- $this->on_summertimeoffset >=
- $this->on_summertimestarttime) {
- return true;
- } else if (($hn_gmt = $hn_seconds * 1000 - $this->offset) >=
- $this->on_summertimestarttime) {
- return PEAR::raiseError("Invalid time specified for date '" .
- Date_Calc::dateFormat($hn_day,
- $hn_month,
- $hn_year,
- "%Y-%m-%d") .
- "'",
- DATE_ERROR_INVALIDTIME);
- } else {
- return false;
- }
- } else if ($hn_month == $this->on_summertimeendmonth) {
- $hn_endday =
- $this->getSummerTimeLimitDay($this->os_summertimeendday,
- $this->on_summertimeendmonth,
- $hn_year);
-
- if ($hn_day < $hn_endday) {
- return true;
- } else if ($hn_day > $hn_endday) {
- return false;
- } else if (($hn_gmt = $hn_seconds * 1000 - $this->offset) -
- $this->on_summertimeoffset >=
- $this->on_summertimeendtime) {
- return false;
- } else if ($hn_gmt >= $this->on_summertimeendtime) {
- // There is a 50:50 chance that it's Summer time, but there
- // is no way of knowing (the hour is repeated), so return
- // default:
- //
- return $pb_repeatedhourdefault;
- } else {
- return true;
- }
- }
-
- return true;
- }
-
- return false;
- }
-
-
- // }}}
- // {{{ inDaylightTimeStandard()
-
- /**
- * Returns whether the given date/time in local standard time is
- * in Summer time
- *
- * For example, if the clocks go forward at 1.00 standard time,
- * then if the specified date/time is at 1.00, the function will
- * return true, although the correct local time will actually
- * be 2.00.
- *
- * This function is reliable for all dates and times, unlike the
- * related function 'inDaylightTime()', which will fail if passed
- * an invalid time (the skipped hour) and will be wrong half the
- * time if passed an ambiguous time (the repeated hour).
- *
- * @param object $pm_date Date object to test or array of day, month, year,
- * seconds past midnight
- *
- * @return bool true if this date is in Summer time for this time
- * zone
- * @access public
- * @since Method available since Release 1.5.0
- */
- function inDaylightTimeStandard($pm_date)
- {
- if (!$this->hasdst) {
- return false;
- }
-
- if (is_a($pm_date, "Date")) {
- $hn_day = $pm_date->getDay();
- $hn_month = $pm_date->getMonth();
- $hn_year = $pm_date->getYear();
- $hn_seconds = $pm_date->getSecondsPastMidnight();
- } else {
- $hn_day = $pm_date[0];
- $hn_month = $pm_date[1];
- $hn_year = $pm_date[2];
- $hn_seconds = $pm_date[3];
- }
-
- if (($this->on_summertimestartmonth < $this->on_summertimeendmonth &&
- $hn_month >= $this->on_summertimestartmonth &&
- $hn_month <= $this->on_summertimeendmonth) ||
- ($this->on_summertimestartmonth > $this->on_summertimeendmonth &&
- $hn_month >= $this->on_summertimestartmonth &&
- $hn_month <= $this->on_summertimeendmonth)
- ) {
-
- if ($hn_month == $this->on_summertimestartmonth) {
- $hn_startday =
- $this->getSummerTimeLimitDay($this->os_summertimestartday,
- $this->on_summertimestartmonth,
- $hn_year);
-
- if ($hn_day < $hn_startday) {
- return false;
- } else if ($hn_day > $hn_startday) {
- return true;
- } else if ($hn_seconds * 1000 - $this->offset >=
- $this->on_summertimestarttime) {
- return true;
- } else {
- return false;
- }
- } else if ($hn_month == $this->on_summertimeendmonth) {
- $hn_endday =
- $this->getSummerTimeLimitDay($this->os_summertimeendday,
- $this->on_summertimeendmonth,
- $hn_year);
-
- if ($hn_day < $hn_endday) {
- return true;
- } else if ($hn_day > $hn_endday) {
- return false;
- } else if ($hn_seconds * 1000 - $this->offset >=
- $this->on_summertimeendtime) {
- return false;
- } else {
- return true;
- }
- }
-
- return true;
- }
-
- return false;
- }
-
-
- // }}}
- // {{{ getDSTSavings()
-
- /**
- * Get the DST offset for this time zone
- *
- * Returns the DST offset of this time zone, in milliseconds,
- * if the zone observes DST, zero otherwise. Currently the
- * DST offset is hard-coded to one hour.
- *
- * @return int the DST offset, in milliseconds or nought if the
- * zone does not observe DST
- * @access public
- */
- function getDSTSavings()
- {
- if ($this->hasdst) {
- // If offset is not specified, guess one hour. (This is almost
- // always correct anyway). This cannot be improved upon, because
- // where it is unset, the offset is either unknowable because the
- // time-zone covers more than one political area (which may have
- // different Summer time policies), or they might all have the
- // same policy, but there is no way to automatically maintain
- // this data at the moment, and manually it is simply not worth
- // the bother. If a user wants this functionality and refuses
- // to use the standard time-zone IDs, then he can always update
- // the array himself.
- //
- return isset($this->on_summertimeoffset) ?
- $this->on_summertimeoffset :
- 3600000;
- } else {
- return 0;
- }
- }
-
-
- // }}}
- // {{{ getRawOffset()
-
- /**
- * Returns the raw (non-DST-corrected) offset from UTC/GMT for this time
- * zone
- *
- * @return int the offset, in milliseconds
- * @access public
- */
- function getRawOffset()
- {
- return $this->offset;
- }
-
-
- // }}}
- // {{{ getOffset()
-
- /**
- * Returns the DST-corrected offset from UTC for the given date
- *
- * Gets the offset to UTC for a given date/time, taking into
- * account daylight savings time, if the time zone observes it and if
- * it is in effect.
- *
- * N.B. that the offset is calculated historically
- * and in the future according to the current Summer time rules,
- * and so this function is proleptically correct, but not necessarily
- * historically correct. (Although if you want to be correct about
- * times in the distant past, this class is probably not for you
- * because the whole notion of time zones does not apply, and
- * historically there are so many time zone changes, Summer time
- * rule changes, name changes, calendar changes, that calculating
- * this sort of information is beyond the scope of this package
- * altogether.)
- *
- * @param mixed $pm_insummertime a boolean specifying whether or not the
- * date is in Summer time, or,
- * a Date object to test for this condition
- *
- * @return int the corrected offset to UTC in milliseconds
- * @access public
- */
- function getOffset($pm_insummertime)
- {
- if ($this->hasdst) {
- if (is_a($pm_insummertime, "Date")) {
- $hb_insummertime = $pm_insummertime->inDaylightTime();
- if (PEAR::isError($hb_insummertime))
- return $hb_insummertime;
- } else {
- $hb_insummertime = $pm_insummertime;
- }
-
- if ($hb_insummertime) {
- return $this->offset + $this->getDSTSavings();
- }
- }
-
- return $this->offset;
- }
-
-
- // }}}
- // {{{ getAvailableIDs()
-
- /**
- * Returns the list of valid time zone id strings
- *
- * @return array an array of strings with the valid time zone IDs
- * @access public
- */
- function getAvailableIDs()
- {
- return array_keys($GLOBALS['_DATE_TIMEZONE_DATA']);
- }
-
-
- // }}}
- // {{{ getID()
-
- /**
- * Returns the time zone id for this time zone, i.e. "America/Chicago"
- *
- * @return string the time zone ID
- * @access public
- */
- function getID()
- {
- return $this->id;
- }
-
-
- // }}}
- // {{{ getLongName()
-
- /**
- * Returns the long name for this time zone
- *
- * Long form of time zone name, e.g. 'Greenwich Mean Time'. Additionally
- * a Date object can be passed in which case the Summer time name will
- * be returned instead if the date falls in Summer time, e.g. 'British
- * Summer Time'.
- *
- * N.B. this is not a unique identifier - for this purpose use the
- * time zone ID.
- *
- * @param mixed $pm_insummertime a boolean specifying whether or not the
- * date is in Summer time, or,
- * a Date object to test for this condition
- *
- * @return string the long name
- * @access public
- */
- function getLongName($pm_insummertime = false)
- {
- if ($this->hasdst) {
- if (is_a($pm_insummertime, "Date")) {
- $hb_insummertime = $pm_insummertime->inDaylightTime();
- if (PEAR::isError($hb_insummertime))
- return $hb_insummertime;
- } else {
- $hb_insummertime = $pm_insummertime;
- }
-
- if ($hb_insummertime) {
- return $this->dstlongname;
- }
- }
-
- return $this->longname;
- }
-
-
- // }}}
- // {{{ getShortName()
-
- /**
- * Returns the short name for this time zone
- *
- * Returns abbreviated form of time zone name, e.g. 'GMT'. Additionally
- * a Date object can be passed in which case the Summer time name will
- * be returned instead if the date falls in Summer time, e.g. 'BST'.
- *
- * N.B. this is not a unique identifier - for this purpose use the
- * time zone ID.
- *
- * @param mixed $pm_insummertime a boolean specifying whether or not the
- * date is in Summer time, or,
- * a Date object to test for this condition
- *
- * @return string the short name
- * @access public
- */
- function getShortName($pm_insummertime = false)
- {
- if ($this->hasdst) {
- if (is_a($pm_insummertime, "Date")) {
- $hb_insummertime = $pm_insummertime->inDaylightTime();
- if (PEAR::isError($hb_insummertime))
- return $hb_insummertime;
- } else {
- $hb_insummertime = $pm_insummertime;
- }
-
- if ($hb_insummertime) {
- return $this->dstshortname;
- }
- }
-
- return $this->shortname;
- }
-
-
- // }}}
- // {{{ getDSTLongName()
-
- /**
- * Returns the DST long name for this time zone, e.g.
- * 'Central Daylight Time'
- *
- * @return string the daylight savings time long name
- * @access public
- */
- function getDSTLongName()
- {
- return $this->hasdst ? $this->dstlongname : $this->longname;
- }
-
-
- // }}}
- // {{{ getDSTShortName()
-
- /**
- * Returns the DST short name for this time zone, e.g. 'CDT'
- *
- * @return string the daylight savings time short name
- * @access public
- */
- function getDSTShortName()
- {
- return $this->hasdst ? $this->dstshortname : $this->shortname;
- }
-
-
- // }}}
- // {{{ getSummerTimeStartMonth()
-
- /**
- * Returns the month number in which Summer time starts
- *
- * @return int integer representing the month (1 to 12)
- * @access public
- * @since Method available since Release 1.5.0
- */
- function getSummerTimeStartMonth()
- {
- return $this->hasdst ? $this->on_summertimestartmonth : null;
- }
-
-
- // }}}
- // {{{ getSummerTimeStartDay()
-
- /**
- * Returns the a code representing the day on which Summer time starts
- *
- * Returns a string in one of the following forms:
- *
- * 5 the fifth of the month
- * lastSun the last Sunday in the month
- * lastMon the last Monday in the month
- * Sun>=8 first Sunday on or after the 8th
- * Sun<=25 last Sunday on or before the 25th
- *
- * @return string
- * @access public
- * @since Method available since Release 1.5.0
- */
- function getSummerTimeStartDay()
- {
- return $this->hasdst ? $this->os_summertimestartday : null;
- }
-
-
- // }}}
- // {{{ getSummerTimeStartTime()
-
- /**
- * Returns the time of day at which which Summer time starts
- *
- * The returned time is an offset, in milliseconds, from midnight UTC. Note
- * that the offset can be negative, which represents the fact that the time
- * zone is East of Greenwich, and that when the clocks change locally, the
- * time in Greenwich is actually a time belonging to the previous day in
- * UTC. This, obviously, is unhelpful if you want to know the local time
- * at which the clocks change, but it is of immense value for the purpose
- * of calculation.
- *
- * @return int integer representing the month (1 to 12)
- * @access public
- * @since Method available since Release 1.5.0
- */
- function getSummerTimeStartTime()
- {
- return $this->hasdst ? $this->on_summertimestarttime : null;
- }
-
-
- // }}}
- // {{{ getSummerTimeEndMonth()
-
- /**
- * Returns the month number in which Summer time ends
- *
- * @return int integer representing the month (1 to 12)
- * @access public
- * @see Date_TimeZone::getSummerTimeStartMonth()
- * @since Method available since Release 1.5.0
- */
- function getSummerTimeEndMonth()
- {
- return $this->hasdst ? $this->on_summertimeendmonth : null;
- }
-
-
- // }}}
- // {{{ getSummerTimeEndDay()
-
- /**
- * Returns the a code representing the day on which Summer time ends
- *
- * @return string
- * @access public
- * @see Date_TimeZone::getSummerTimeStartDay()
- * @since Method available since Release 1.5.0
- */
- function getSummerTimeEndDay()
- {
- return $this->hasdst ? $this->os_summertimeendday : null;
- }
-
-
- // }}}
- // {{{ getSummerTimeEndTime()
-
- /**
- * Returns the time of day at which which Summer time ends
- *
- * @return int integer representing the month (1 to 12)
- * @access public
- * @see Date_TimeZone::getSummerTimeStartTime()
- * @since Method available since Release 1.5.0
- */
- function getSummerTimeEndTime()
- {
- return $this->hasdst ? $this->on_summertimeendtime : null;
- }
-
-
- // }}}
-
-}
-
-// }}}
-
-/**
- * Time Zone Data offset is in miliseconds
- *
- * @global array $GLOBALS['_DATE_TIMEZONE_DATA']
- */
-$GLOBALS['_DATE_TIMEZONE_DATA'] = array(
- //
- // Time zone data is correct as of 15.iii.2007
- //
- 'Africa/Abidjan' => array(
- 'offset' => 0,
- 'shortname' => 'GMT',
- 'dstshortname' => null,
- 'longname' => 'Greenwich Mean Time' ),
- 'Africa/Accra' => array(
- 'offset' => 0,
- 'shortname' => 'GMT',
- 'dstshortname' => null,
- 'longname' => 'Greenwich Mean Time' ),
- 'Africa/Addis_Ababa' => array(
- 'offset' => 10800000,
- 'shortname' => 'EAT',
- 'dstshortname' => null,
- 'longname' => 'Eastern African Time' ),
- 'Africa/Algiers' => array(
- 'offset' => 3600000,
- 'shortname' => 'CET',
- 'dstshortname' => null,
- 'longname' => 'Central European Time' ),
- 'Africa/Asmara' => array(
- 'offset' => 10800000,
- 'shortname' => 'EAT',
- 'dstshortname' => null ),
- 'Africa/Asmera' => array(
- 'offset' => 10800000,
- 'shortname' => 'EAT',
- 'dstshortname' => null,
- 'longname' => 'Eastern African Time' ),
- 'Africa/Bamako' => array(
- 'offset' => 0,
- 'shortname' => 'GMT',
- 'dstshortname' => null,
- 'longname' => 'Greenwich Mean Time' ),
- 'Africa/Bangui' => array(
- 'offset' => 3600000,
- 'shortname' => 'WAT',
- 'dstshortname' => null,
- 'longname' => 'Western African Time' ),
- 'Africa/Banjul' => array(
- 'offset' => 0,
- 'shortname' => 'GMT',
- 'dstshortname' => null,
- 'longname' => 'Greenwich Mean Time' ),
- 'Africa/Bissau' => array(
- 'offset' => 0,
- 'shortname' => 'GMT',
- 'dstshortname' => null,
- 'longname' => 'Greenwich Mean Time' ),
- 'Africa/Blantyre' => array(
- 'offset' => 7200000,
- 'shortname' => 'CAT',
- 'dstshortname' => null,
- 'longname' => 'Central African Time' ),
- 'Africa/Brazzaville' => array(
- 'offset' => 3600000,
- 'shortname' => 'WAT',
- 'dstshortname' => null,
- 'longname' => 'Western African Time' ),
- 'Africa/Bujumbura' => array(
- 'offset' => 7200000,
- 'shortname' => 'CAT',
- 'dstshortname' => null,
- 'longname' => 'Central African Time' ),
- 'Africa/Cairo' => array(
- 'offset' => 7200000,
- 'shortname' => 'EET',
- 'dstshortname' => 'EEST',
- 'longname' => 'Eastern European Time',
- 'dstlongname' => 'Eastern European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 4,
- 'summertimestartday' => 'lastFri',
- 'summertimestarttime' => -7200000,
- 'summertimeendmonth' => 8,
- 'summertimeendday' => 'lastThu',
- 'summertimeendtime' => 75600000 ),
- 'Africa/Casablanca' => array(
- 'offset' => 0,
- 'shortname' => 'WET',
- 'dstshortname' => null,
- 'longname' => 'Western European Time' ),
- 'Africa/Ceuta' => array(
- 'offset' => 3600000,
- 'shortname' => 'CET',
- 'dstshortname' => 'CEST',
- 'longname' => 'Central European Time',
- 'dstlongname' => 'Central European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Africa/Conakry' => array(
- 'offset' => 0,
- 'shortname' => 'GMT',
- 'dstshortname' => null,
- 'longname' => 'Greenwich Mean Time' ),
- 'Africa/Dakar' => array(
- 'offset' => 0,
- 'shortname' => 'GMT',
- 'dstshortname' => null,
- 'longname' => 'Greenwich Mean Time' ),
- 'Africa/Dar_es_Salaam' => array(
- 'offset' => 10800000,
- 'shortname' => 'EAT',
- 'dstshortname' => null,
- 'longname' => 'Eastern African Time' ),
- 'Africa/Djibouti' => array(
- 'offset' => 10800000,
- 'shortname' => 'EAT',
- 'dstshortname' => null,
- 'longname' => 'Eastern African Time' ),
- 'Africa/Douala' => array(
- 'offset' => 3600000,
- 'shortname' => 'WAT',
- 'dstshortname' => null,
- 'longname' => 'Western African Time' ),
- 'Africa/El_Aaiun' => array(
- 'offset' => 0,
- 'shortname' => 'WET',
- 'dstshortname' => null,
- 'longname' => 'Western European Time' ),
- 'Africa/Freetown' => array(
- 'offset' => 0,
- 'shortname' => 'GMT',
- 'dstshortname' => null,
- 'longname' => 'Greenwich Mean Time' ),
- 'Africa/Gaborone' => array(
- 'offset' => 7200000,
- 'shortname' => 'CAT',
- 'dstshortname' => null,
- 'longname' => 'Central African Time' ),
- 'Africa/Harare' => array(
- 'offset' => 7200000,
- 'shortname' => 'CAT',
- 'dstshortname' => null,
- 'longname' => 'Central African Time' ),
- 'Africa/Johannesburg' => array(
- 'offset' => 7200000,
- 'shortname' => 'SAST',
- 'dstshortname' => null,
- 'longname' => 'South Africa Standard Time' ),
- 'Africa/Kampala' => array(
- 'offset' => 10800000,
- 'shortname' => 'EAT',
- 'dstshortname' => null,
- 'longname' => 'Eastern African Time' ),
- 'Africa/Khartoum' => array(
- 'offset' => 10800000,
- 'shortname' => 'EAT',
- 'dstshortname' => null,
- 'longname' => 'Eastern African Time' ),
- 'Africa/Kigali' => array(
- 'offset' => 7200000,
- 'shortname' => 'CAT',
- 'dstshortname' => null,
- 'longname' => 'Central African Time' ),
- 'Africa/Kinshasa' => array(
- 'offset' => 3600000,
- 'shortname' => 'WAT',
- 'dstshortname' => null,
- 'longname' => 'Western African Time' ),
- 'Africa/Lagos' => array(
- 'offset' => 3600000,
- 'shortname' => 'WAT',
- 'dstshortname' => null,
- 'longname' => 'Western African Time' ),
- 'Africa/Libreville' => array(
- 'offset' => 3600000,
- 'shortname' => 'WAT',
- 'dstshortname' => null,
- 'longname' => 'Western African Time' ),
- 'Africa/Lome' => array(
- 'offset' => 0,
- 'shortname' => 'GMT',
- 'dstshortname' => null,
- 'longname' => 'Greenwich Mean Time' ),
- 'Africa/Luanda' => array(
- 'offset' => 3600000,
- 'shortname' => 'WAT',
- 'dstshortname' => null,
- 'longname' => 'Western African Time' ),
- 'Africa/Lubumbashi' => array(
- 'offset' => 7200000,
- 'shortname' => 'CAT',
- 'dstshortname' => null,
- 'longname' => 'Central African Time' ),
- 'Africa/Lusaka' => array(
- 'offset' => 7200000,
- 'shortname' => 'CAT',
- 'dstshortname' => null,
- 'longname' => 'Central African Time' ),
- 'Africa/Malabo' => array(
- 'offset' => 3600000,
- 'shortname' => 'WAT',
- 'dstshortname' => null,
- 'longname' => 'Western African Time' ),
- 'Africa/Maputo' => array(
- 'offset' => 7200000,
- 'shortname' => 'CAT',
- 'dstshortname' => null,
- 'longname' => 'Central African Time' ),
- 'Africa/Maseru' => array(
- 'offset' => 7200000,
- 'shortname' => 'SAST',
- 'dstshortname' => null,
- 'longname' => 'South Africa Standard Time' ),
- 'Africa/Mbabane' => array(
- 'offset' => 7200000,
- 'shortname' => 'SAST',
- 'dstshortname' => null,
- 'longname' => 'South Africa Standard Time' ),
- 'Africa/Mogadishu' => array(
- 'offset' => 10800000,
- 'shortname' => 'EAT',
- 'dstshortname' => null,
- 'longname' => 'Eastern African Time' ),
- 'Africa/Monrovia' => array(
- 'offset' => 0,
- 'shortname' => 'GMT',
- 'dstshortname' => null,
- 'longname' => 'Greenwich Mean Time' ),
- 'Africa/Nairobi' => array(
- 'offset' => 10800000,
- 'shortname' => 'EAT',
- 'dstshortname' => null,
- 'longname' => 'Eastern African Time' ),
- 'Africa/Ndjamena' => array(
- 'offset' => 3600000,
- 'shortname' => 'WAT',
- 'dstshortname' => null,
- 'longname' => 'Western African Time' ),
- 'Africa/Niamey' => array(
- 'offset' => 3600000,
- 'shortname' => 'WAT',
- 'dstshortname' => null,
- 'longname' => 'Western African Time' ),
- 'Africa/Nouakchott' => array(
- 'offset' => 0,
- 'shortname' => 'GMT',
- 'dstshortname' => null,
- 'longname' => 'Greenwich Mean Time' ),
- 'Africa/Ouagadougou' => array(
- 'offset' => 0,
- 'shortname' => 'GMT',
- 'dstshortname' => null,
- 'longname' => 'Greenwich Mean Time' ),
- 'Africa/Porto-Novo' => array(
- 'offset' => 3600000,
- 'shortname' => 'WAT',
- 'dstshortname' => null,
- 'longname' => 'Western African Time' ),
- 'Africa/Sao_Tome' => array(
- 'offset' => 0,
- 'shortname' => 'GMT',
- 'dstshortname' => null,
- 'longname' => 'Greenwich Mean Time' ),
- 'Africa/Timbuktu' => array(
- 'offset' => 0,
- 'shortname' => 'GMT',
- 'dstshortname' => null,
- 'longname' => 'Greenwich Mean Time' ),
- 'Africa/Tripoli' => array(
- 'offset' => 7200000,
- 'shortname' => 'EET',
- 'dstshortname' => null,
- 'longname' => 'Eastern European Time' ),
- 'Africa/Tunis' => array(
- 'offset' => 3600000,
- 'shortname' => 'CET',
- 'dstshortname' => 'CEST',
- 'longname' => 'Central European Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Africa/Windhoek' => array(
- 'offset' => 3600000,
- 'shortname' => 'WAT',
- 'dstshortname' => 'WAST',
- 'longname' => 'Western African Time',
- 'dstlongname' => 'Western African Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 9,
- 'summertimestartday' => 'Sun>=1',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 4,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 0 ),
- 'America/Adak' => array(
- 'offset' => -36000000,
- 'shortname' => 'HAST',
- 'dstshortname' => 'HADT',
- 'longname' => 'Hawaii-Aleutian Standard Time',
- 'dstlongname' => 'Hawaii-Aleutian Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 43200000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 39600000 ),
- 'America/Anchorage' => array(
- 'offset' => -32400000,
- 'shortname' => 'AKST',
- 'dstshortname' => 'AKDT',
- 'longname' => 'Alaska Standard Time',
- 'dstlongname' => 'Alaska Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 39600000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 36000000 ),
- 'America/Anguilla' => array(
- 'offset' => -14400000,
- 'shortname' => 'AST',
- 'dstshortname' => null,
- 'longname' => 'Atlantic Standard Time' ),
- 'America/Antigua' => array(
- 'offset' => -14400000,
- 'shortname' => 'AST',
- 'dstshortname' => null,
- 'longname' => 'Atlantic Standard Time' ),
- 'America/Araguaina' => array(
- 'offset' => -10800000,
- 'shortname' => 'BRT',
- 'dstshortname' => null,
- 'longname' => 'Brazil Time',
- 'dstlongname' => 'Brazil Summer Time' ),
- 'America/Argentina/Buenos_Aires' => array(
- 'offset' => -10800000,
- 'shortname' => 'ART',
- 'dstshortname' => 'ARST',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 10,
- 'summertimestartday' => 'Sun>=1',
- 'summertimestarttime' => 0,
- 'summertimeendmonth' => 3,
- 'summertimeendday' => 'Sun>=15',
- 'summertimeendtime' => 0 ),
- 'America/Argentina/Catamarca' => array(
- 'offset' => -10800000,
- 'shortname' => 'ART',
- 'dstshortname' => 'ARST',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 10,
- 'summertimestartday' => 'Sun>=1',
- 'summertimestarttime' => 0,
- 'summertimeendmonth' => 3,
- 'summertimeendday' => 'Sun>=15',
- 'summertimeendtime' => 0 ),
- 'America/Argentina/ComodRivadavia' => array(
- 'offset' => -10800000,
- 'shortname' => 'ART',
- 'dstshortname' => 'ARST',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 10,
- 'summertimestartday' => 'Sun>=1',
- 'summertimestarttime' => 0,
- 'summertimeendmonth' => 3,
- 'summertimeendday' => 'Sun>=15',
- 'summertimeendtime' => 0 ),
- 'America/Argentina/Cordoba' => array(
- 'offset' => -10800000,
- 'shortname' => 'ART',
- 'dstshortname' => 'ARST',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 10,
- 'summertimestartday' => 'Sun>=1',
- 'summertimestarttime' => 0,
- 'summertimeendmonth' => 3,
- 'summertimeendday' => 'Sun>=15',
- 'summertimeendtime' => 0 ),
- 'America/Argentina/Jujuy' => array(
- 'offset' => -10800000,
- 'shortname' => 'ART',
- 'dstshortname' => 'ARST',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 10,
- 'summertimestartday' => 'Sun>=1',
- 'summertimestarttime' => 0,
- 'summertimeendmonth' => 3,
- 'summertimeendday' => 'Sun>=15',
- 'summertimeendtime' => 0 ),
- 'America/Argentina/La_Rioja' => array(
- 'offset' => -10800000,
- 'shortname' => 'ART',
- 'dstshortname' => 'ARST',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 10,
- 'summertimestartday' => 'Sun>=1',
- 'summertimestarttime' => 0,
- 'summertimeendmonth' => 3,
- 'summertimeendday' => 'Sun>=15',
- 'summertimeendtime' => 0 ),
- 'America/Argentina/Mendoza' => array(
- 'offset' => -10800000,
- 'shortname' => 'ART',
- 'dstshortname' => 'ARST',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 10,
- 'summertimestartday' => 'Sun>=1',
- 'summertimestarttime' => 0,
- 'summertimeendmonth' => 3,
- 'summertimeendday' => 'Sun>=15',
- 'summertimeendtime' => 0 ),
- 'America/Argentina/Rio_Gallegos' => array(
- 'offset' => -10800000,
- 'shortname' => 'ART',
- 'dstshortname' => 'ARST',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 10,
- 'summertimestartday' => 'Sun>=1',
- 'summertimestarttime' => 0,
- 'summertimeendmonth' => 3,
- 'summertimeendday' => 'Sun>=15',
- 'summertimeendtime' => 0 ),
- 'America/Argentina/San_Juan' => array(
- 'offset' => -10800000,
- 'shortname' => 'ART',
- 'dstshortname' => 'ARST',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 10,
- 'summertimestartday' => 'Sun>=1',
- 'summertimestarttime' => 0,
- 'summertimeendmonth' => 3,
- 'summertimeendday' => 'Sun>=15',
- 'summertimeendtime' => 0 ),
- 'America/Argentina/Tucuman' => array(
- 'offset' => -10800000,
- 'shortname' => 'ART',
- 'dstshortname' => 'ARST',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 10,
- 'summertimestartday' => 'Sun>=1',
- 'summertimestarttime' => 0,
- 'summertimeendmonth' => 3,
- 'summertimeendday' => 'Sun>=15',
- 'summertimeendtime' => 0 ),
- 'America/Argentina/Ushuaia' => array(
- 'offset' => -10800000,
- 'shortname' => 'ART',
- 'dstshortname' => 'ARST',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 10,
- 'summertimestartday' => 'Sun>=1',
- 'summertimestarttime' => 0,
- 'summertimeendmonth' => 3,
- 'summertimeendday' => 'Sun>=15',
- 'summertimeendtime' => 0 ),
- 'America/Aruba' => array(
- 'offset' => -14400000,
- 'shortname' => 'AST',
- 'dstshortname' => null,
- 'longname' => 'Atlantic Standard Time' ),
- 'America/Asuncion' => array(
- 'offset' => -14400000,
- 'shortname' => 'PYT',
- 'dstshortname' => 'PYST',
- 'longname' => 'Paraguay Time',
- 'dstlongname' => 'Paraguay Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 10,
- 'summertimestartday' => 'Sun>=15',
- 'summertimestarttime' => 14400000,
- 'summertimeendmonth' => 3,
- 'summertimeendday' => 'Sun>=8',
- 'summertimeendtime' => 10800000 ),
- 'America/Atikokan' => array(
- 'offset' => -18000000,
- 'shortname' => 'EST',
- 'dstshortname' => null ),
- 'America/Atka' => array(
- 'offset' => -36000000,
- 'shortname' => 'HAST',
- 'dstshortname' => 'HADT',
- 'longname' => 'Hawaii-Aleutian Standard Time',
- 'dstlongname' => 'Hawaii-Aleutian Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 43200000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 39600000 ),
- 'America/Bahia' => array(
- 'offset' => -10800000,
- 'shortname' => 'BRT',
- 'dstshortname' => null ),
- 'America/Barbados' => array(
- 'offset' => -14400000,
- 'shortname' => 'AST',
- 'dstshortname' => null,
- 'longname' => 'Atlantic Standard Time' ),
- 'America/Belem' => array(
- 'offset' => -10800000,
- 'shortname' => 'BRT',
- 'dstshortname' => null,
- 'longname' => 'Brazil Time' ),
- 'America/Belize' => array(
- 'offset' => -21600000,
- 'shortname' => 'CST',
- 'dstshortname' => null,
- 'longname' => 'Central Standard Time' ),
- 'America/Blanc-Sablon' => array(
- 'offset' => -14400000,
- 'shortname' => 'AST',
- 'dstshortname' => null ),
- 'America/Boa_Vista' => array(
- 'offset' => -14400000,
- 'shortname' => 'AMT',
- 'dstshortname' => null,
- 'longname' => 'Amazon Standard Time' ),
- 'America/Bogota' => array(
- 'offset' => -18000000,
- 'shortname' => 'COT',
- 'dstshortname' => null,
- 'longname' => 'Colombia Time' ),
- 'America/Boise' => array(
- 'offset' => -25200000,
- 'shortname' => 'MST',
- 'dstshortname' => 'MDT',
- 'longname' => 'Mountain Standard Time',
- 'dstlongname' => 'Mountain Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 32400000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 28800000 ),
- 'America/Buenos_Aires' => array(
- 'offset' => -10800000,
- 'shortname' => 'ART',
- 'dstshortname' => 'ARST',
- 'longname' => 'Argentine Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 10,
- 'summertimestartday' => 'Sun>=1',
- 'summertimestarttime' => 0,
- 'summertimeendmonth' => 3,
- 'summertimeendday' => 'Sun>=15',
- 'summertimeendtime' => 0 ),
- 'America/Cambridge_Bay' => array(
- 'offset' => -25200000,
- 'shortname' => 'MST',
- 'dstshortname' => 'MDT',
- 'longname' => 'Mountain Standard Time',
- 'dstlongname' => 'Mountain Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 32400000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 28800000 ),
- 'America/Campo_Grande' => array(
- 'offset' => -14400000,
- 'shortname' => 'AMT',
- 'dstshortname' => 'AMST',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 10,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 14400000,
- 'summertimeendmonth' => 2,
- 'summertimeendday' => 'Sun>=15',
- 'summertimeendtime' => 10800000 ),
- 'America/Cancun' => array(
- 'offset' => -21600000,
- 'shortname' => 'CST',
- 'dstshortname' => 'CDT',
- 'longname' => 'Central Standard Time',
- 'dstlongname' => 'Central Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 4,
- 'summertimestartday' => 'Sun>=1',
- 'summertimestarttime' => 28800000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 25200000 ),
- 'America/Caracas' => array(
- 'offset' => -16200000,
- 'shortname' => 'VET',
- 'dstshortname' => null,
- 'longname' => 'Venezuela Time' ),
- 'America/Catamarca' => array(
- 'offset' => -10800000,
- 'shortname' => 'ART',
- 'dstshortname' => 'ARST',
- 'longname' => 'Argentine Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 10,
- 'summertimestartday' => 'Sun>=1',
- 'summertimestarttime' => 0,
- 'summertimeendmonth' => 3,
- 'summertimeendday' => 'Sun>=15',
- 'summertimeendtime' => 0 ),
- 'America/Cayenne' => array(
- 'offset' => -10800000,
- 'shortname' => 'GFT',
- 'dstshortname' => null,
- 'longname' => 'French Guiana Time' ),
- 'America/Cayman' => array(
- 'offset' => -18000000,
- 'shortname' => 'EST',
- 'dstshortname' => null,
- 'longname' => 'Eastern Standard Time' ),
- 'America/Chicago' => array(
- 'offset' => -21600000,
- 'shortname' => 'CST',
- 'dstshortname' => 'CDT',
- 'longname' => 'Central Standard Time',
- 'dstlongname' => 'Central Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 28800000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 25200000 ),
- 'America/Chihuahua' => array(
- 'offset' => -25200000,
- 'shortname' => 'MST',
- 'dstshortname' => 'MDT',
- 'longname' => 'Mountain Standard Time',
- 'dstlongname' => 'Mountain Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 4,
- 'summertimestartday' => 'Sun>=1',
- 'summertimestarttime' => 32400000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 28800000 ),
- 'America/Coral_Harbour' => array(
- 'offset' => -18000000,
- 'shortname' => 'EST',
- 'dstshortname' => null ),
- 'America/Cordoba' => array(
- 'offset' => -10800000,
- 'shortname' => 'ART',
- 'dstshortname' => 'ARST',
- 'longname' => 'Argentine Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 10,
- 'summertimestartday' => 'Sun>=1',
- 'summertimestarttime' => 0,
- 'summertimeendmonth' => 3,
- 'summertimeendday' => 'Sun>=15',
- 'summertimeendtime' => 0 ),
- 'America/Costa_Rica' => array(
- 'offset' => -21600000,
- 'shortname' => 'CST',
- 'dstshortname' => null,
- 'longname' => 'Central Standard Time' ),
- 'America/Cuiaba' => array(
- 'offset' => -14400000,
- 'shortname' => 'AMT',
- 'dstshortname' => 'AMST',
- 'longname' => 'Amazon Standard Time',
- 'dstlongname' => 'Amazon Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 10,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 14400000,
- 'summertimeendmonth' => 2,
- 'summertimeendday' => 'Sun>=15',
- 'summertimeendtime' => 10800000 ),
- 'America/Curacao' => array(
- 'offset' => -14400000,
- 'shortname' => 'AST',
- 'dstshortname' => null,
- 'longname' => 'Atlantic Standard Time' ),
- 'America/Danmarkshavn' => array(
- 'offset' => 0,
- 'shortname' => 'GMT',
- 'dstshortname' => null,
- 'longname' => 'Greenwich Mean Time' ),
- 'America/Dawson' => array(
- 'offset' => -28800000,
- 'shortname' => 'PST',
- 'dstshortname' => 'PDT',
- 'longname' => 'Pacific Standard Time',
- 'dstlongname' => 'Pacific Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 36000000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 32400000 ),
- 'America/Dawson_Creek' => array(
- 'offset' => -25200000,
- 'shortname' => 'MST',
- 'dstshortname' => null,
- 'longname' => 'Mountain Standard Time' ),
- 'America/Denver' => array(
- 'offset' => -25200000,
- 'shortname' => 'MST',
- 'dstshortname' => 'MDT',
- 'longname' => 'Mountain Standard Time',
- 'dstlongname' => 'Mountain Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 32400000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 28800000 ),
- 'America/Detroit' => array(
- 'offset' => -18000000,
- 'shortname' => 'EST',
- 'dstshortname' => 'EDT',
- 'longname' => 'Eastern Standard Time',
- 'dstlongname' => 'Eastern Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 25200000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 21600000 ),
- 'America/Dominica' => array(
- 'offset' => -14400000,
- 'shortname' => 'AST',
- 'dstshortname' => null,
- 'longname' => 'Atlantic Standard Time' ),
- 'America/Edmonton' => array(
- 'offset' => -25200000,
- 'shortname' => 'MST',
- 'dstshortname' => 'MDT',
- 'longname' => 'Mountain Standard Time',
- 'dstlongname' => 'Mountain Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 32400000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 28800000 ),
- 'America/Eirunepe' => array(
- 'offset' => -18000000,
- 'shortname' => 'ACT',
- 'dstshortname' => null,
- 'longname' => 'Acre Time' ),
- 'America/El_Salvador' => array(
- 'offset' => -21600000,
- 'shortname' => 'CST',
- 'dstshortname' => null,
- 'longname' => 'Central Standard Time' ),
- 'America/Ensenada' => array(
- 'offset' => -28800000,
- 'shortname' => 'PST',
- 'dstshortname' => 'PDT',
- 'longname' => 'Pacific Standard Time',
- 'dstlongname' => 'Pacific Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 4,
- 'summertimestartday' => 'Sun>=1',
- 'summertimestarttime' => 36000000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 32400000 ),
- 'America/Fort_Wayne' => array(
- 'offset' => -18000000,
- 'shortname' => 'EST',
- 'dstshortname' => 'EDT',
- 'longname' => 'Eastern Standard Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 25200000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 21600000 ),
- 'America/Fortaleza' => array(
- 'offset' => -10800000,
- 'shortname' => 'BRT',
- 'dstshortname' => null,
- 'longname' => 'Brazil Time',
- 'dstlongname' => 'Brazil Summer Time' ),
- 'America/Glace_Bay' => array(
- 'offset' => -14400000,
- 'shortname' => 'AST',
- 'dstshortname' => 'ADT',
- 'longname' => 'Atlantic Standard Time',
- 'dstlongname' => 'Atlantic Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 21600000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 18000000 ),
- 'America/Godthab' => array(
- 'offset' => -10800000,
- 'shortname' => 'WGT',
- 'dstshortname' => 'WGST',
- 'longname' => 'Western Greenland Time',
- 'dstlongname' => 'Western Greenland Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'America/Goose_Bay' => array(
- 'offset' => -14400000,
- 'shortname' => 'AST',
- 'dstshortname' => 'ADT',
- 'longname' => 'Atlantic Standard Time',
- 'dstlongname' => 'Atlantic Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 14460000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 10860000 ),
- 'America/Grand_Turk' => array(
- 'offset' => -18000000,
- 'shortname' => 'EST',
- 'dstshortname' => 'EDT',
- 'longname' => 'Eastern Standard Time',
- 'dstlongname' => 'Eastern Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 25200000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 21600000 ),
- 'America/Grenada' => array(
- 'offset' => -14400000,
- 'shortname' => 'AST',
- 'dstshortname' => null,
- 'longname' => 'Atlantic Standard Time' ),
- 'America/Guadeloupe' => array(
- 'offset' => -14400000,
- 'shortname' => 'AST',
- 'dstshortname' => null,
- 'longname' => 'Atlantic Standard Time' ),
- 'America/Guatemala' => array(
- 'offset' => -21600000,
- 'shortname' => 'CST',
- 'dstshortname' => null,
- 'longname' => 'Central Standard Time' ),
- 'America/Guayaquil' => array(
- 'offset' => -18000000,
- 'shortname' => 'ECT',
- 'dstshortname' => null,
- 'longname' => 'Ecuador Time' ),
- 'America/Guyana' => array(
- 'offset' => -14400000,
- 'shortname' => 'GYT',
- 'dstshortname' => null,
- 'longname' => 'Guyana Time' ),
- 'America/Halifax' => array(
- 'offset' => -14400000,
- 'shortname' => 'AST',
- 'dstshortname' => 'ADT',
- 'longname' => 'Atlantic Standard Time',
- 'dstlongname' => 'Atlantic Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 21600000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 18000000 ),
- 'America/Havana' => array(
- 'offset' => -18000000,
- 'shortname' => 'CST',
- 'dstshortname' => 'CDT',
- 'longname' => 'Central Standard Time',
- 'dstlongname' => 'Central Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 18000000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 18000000 ),
- 'America/Hermosillo' => array(
- 'offset' => -25200000,
- 'shortname' => 'MST',
- 'dstshortname' => null,
- 'longname' => 'Mountain Standard Time' ),
- 'America/Indiana/Indianapolis' => array(
- 'offset' => -18000000,
- 'shortname' => 'EST',
- 'dstshortname' => 'EDT',
- 'longname' => 'Eastern Standard Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 25200000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 21600000 ),
- 'America/Indiana/Knox' => array(
- 'offset' => -21600000,
- 'shortname' => 'CST',
- 'dstshortname' => 'CDT',
- 'longname' => 'Central Standard Time',
- 'dstlongname' => 'Central Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 28800000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 25200000 ),
- 'America/Indiana/Marengo' => array(
- 'offset' => -18000000,
- 'shortname' => 'EST',
- 'dstshortname' => 'EDT',
- 'longname' => 'Eastern Standard Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 25200000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 21600000 ),
- 'America/Indiana/Petersburg' => array(
- 'offset' => -18000000,
- 'shortname' => 'EST',
- 'dstshortname' => 'EDT',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 25200000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 21600000 ),
- 'America/Indiana/Tell_City' => array(
- 'offset' => -21600000,
- 'shortname' => 'CST',
- 'dstshortname' => 'CDT',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 28800000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 25200000 ),
- 'America/Indiana/Vevay' => array(
- 'offset' => -18000000,
- 'shortname' => 'EST',
- 'dstshortname' => 'EDT',
- 'longname' => 'Eastern Standard Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 25200000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 21600000 ),
- 'America/Indiana/Vincennes' => array(
- 'offset' => -18000000,
- 'shortname' => 'EST',
- 'dstshortname' => 'EDT',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 25200000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 21600000 ),
- 'America/Indiana/Winamac' => array(
- 'offset' => -18000000,
- 'shortname' => 'EST',
- 'dstshortname' => 'EDT',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 25200000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 21600000 ),
- 'America/Indianapolis' => array(
- 'offset' => -18000000,
- 'shortname' => 'EST',
- 'dstshortname' => 'EDT',
- 'longname' => 'Eastern Standard Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 25200000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 21600000 ),
- 'America/Inuvik' => array(
- 'offset' => -25200000,
- 'shortname' => 'MST',
- 'dstshortname' => 'MDT',
- 'longname' => 'Mountain Standard Time',
- 'dstlongname' => 'Mountain Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 32400000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 28800000 ),
- 'America/Iqaluit' => array(
- 'offset' => -18000000,
- 'shortname' => 'EST',
- 'dstshortname' => 'EDT',
- 'longname' => 'Eastern Standard Time',
- 'dstlongname' => 'Eastern Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 25200000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 21600000 ),
- 'America/Jamaica' => array(
- 'offset' => -18000000,
- 'shortname' => 'EST',
- 'dstshortname' => null,
- 'longname' => 'Eastern Standard Time' ),
- 'America/Jujuy' => array(
- 'offset' => -10800000,
- 'shortname' => 'ART',
- 'dstshortname' => 'ARST',
- 'longname' => 'Argentine Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 10,
- 'summertimestartday' => 'Sun>=1',
- 'summertimestarttime' => 0,
- 'summertimeendmonth' => 3,
- 'summertimeendday' => 'Sun>=15',
- 'summertimeendtime' => 0 ),
- 'America/Juneau' => array(
- 'offset' => -32400000,
- 'shortname' => 'AKST',
- 'dstshortname' => 'AKDT',
- 'longname' => 'Alaska Standard Time',
- 'dstlongname' => 'Alaska Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 39600000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 36000000 ),
- 'America/Kentucky/Louisville' => array(
- 'offset' => -18000000,
- 'shortname' => 'EST',
- 'dstshortname' => 'EDT',
- 'longname' => 'Eastern Standard Time',
- 'dstlongname' => 'Eastern Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 25200000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 21600000 ),
- 'America/Kentucky/Monticello' => array(
- 'offset' => -18000000,
- 'shortname' => 'EST',
- 'dstshortname' => 'EDT',
- 'longname' => 'Eastern Standard Time',
- 'dstlongname' => 'Eastern Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 25200000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 21600000 ),
- 'America/Knox_IN' => array(
- 'offset' => -21600000,
- 'shortname' => 'CST',
- 'dstshortname' => 'CDT',
- 'longname' => 'Central Standard Time',
- 'dstlongname' => 'Central Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 28800000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 25200000 ),
- 'America/La_Paz' => array(
- 'offset' => -14400000,
- 'shortname' => 'BOT',
- 'dstshortname' => null,
- 'longname' => 'Bolivia Time' ),
- 'America/Lima' => array(
- 'offset' => -18000000,
- 'shortname' => 'PET',
- 'dstshortname' => null,
- 'longname' => 'Peru Time' ),
- 'America/Los_Angeles' => array(
- 'offset' => -28800000,
- 'shortname' => 'PST',
- 'dstshortname' => 'PDT',
- 'longname' => 'Pacific Standard Time',
- 'dstlongname' => 'Pacific Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 36000000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 32400000 ),
- 'America/Louisville' => array(
- 'offset' => -18000000,
- 'shortname' => 'EST',
- 'dstshortname' => 'EDT',
- 'longname' => 'Eastern Standard Time',
- 'dstlongname' => 'Eastern Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 25200000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 21600000 ),
- 'America/Maceio' => array(
- 'offset' => -10800000,
- 'shortname' => 'BRT',
- 'dstshortname' => null,
- 'longname' => 'Brazil Time',
- 'dstlongname' => 'Brazil Summer Time' ),
- 'America/Managua' => array(
- 'offset' => -21600000,
- 'shortname' => 'CST',
- 'dstshortname' => null,
- 'longname' => 'Central Standard Time' ),
- 'America/Manaus' => array(
- 'offset' => -14400000,
- 'shortname' => 'AMT',
- 'dstshortname' => null,
- 'longname' => 'Amazon Standard Time' ),
- 'America/Marigot' => array(
- 'offset' => -14400000,
- 'shortname' => 'AST',
- 'dstshortname' => null ),
- 'America/Martinique' => array(
- 'offset' => -14400000,
- 'shortname' => 'AST',
- 'dstshortname' => null,
- 'longname' => 'Atlantic Standard Time' ),
- 'America/Mazatlan' => array(
- 'offset' => -25200000,
- 'shortname' => 'MST',
- 'dstshortname' => 'MDT',
- 'longname' => 'Mountain Standard Time',
- 'dstlongname' => 'Mountain Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 4,
- 'summertimestartday' => 'Sun>=1',
- 'summertimestarttime' => 32400000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 28800000 ),
- 'America/Mendoza' => array(
- 'offset' => -10800000,
- 'shortname' => 'ART',
- 'dstshortname' => 'ARST',
- 'longname' => 'Argentine Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 10,
- 'summertimestartday' => 'Sun>=1',
- 'summertimestarttime' => 0,
- 'summertimeendmonth' => 3,
- 'summertimeendday' => 'Sun>=15',
- 'summertimeendtime' => 0 ),
- 'America/Menominee' => array(
- 'offset' => -21600000,
- 'shortname' => 'CST',
- 'dstshortname' => 'CDT',
- 'longname' => 'Central Standard Time',
- 'dstlongname' => 'Central Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 28800000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 25200000 ),
- 'America/Merida' => array(
- 'offset' => -21600000,
- 'shortname' => 'CST',
- 'dstshortname' => 'CDT',
- 'longname' => 'Central Standard Time',
- 'dstlongname' => 'Central Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 4,
- 'summertimestartday' => 'Sun>=1',
- 'summertimestarttime' => 28800000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 25200000 ),
- 'America/Mexico_City' => array(
- 'offset' => -21600000,
- 'shortname' => 'CST',
- 'dstshortname' => 'CDT',
- 'longname' => 'Central Standard Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 4,
- 'summertimestartday' => 'Sun>=1',
- 'summertimestarttime' => 28800000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 25200000 ),
- 'America/Miquelon' => array(
- 'offset' => -10800000,
- 'shortname' => 'PMST',
- 'dstshortname' => 'PMDT',
- 'longname' => 'Pierre & Miquelon Standard Time',
- 'dstlongname' => 'Pierre & Miquelon Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 18000000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 14400000 ),
- 'America/Moncton' => array(
- 'offset' => -14400000,
- 'shortname' => 'AST',
- 'dstshortname' => 'ADT',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 21600000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 18000000 ),
- 'America/Monterrey' => array(
- 'offset' => -21600000,
- 'shortname' => 'CST',
- 'dstshortname' => 'CDT',
- 'longname' => 'Central Standard Time',
- 'dstlongname' => 'Central Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 4,
- 'summertimestartday' => 'Sun>=1',
- 'summertimestarttime' => 28800000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 25200000 ),
- 'America/Montevideo' => array(
- 'offset' => -10800000,
- 'shortname' => 'UYT',
- 'dstshortname' => 'UYST',
- 'longname' => 'Uruguay Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 10,
- 'summertimestartday' => 'Sun>=1',
- 'summertimestarttime' => 18000000,
- 'summertimeendmonth' => 3,
- 'summertimeendday' => 'Sun>=8',
- 'summertimeendtime' => 14400000 ),
- 'America/Montreal' => array(
- 'offset' => -18000000,
- 'shortname' => 'EST',
- 'dstshortname' => 'EDT',
- 'longname' => 'Eastern Standard Time',
- 'dstlongname' => 'Eastern Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 25200000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 21600000 ),
- 'America/Montserrat' => array(
- 'offset' => -14400000,
- 'shortname' => 'AST',
- 'dstshortname' => null,
- 'longname' => 'Atlantic Standard Time' ),
- 'America/Nassau' => array(
- 'offset' => -18000000,
- 'shortname' => 'EST',
- 'dstshortname' => 'EDT',
- 'longname' => 'Eastern Standard Time',
- 'dstlongname' => 'Eastern Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 25200000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 21600000 ),
- 'America/New_York' => array(
- 'offset' => -18000000,
- 'shortname' => 'EST',
- 'dstshortname' => 'EDT',
- 'longname' => 'Eastern Standard Time',
- 'dstlongname' => 'Eastern Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 25200000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 21600000 ),
- 'America/Nipigon' => array(
- 'offset' => -18000000,
- 'shortname' => 'EST',
- 'dstshortname' => 'EDT',
- 'longname' => 'Eastern Standard Time',
- 'dstlongname' => 'Eastern Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 25200000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 21600000 ),
- 'America/Nome' => array(
- 'offset' => -32400000,
- 'shortname' => 'AKST',
- 'dstshortname' => 'AKDT',
- 'longname' => 'Alaska Standard Time',
- 'dstlongname' => 'Alaska Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 39600000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 36000000 ),
- 'America/Noronha' => array(
- 'offset' => -7200000,
- 'shortname' => 'FNT',
- 'dstshortname' => null,
- 'longname' => 'Fernando de Noronha Time' ),
- 'America/North_Dakota/Center' => array(
- 'offset' => -21600000,
- 'shortname' => 'CST',
- 'dstshortname' => 'CDT',
- 'longname' => 'Central Standard Time',
- 'dstlongname' => 'Central Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 28800000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 25200000 ),
- 'America/North_Dakota/New_Salem' => array(
- 'offset' => -21600000,
- 'shortname' => 'CST',
- 'dstshortname' => 'CDT',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 28800000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 25200000 ),
- 'America/Panama' => array(
- 'offset' => -18000000,
- 'shortname' => 'EST',
- 'dstshortname' => null,
- 'longname' => 'Eastern Standard Time' ),
- 'America/Pangnirtung' => array(
- 'offset' => -18000000,
- 'shortname' => 'EST',
- 'dstshortname' => 'EDT',
- 'longname' => 'Eastern Standard Time',
- 'dstlongname' => 'Eastern Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 25200000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 21600000 ),
- 'America/Paramaribo' => array(
- 'offset' => -10800000,
- 'shortname' => 'SRT',
- 'dstshortname' => null,
- 'longname' => 'Suriname Time' ),
- 'America/Phoenix' => array(
- 'offset' => -25200000,
- 'shortname' => 'MST',
- 'dstshortname' => null,
- 'longname' => 'Mountain Standard Time' ),
- 'America/Port-au-Prince' => array(
- 'offset' => -18000000,
- 'shortname' => 'EST',
- 'dstshortname' => null,
- 'longname' => 'Eastern Standard Time' ),
- 'America/Port_of_Spain' => array(
- 'offset' => -14400000,
- 'shortname' => 'AST',
- 'dstshortname' => null,
- 'longname' => 'Atlantic Standard Time' ),
- 'America/Porto_Acre' => array(
- 'offset' => -18000000,
- 'shortname' => 'ACT',
- 'dstshortname' => null,
- 'longname' => 'Acre Time' ),
- 'America/Porto_Velho' => array(
- 'offset' => -14400000,
- 'shortname' => 'AMT',
- 'dstshortname' => null,
- 'longname' => 'Amazon Standard Time' ),
- 'America/Puerto_Rico' => array(
- 'offset' => -14400000,
- 'shortname' => 'AST',
- 'dstshortname' => null,
- 'longname' => 'Atlantic Standard Time' ),
- 'America/Rainy_River' => array(
- 'offset' => -21600000,
- 'shortname' => 'CST',
- 'dstshortname' => 'CDT',
- 'longname' => 'Central Standard Time',
- 'dstlongname' => 'Central Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 28800000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 25200000 ),
- 'America/Rankin_Inlet' => array(
- 'offset' => -21600000,
- 'shortname' => 'CST',
- 'dstshortname' => 'CDT',
- 'longname' => 'Central Standard Time',
- 'dstlongname' => 'Central Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 28800000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 25200000 ),
- 'America/Recife' => array(
- 'offset' => -10800000,
- 'shortname' => 'BRT',
- 'dstshortname' => null,
- 'longname' => 'Brazil Time',
- 'dstlongname' => 'Brazil Summer Time' ),
- 'America/Regina' => array(
- 'offset' => -21600000,
- 'shortname' => 'CST',
- 'dstshortname' => null,
- 'longname' => 'Central Standard Time' ),
- 'America/Resolute' => array(
- 'offset' => -18000000,
- 'shortname' => 'EST',
- 'dstshortname' => null ),
- 'America/Rio_Branco' => array(
- 'offset' => -18000000,
- 'shortname' => 'ACT',
- 'dstshortname' => null,
- 'longname' => 'Acre Time' ),
- 'America/Rosario' => array(
- 'offset' => -10800000,
- 'shortname' => 'ART',
- 'dstshortname' => 'ARST',
- 'longname' => 'Argentine Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 10,
- 'summertimestartday' => 'Sun>=1',
- 'summertimestarttime' => 0,
- 'summertimeendmonth' => 3,
- 'summertimeendday' => 'Sun>=15',
- 'summertimeendtime' => 0 ),
- 'America/Santiago' => array(
- 'offset' => -14400000,
- 'shortname' => 'CLT',
- 'dstshortname' => 'CLST',
- 'longname' => 'Chile Time',
- 'dstlongname' => 'Chile Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 10,
- 'summertimestartday' => 'Sun>=9',
- 'summertimestarttime' => 14400000,
- 'summertimeendmonth' => 3,
- 'summertimeendday' => '30',
- 'summertimeendtime' => 10800000 ),
- 'America/Santo_Domingo' => array(
- 'offset' => -14400000,
- 'shortname' => 'AST',
- 'dstshortname' => null,
- 'longname' => 'Atlantic Standard Time' ),
- 'America/Sao_Paulo' => array(
- 'offset' => -10800000,
- 'shortname' => 'BRT',
- 'dstshortname' => 'BRST',
- 'longname' => 'Brazil Time',
- 'dstlongname' => 'Brazil Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 10,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 10800000,
- 'summertimeendmonth' => 2,
- 'summertimeendday' => 'Sun>=15',
- 'summertimeendtime' => 7200000 ),
- 'America/Scoresbysund' => array(
- 'offset' => -3600000,
- 'shortname' => 'EGT',
- 'dstshortname' => 'EGST',
- 'longname' => 'Eastern Greenland Time',
- 'dstlongname' => 'Eastern Greenland Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'America/Shiprock' => array(
- 'offset' => -25200000,
- 'shortname' => 'MST',
- 'dstshortname' => 'MDT',
- 'longname' => 'Mountain Standard Time',
- 'dstlongname' => 'Mountain Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 32400000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 28800000 ),
- 'America/St_Barthelemy' => array(
- 'offset' => -14400000,
- 'shortname' => 'AST',
- 'dstshortname' => null ),
- 'America/St_Johns' => array(
- 'offset' => -12600000,
- 'shortname' => 'NST',
- 'dstshortname' => 'NDT',
- 'longname' => 'Newfoundland Standard Time',
- 'dstlongname' => 'Newfoundland Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 12660000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 9060000 ),
- 'America/St_Kitts' => array(
- 'offset' => -14400000,
- 'shortname' => 'AST',
- 'dstshortname' => null,
- 'longname' => 'Atlantic Standard Time' ),
- 'America/St_Lucia' => array(
- 'offset' => -14400000,
- 'shortname' => 'AST',
- 'dstshortname' => null,
- 'longname' => 'Atlantic Standard Time' ),
- 'America/St_Thomas' => array(
- 'offset' => -14400000,
- 'shortname' => 'AST',
- 'dstshortname' => null,
- 'longname' => 'Atlantic Standard Time' ),
- 'America/St_Vincent' => array(
- 'offset' => -14400000,
- 'shortname' => 'AST',
- 'dstshortname' => null,
- 'longname' => 'Atlantic Standard Time' ),
- 'America/Swift_Current' => array(
- 'offset' => -21600000,
- 'shortname' => 'CST',
- 'dstshortname' => null,
- 'longname' => 'Central Standard Time' ),
- 'America/Tegucigalpa' => array(
- 'offset' => -21600000,
- 'shortname' => 'CST',
- 'dstshortname' => null,
- 'longname' => 'Central Standard Time' ),
- 'America/Thule' => array(
- 'offset' => -14400000,
- 'shortname' => 'AST',
- 'dstshortname' => 'ADT',
- 'longname' => 'Atlantic Standard Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 21600000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 18000000 ),
- 'America/Thunder_Bay' => array(
- 'offset' => -18000000,
- 'shortname' => 'EST',
- 'dstshortname' => 'EDT',
- 'longname' => 'Eastern Standard Time',
- 'dstlongname' => 'Eastern Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 25200000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 21600000 ),
- 'America/Tijuana' => array(
- 'offset' => -28800000,
- 'shortname' => 'PST',
- 'dstshortname' => 'PDT',
- 'longname' => 'Pacific Standard Time',
- 'dstlongname' => 'Pacific Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 4,
- 'summertimestartday' => 'Sun>=1',
- 'summertimestarttime' => 36000000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 32400000 ),
- 'America/Toronto' => array(
- 'offset' => -18000000,
- 'shortname' => 'EST',
- 'dstshortname' => 'EDT',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 25200000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 21600000 ),
- 'America/Tortola' => array(
- 'offset' => -14400000,
- 'shortname' => 'AST',
- 'dstshortname' => null,
- 'longname' => 'Atlantic Standard Time' ),
- 'America/Vancouver' => array(
- 'offset' => -28800000,
- 'shortname' => 'PST',
- 'dstshortname' => 'PDT',
- 'longname' => 'Pacific Standard Time',
- 'dstlongname' => 'Pacific Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 36000000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 32400000 ),
- 'America/Virgin' => array(
- 'offset' => -14400000,
- 'shortname' => 'AST',
- 'dstshortname' => null,
- 'longname' => 'Atlantic Standard Time' ),
- 'America/Whitehorse' => array(
- 'offset' => -28800000,
- 'shortname' => 'PST',
- 'dstshortname' => 'PDT',
- 'longname' => 'Pacific Standard Time',
- 'dstlongname' => 'Pacific Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 36000000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 32400000 ),
- 'America/Winnipeg' => array(
- 'offset' => -21600000,
- 'shortname' => 'CST',
- 'dstshortname' => 'CDT',
- 'longname' => 'Central Standard Time',
- 'dstlongname' => 'Central Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 28800000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 25200000 ),
- 'America/Yakutat' => array(
- 'offset' => -32400000,
- 'shortname' => 'AKST',
- 'dstshortname' => 'AKDT',
- 'longname' => 'Alaska Standard Time',
- 'dstlongname' => 'Alaska Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 39600000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 36000000 ),
- 'America/Yellowknife' => array(
- 'offset' => -25200000,
- 'shortname' => 'MST',
- 'dstshortname' => 'MDT',
- 'longname' => 'Mountain Standard Time',
- 'dstlongname' => 'Mountain Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 32400000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 28800000 ),
- 'Antarctica/Casey' => array(
- 'offset' => 28800000,
- 'shortname' => 'WST',
- 'dstshortname' => null,
- 'longname' => 'Western Standard Time (Australia)' ),
- 'Antarctica/Davis' => array(
- 'offset' => 25200000,
- 'shortname' => 'DAVT',
- 'dstshortname' => null,
- 'longname' => 'Davis Time' ),
- 'Antarctica/DumontDUrville' => array(
- 'offset' => 36000000,
- 'shortname' => 'DDUT',
- 'dstshortname' => null,
- 'longname' => 'Dumont-d\'Urville Time' ),
- 'Antarctica/Mawson' => array(
- 'offset' => 21600000,
- 'shortname' => 'MAWT',
- 'dstshortname' => null,
- 'longname' => 'Mawson Time' ),
- 'Antarctica/McMurdo' => array(
- 'offset' => 43200000,
- 'shortname' => 'NZST',
- 'dstshortname' => 'NZDT',
- 'longname' => 'New Zealand Standard Time',
- 'dstlongname' => 'New Zealand Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 9,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => -36000000,
- 'summertimeendmonth' => 4,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => -36000000 ),
- 'Antarctica/Palmer' => array(
- 'offset' => -14400000,
- 'shortname' => 'CLT',
- 'dstshortname' => 'CLST',
- 'longname' => 'Chile Time',
- 'dstlongname' => 'Chile Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 10,
- 'summertimestartday' => 'Sun>=9',
- 'summertimestarttime' => 14400000,
- 'summertimeendmonth' => 3,
- 'summertimeendday' => 'Sun>=9',
- 'summertimeendtime' => 10800000 ),
- 'Antarctica/Rothera' => array(
- 'offset' => -10800000,
- 'shortname' => 'ROTT',
- 'dstshortname' => null ),
- 'Antarctica/South_Pole' => array(
- 'offset' => 43200000,
- 'shortname' => 'NZST',
- 'dstshortname' => 'NZDT',
- 'longname' => 'New Zealand Standard Time',
- 'dstlongname' => 'New Zealand Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 9,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => -36000000,
- 'summertimeendmonth' => 4,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => -36000000 ),
- 'Antarctica/Syowa' => array(
- 'offset' => 10800000,
- 'shortname' => 'SYOT',
- 'dstshortname' => null,
- 'longname' => 'Syowa Time' ),
- 'Antarctica/Vostok' => array(
- 'offset' => 21600000,
- 'shortname' => 'VOST',
- 'dstshortname' => null,
- 'longname' => 'Vostok time' ),
- 'Arctic/Longyearbyen' => array(
- 'offset' => 3600000,
- 'shortname' => 'CET',
- 'dstshortname' => 'CEST',
- 'longname' => 'Central European Time',
- 'dstlongname' => 'Central European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Asia/Aden' => array(
- 'offset' => 10800000,
- 'shortname' => 'AST',
- 'dstshortname' => null,
- 'longname' => 'Arabia Standard Time' ),
- 'Asia/Almaty' => array(
- 'offset' => 21600000,
- 'shortname' => 'ALMT',
- 'dstshortname' => null,
- 'longname' => 'Alma-Ata Time',
- 'dstlongname' => 'Alma-Ata Summer Time' ),
- 'Asia/Amman' => array(
- 'offset' => 7200000,
- 'shortname' => 'EET',
- 'dstshortname' => 'EEST',
- 'longname' => 'Eastern European Time',
- 'dstlongname' => 'Eastern European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastThu',
- 'summertimestarttime' => -7200000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastFri',
- 'summertimeendtime' => -7200000 ),
- 'Asia/Anadyr' => array(
- 'offset' => 43200000,
- 'shortname' => 'ANAT',
- 'dstshortname' => 'ANAST',
- 'longname' => 'Anadyr Time',
- 'dstlongname' => 'Anadyr Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => -36000000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => -36000000 ),
- 'Asia/Aqtau' => array(
- 'offset' => 18000000,
- 'shortname' => 'AQTT',
- 'dstshortname' => null,
- 'longname' => 'Aqtau Time',
- 'dstlongname' => 'Aqtau Summer Time' ),
- 'Asia/Aqtobe' => array(
- 'offset' => 18000000,
- 'shortname' => 'AQTT',
- 'dstshortname' => null,
- 'longname' => 'Aqtobe Time',
- 'dstlongname' => 'Aqtobe Summer Time' ),
- 'Asia/Ashgabat' => array(
- 'offset' => 18000000,
- 'shortname' => 'TMT',
- 'dstshortname' => null,
- 'longname' => 'Turkmenistan Time' ),
- 'Asia/Ashkhabad' => array(
- 'offset' => 18000000,
- 'shortname' => 'TMT',
- 'dstshortname' => null,
- 'longname' => 'Turkmenistan Time' ),
- 'Asia/Baghdad' => array(
- 'offset' => 10800000,
- 'shortname' => 'AST',
- 'dstshortname' => 'ADT',
- 'longname' => 'Arabia Standard Time',
- 'dstlongname' => 'Arabia Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 4,
- 'summertimestartday' => '1',
- 'summertimestarttime' => 0,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => '1',
- 'summertimeendtime' => 0 ),
- 'Asia/Bahrain' => array(
- 'offset' => 10800000,
- 'shortname' => 'AST',
- 'dstshortname' => null,
- 'longname' => 'Arabia Standard Time' ),
- 'Asia/Baku' => array(
- 'offset' => 14400000,
- 'shortname' => 'AZT',
- 'dstshortname' => 'AZST',
- 'longname' => 'Azerbaijan Time',
- 'dstlongname' => 'Azerbaijan Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 0,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 0 ),
- 'Asia/Bangkok' => array(
- 'offset' => 25200000,
- 'shortname' => 'ICT',
- 'dstshortname' => null,
- 'longname' => 'Indochina Time' ),
- 'Asia/Beirut' => array(
- 'offset' => 7200000,
- 'shortname' => 'EET',
- 'dstshortname' => 'EEST',
- 'longname' => 'Eastern European Time',
- 'dstlongname' => 'Eastern European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => -7200000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => -10800000 ),
- 'Asia/Bishkek' => array(
- 'offset' => 21600000,
- 'shortname' => 'KGT',
- 'dstshortname' => null,
- 'longname' => 'Kirgizstan Time',
- 'dstlongname' => 'Kirgizstan Summer Time' ),
- 'Asia/Brunei' => array(
- 'offset' => 28800000,
- 'shortname' => 'BNT',
- 'dstshortname' => null,
- 'longname' => 'Brunei Time' ),
- 'Asia/Calcutta' => array(
- 'offset' => 19800000,
- 'shortname' => 'IST',
- 'dstshortname' => null,
- 'longname' => 'India Standard Time' ),
- 'Asia/Choibalsan' => array(
- 'offset' => 32400000,
- 'shortname' => 'CHOT',
- 'dstshortname' => null,
- 'longname' => 'Choibalsan Time' ),
- 'Asia/Chongqing' => array(
- 'offset' => 28800000,
- 'shortname' => 'CST',
- 'dstshortname' => null,
- 'longname' => 'China Standard Time' ),
- 'Asia/Chungking' => array(
- 'offset' => 28800000,
- 'shortname' => 'CST',
- 'dstshortname' => null,
- 'longname' => 'China Standard Time' ),
- 'Asia/Colombo' => array(
- 'offset' => 19800000,
- 'shortname' => 'IST',
- 'dstshortname' => null,
- 'longname' => 'India Standard Time' ),
- 'Asia/Dacca' => array(
- 'offset' => 21600000,
- 'shortname' => 'BDT',
- 'dstshortname' => null,
- 'longname' => 'Bangladesh Time' ),
- 'Asia/Damascus' => array(
- 'offset' => 7200000,
- 'shortname' => 'EET',
- 'dstshortname' => 'EEST',
- 'longname' => 'Eastern European Time',
- 'dstlongname' => 'Eastern European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastFri',
- 'summertimestarttime' => -7200000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Fri>=1',
- 'summertimeendtime' => -10800000 ),
- 'Asia/Dhaka' => array(
- 'offset' => 21600000,
- 'shortname' => 'BDT',
- 'dstshortname' => null,
- 'longname' => 'Bangladesh Time' ),
- 'Asia/Dili' => array(
- 'offset' => 32400000,
- 'shortname' => 'TLT',
- 'dstshortname' => null,
- 'longname' => 'East Timor Time' ),
- 'Asia/Dubai' => array(
- 'offset' => 14400000,
- 'shortname' => 'GST',
- 'dstshortname' => null,
- 'longname' => 'Gulf Standard Time' ),
- 'Asia/Dushanbe' => array(
- 'offset' => 18000000,
- 'shortname' => 'TJT',
- 'dstshortname' => null,
- 'longname' => 'Tajikistan Time' ),
- 'Asia/Gaza' => array(
- 'offset' => 7200000,
- 'shortname' => 'EET',
- 'dstshortname' => 'EEST',
- 'longname' => 'Eastern European Time',
- 'dstlongname' => 'Eastern European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 4,
- 'summertimestartday' => '1',
- 'summertimestarttime' => -7200000,
- 'summertimeendmonth' => 9,
- 'summertimeendday' => 'Thu>=8',
- 'summertimeendtime' => -3600000 ),
- 'Asia/Harbin' => array(
- 'offset' => 28800000,
- 'shortname' => 'CST',
- 'dstshortname' => null,
- 'longname' => 'China Standard Time' ),
- 'Asia/Hong_Kong' => array(
- 'offset' => 28800000,
- 'shortname' => 'HKT',
- 'dstshortname' => null,
- 'longname' => 'Hong Kong Time' ),
- 'Asia/Hovd' => array(
- 'offset' => 25200000,
- 'shortname' => 'HOVT',
- 'dstshortname' => null,
- 'longname' => 'Hovd Time' ),
- 'Asia/Irkutsk' => array(
- 'offset' => 28800000,
- 'shortname' => 'IRKT',
- 'dstshortname' => 'IRKST',
- 'longname' => 'Irkutsk Time',
- 'dstlongname' => 'Irkutsk Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => -21600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => -21600000 ),
- 'Asia/Istanbul' => array(
- 'offset' => 7200000,
- 'shortname' => 'EET',
- 'dstshortname' => 'EEST',
- 'longname' => 'Eastern European Time',
- 'dstlongname' => 'Eastern European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Asia/Jakarta' => array(
- 'offset' => 25200000,
- 'shortname' => 'WIT',
- 'dstshortname' => null,
- 'longname' => 'West Indonesia Time' ),
- 'Asia/Jayapura' => array(
- 'offset' => 32400000,
- 'shortname' => 'EIT',
- 'dstshortname' => null,
- 'longname' => 'East Indonesia Time' ),
- 'Asia/Jerusalem' => array(
- 'offset' => 7200000,
- 'shortname' => 'IST',
- 'dstshortname' => 'IDT',
- 'longname' => 'Israel Standard Time',
- 'dstlongname' => 'Israel Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Fri>=26',
- 'summertimestarttime' => 0,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => '5',
- 'summertimeendtime' => -3600000 ),
- 'Asia/Kabul' => array(
- 'offset' => 16200000,
- 'shortname' => 'AFT',
- 'dstshortname' => null,
- 'longname' => 'Afghanistan Time' ),
- 'Asia/Kamchatka' => array(
- 'offset' => 43200000,
- 'shortname' => 'PETT',
- 'dstshortname' => 'PETST',
- 'longname' => 'Petropavlovsk-Kamchatski Time',
- 'dstlongname' => 'Petropavlovsk-Kamchatski Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => -36000000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => -36000000 ),
- 'Asia/Karachi' => array(
- 'offset' => 18000000,
- 'shortname' => 'PKT',
- 'dstshortname' => null,
- 'longname' => 'Pakistan Time' ),
- 'Asia/Kashgar' => array(
- 'offset' => 28800000,
- 'shortname' => 'CST',
- 'dstshortname' => null,
- 'longname' => 'China Standard Time' ),
- 'Asia/Katmandu' => array(
- 'offset' => 20700000,
- 'shortname' => 'NPT',
- 'dstshortname' => null,
- 'longname' => 'Nepal Time' ),
- 'Asia/Krasnoyarsk' => array(
- 'offset' => 25200000,
- 'shortname' => 'KRAT',
- 'dstshortname' => 'KRAST',
- 'longname' => 'Krasnoyarsk Time',
- 'dstlongname' => 'Krasnoyarsk Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => -18000000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => -18000000 ),
- 'Asia/Kuala_Lumpur' => array(
- 'offset' => 28800000,
- 'shortname' => 'MYT',
- 'dstshortname' => null,
- 'longname' => 'Malaysia Time' ),
- 'Asia/Kuching' => array(
- 'offset' => 28800000,
- 'shortname' => 'MYT',
- 'dstshortname' => null,
- 'longname' => 'Malaysia Time' ),
- 'Asia/Kuwait' => array(
- 'offset' => 10800000,
- 'shortname' => 'AST',
- 'dstshortname' => null,
- 'longname' => 'Arabia Standard Time' ),
- 'Asia/Macao' => array(
- 'offset' => 28800000,
- 'shortname' => 'CST',
- 'dstshortname' => null,
- 'longname' => 'China Standard Time' ),
- 'Asia/Macau' => array(
- 'offset' => 28800000,
- 'shortname' => 'CST',
- 'dstshortname' => null ),
- 'Asia/Magadan' => array(
- 'offset' => 39600000,
- 'shortname' => 'MAGT',
- 'dstshortname' => 'MAGST',
- 'longname' => 'Magadan Time',
- 'dstlongname' => 'Magadan Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => -32400000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => -32400000 ),
- 'Asia/Makassar' => array(
- 'offset' => 28800000,
- 'shortname' => 'CIT',
- 'dstshortname' => null ),
- 'Asia/Manila' => array(
- 'offset' => 28800000,
- 'shortname' => 'PHT',
- 'dstshortname' => null,
- 'longname' => 'Philippines Time' ),
- 'Asia/Muscat' => array(
- 'offset' => 14400000,
- 'shortname' => 'GST',
- 'dstshortname' => null,
- 'longname' => 'Gulf Standard Time' ),
- 'Asia/Nicosia' => array(
- 'offset' => 7200000,
- 'shortname' => 'EET',
- 'dstshortname' => 'EEST',
- 'longname' => 'Eastern European Time',
- 'dstlongname' => 'Eastern European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Asia/Novosibirsk' => array(
- 'offset' => 21600000,
- 'shortname' => 'NOVT',
- 'dstshortname' => 'NOVST',
- 'longname' => 'Novosibirsk Time',
- 'dstlongname' => 'Novosibirsk Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => -14400000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => -14400000 ),
- 'Asia/Omsk' => array(
- 'offset' => 21600000,
- 'shortname' => 'OMST',
- 'dstshortname' => 'OMSST',
- 'longname' => 'Omsk Time',
- 'dstlongname' => 'Omsk Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => -14400000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => -14400000 ),
- 'Asia/Oral' => array(
- 'offset' => 18000000,
- 'shortname' => 'ORAT',
- 'dstshortname' => null ),
- 'Asia/Phnom_Penh' => array(
- 'offset' => 25200000,
- 'shortname' => 'ICT',
- 'dstshortname' => null,
- 'longname' => 'Indochina Time' ),
- 'Asia/Pontianak' => array(
- 'offset' => 25200000,
- 'shortname' => 'WIT',
- 'dstshortname' => null,
- 'longname' => 'West Indonesia Time' ),
- 'Asia/Pyongyang' => array(
- 'offset' => 32400000,
- 'shortname' => 'KST',
- 'dstshortname' => null,
- 'longname' => 'Korea Standard Time' ),
- 'Asia/Qatar' => array(
- 'offset' => 10800000,
- 'shortname' => 'AST',
- 'dstshortname' => null,
- 'longname' => 'Arabia Standard Time' ),
- 'Asia/Qyzylorda' => array(
- 'offset' => 21600000,
- 'shortname' => 'QYZT',
- 'dstshortname' => null ),
- 'Asia/Rangoon' => array(
- 'offset' => 23400000,
- 'shortname' => 'MMT',
- 'dstshortname' => null,
- 'longname' => 'Myanmar Time' ),
- 'Asia/Riyadh' => array(
- 'offset' => 10800000,
- 'shortname' => 'AST',
- 'dstshortname' => null,
- 'longname' => 'Arabia Standard Time' ),
- 'Asia/Riyadh87' => array(
- 'offset' => 11224000,
- 'shortname' => '',
- 'dstshortname' => null,
- 'longname' => 'GMT+03:07' ),
- 'Asia/Riyadh88' => array(
- 'offset' => 11224000,
- 'shortname' => '',
- 'dstshortname' => null,
- 'longname' => 'GMT+03:07' ),
- 'Asia/Riyadh89' => array(
- 'offset' => 11224000,
- 'shortname' => '',
- 'dstshortname' => null,
- 'longname' => 'GMT+03:07' ),
- 'Asia/Saigon' => array(
- 'offset' => 25200000,
- 'shortname' => 'ICT',
- 'dstshortname' => null,
- 'longname' => 'Indochina Time' ),
- 'Asia/Sakhalin' => array(
- 'offset' => 36000000,
- 'shortname' => 'SAKT',
- 'dstshortname' => 'SAKST',
- 'longname' => 'Sakhalin Time',
- 'dstlongname' => 'Sakhalin Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => -28800000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => -28800000 ),
- 'Asia/Samarkand' => array(
- 'offset' => 18000000,
- 'shortname' => 'UZT',
- 'dstshortname' => null,
- 'longname' => 'Turkmenistan Time' ),
- 'Asia/Seoul' => array(
- 'offset' => 32400000,
- 'shortname' => 'KST',
- 'dstshortname' => null,
- 'longname' => 'Korea Standard Time' ),
- 'Asia/Shanghai' => array(
- 'offset' => 28800000,
- 'shortname' => 'CST',
- 'dstshortname' => null,
- 'longname' => 'China Standard Time' ),
- 'Asia/Singapore' => array(
- 'offset' => 28800000,
- 'shortname' => 'SGT',
- 'dstshortname' => null,
- 'longname' => 'Singapore Time' ),
- 'Asia/Taipei' => array(
- 'offset' => 28800000,
- 'shortname' => 'CST',
- 'dstshortname' => null,
- 'longname' => 'China Standard Time' ),
- 'Asia/Tashkent' => array(
- 'offset' => 18000000,
- 'shortname' => 'UZT',
- 'dstshortname' => null,
- 'longname' => 'Uzbekistan Time' ),
- 'Asia/Tbilisi' => array(
- 'offset' => 14400000,
- 'shortname' => 'GET',
- 'dstshortname' => null,
- 'longname' => 'Georgia Time',
- 'dstlongname' => 'Georgia Summer Time' ),
- 'Asia/Tehran' => array(
- 'offset' => 12600000,
- 'shortname' => 'IRST',
- 'dstshortname' => 'IRDT',
- 'longname' => 'Iran Time',
- 'dstlongname' => 'Iran Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => '21',
- 'summertimestarttime' => -12600000,
- 'summertimeendmonth' => 9,
- 'summertimeendday' => '21',
- 'summertimeendtime' => -16200000 ),
- 'Asia/Tel_Aviv' => array(
- 'offset' => 7200000,
- 'shortname' => 'IST',
- 'dstshortname' => 'IDT',
- 'longname' => 'Israel Standard Time',
- 'dstlongname' => 'Israel Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Fri>=26',
- 'summertimestarttime' => 0,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => '5',
- 'summertimeendtime' => -3600000 ),
- 'Asia/Thimbu' => array(
- 'offset' => 21600000,
- 'shortname' => 'BTT',
- 'dstshortname' => null,
- 'longname' => 'Bhutan Time' ),
- 'Asia/Thimphu' => array(
- 'offset' => 21600000,
- 'shortname' => 'BTT',
- 'dstshortname' => null,
- 'longname' => 'Bhutan Time' ),
- 'Asia/Tokyo' => array(
- 'offset' => 32400000,
- 'shortname' => 'JST',
- 'dstshortname' => null,
- 'longname' => 'Japan Standard Time' ),
- 'Asia/Ujung_Pandang' => array(
- 'offset' => 28800000,
- 'shortname' => 'CIT',
- 'dstshortname' => null,
- 'longname' => 'Central Indonesia Time' ),
- 'Asia/Ulaanbaatar' => array(
- 'offset' => 28800000,
- 'shortname' => 'ULAT',
- 'dstshortname' => null,
- 'longname' => 'Ulaanbaatar Time' ),
- 'Asia/Ulan_Bator' => array(
- 'offset' => 28800000,
- 'shortname' => 'ULAT',
- 'dstshortname' => null,
- 'longname' => 'Ulaanbaatar Time' ),
- 'Asia/Urumqi' => array(
- 'offset' => 28800000,
- 'shortname' => 'CST',
- 'dstshortname' => null,
- 'longname' => 'China Standard Time' ),
- 'Asia/Vientiane' => array(
- 'offset' => 25200000,
- 'shortname' => 'ICT',
- 'dstshortname' => null,
- 'longname' => 'Indochina Time' ),
- 'Asia/Vladivostok' => array(
- 'offset' => 36000000,
- 'shortname' => 'VLAT',
- 'dstshortname' => 'VLAST',
- 'longname' => 'Vladivostok Time',
- 'dstlongname' => 'Vladivostok Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => -28800000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => -28800000 ),
- 'Asia/Yakutsk' => array(
- 'offset' => 32400000,
- 'shortname' => 'YAKT',
- 'dstshortname' => 'YAKST',
- 'longname' => 'Yakutsk Time',
- 'dstlongname' => 'Yaktsk Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => -25200000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => -25200000 ),
- 'Asia/Yekaterinburg' => array(
- 'offset' => 18000000,
- 'shortname' => 'YEKT',
- 'dstshortname' => 'YEKST',
- 'longname' => 'Yekaterinburg Time',
- 'dstlongname' => 'Yekaterinburg Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => -10800000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => -10800000 ),
- 'Asia/Yerevan' => array(
- 'offset' => 14400000,
- 'shortname' => 'AMT',
- 'dstshortname' => 'AMST',
- 'longname' => 'Armenia Time',
- 'dstlongname' => 'Armenia Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => -7200000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => -7200000 ),
- 'Atlantic/Azores' => array(
- 'offset' => -3600000,
- 'shortname' => 'AZOT',
- 'dstshortname' => 'AZOST',
- 'longname' => 'Azores Time',
- 'dstlongname' => 'Azores Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Atlantic/Bermuda' => array(
- 'offset' => -14400000,
- 'shortname' => 'AST',
- 'dstshortname' => 'ADT',
- 'longname' => 'Atlantic Standard Time',
- 'dstlongname' => 'Atlantic Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 21600000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 18000000 ),
- 'Atlantic/Canary' => array(
- 'offset' => 0,
- 'shortname' => 'WET',
- 'dstshortname' => 'WEST',
- 'longname' => 'Western European Time',
- 'dstlongname' => 'Western European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Atlantic/Cape_Verde' => array(
- 'offset' => -3600000,
- 'shortname' => 'CVT',
- 'dstshortname' => null,
- 'longname' => 'Cape Verde Time' ),
- 'Atlantic/Faeroe' => array(
- 'offset' => 0,
- 'shortname' => 'WET',
- 'dstshortname' => 'WEST',
- 'longname' => 'Western European Time',
- 'dstlongname' => 'Western European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Atlantic/Faroe' => array(
- 'offset' => 0,
- 'shortname' => 'WET',
- 'dstshortname' => 'WEST',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Atlantic/Jan_Mayen' => array(
- 'offset' => 3600000,
- 'shortname' => 'CET',
- 'dstshortname' => 'CEST',
- 'longname' => 'Eastern Greenland Time',
- 'dstlongname' => 'Eastern Greenland Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Atlantic/Madeira' => array(
- 'offset' => 0,
- 'shortname' => 'WET',
- 'dstshortname' => 'WEST',
- 'longname' => 'Western European Time',
- 'dstlongname' => 'Western European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Atlantic/Reykjavik' => array(
- 'offset' => 0,
- 'shortname' => 'GMT',
- 'dstshortname' => null,
- 'longname' => 'Greenwich Mean Time' ),
- 'Atlantic/South_Georgia' => array(
- 'offset' => -7200000,
- 'shortname' => 'GST',
- 'dstshortname' => null,
- 'longname' => 'South Georgia Standard Time' ),
- 'Atlantic/St_Helena' => array(
- 'offset' => 0,
- 'shortname' => 'GMT',
- 'dstshortname' => null,
- 'longname' => 'Greenwich Mean Time' ),
- 'Atlantic/Stanley' => array(
- 'offset' => -14400000,
- 'shortname' => 'FKT',
- 'dstshortname' => 'FKST',
- 'longname' => 'Falkland Is. Time',
- 'dstlongname' => 'Falkland Is. Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 9,
- 'summertimestartday' => 'Sun>=1',
- 'summertimestarttime' => 7200000,
- 'summertimeendmonth' => 4,
- 'summertimeendday' => 'Sun>=15',
- 'summertimeendtime' => 7200000 ),
- 'Australia/ACT' => array(
- 'offset' => 36000000,
- 'shortname' => 'EST',
- 'dstshortname' => 'EST',
- 'longname' => 'Eastern Standard Time (New South Wales)',
- 'dstlongname' => 'Eastern Summer Time (New South Wales)',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 10,
- 'summertimestartday' => 'Sun>=1',
- 'summertimestarttime' => -28800000,
- 'summertimeendmonth' => 4,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => -28800000 ),
- 'Australia/Adelaide' => array(
- 'offset' => 34200000,
- 'shortname' => 'CST',
- 'dstshortname' => 'CST',
- 'longname' => 'Central Standard Time (South Australia)',
- 'dstlongname' => 'Central Summer Time (South Australia)',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 10,
- 'summertimestartday' => 'Sun>=1',
- 'summertimestarttime' => -27000000,
- 'summertimeendmonth' => 4,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => -27000000 ),
- 'Australia/Brisbane' => array(
- 'offset' => 36000000,
- 'shortname' => 'EST',
- 'dstshortname' => null,
- 'longname' => 'Eastern Standard Time (Queensland)' ),
- 'Australia/Broken_Hill' => array(
- 'offset' => 34200000,
- 'shortname' => 'CST',
- 'dstshortname' => 'CST',
- 'longname' => 'Central Standard Time (South Australia/New South Wales)',
- 'dstlongname' => 'Central Summer Time (South Australia/New South Wales)',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 10,
- 'summertimestartday' => 'Sun>=1',
- 'summertimestarttime' => -27000000,
- 'summertimeendmonth' => 4,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => -27000000 ),
- 'Australia/Canberra' => array(
- 'offset' => 36000000,
- 'shortname' => 'EST',
- 'dstshortname' => 'EST',
- 'longname' => 'Eastern Standard Time (New South Wales)',
- 'dstlongname' => 'Eastern Summer Time (New South Wales)',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 10,
- 'summertimestartday' => 'Sun>=1',
- 'summertimestarttime' => -28800000,
- 'summertimeendmonth' => 4,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => -28800000 ),
- 'Australia/Currie' => array(
- 'offset' => 36000000,
- 'shortname' => 'EST',
- 'dstshortname' => 'EST',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 10,
- 'summertimestartday' => 'Sun>=1',
- 'summertimestarttime' => -28800000,
- 'summertimeendmonth' => 4,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => -28800000 ),
- 'Australia/Darwin' => array(
- 'offset' => 34200000,
- 'shortname' => 'CST',
- 'dstshortname' => null,
- 'longname' => 'Central Standard Time (Northern Territory)' ),
- 'Australia/Eucla' => array(
- 'offset' => 31500000,
- 'shortname' => 'CWST',
- 'dstshortname' => 'CWST',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 10,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => -24300000,
- 'summertimeendmonth' => 3,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => -24300000 ),
- 'Australia/Hobart' => array(
- 'offset' => 36000000,
- 'shortname' => 'EST',
- 'dstshortname' => 'EST',
- 'longname' => 'Eastern Standard Time (Tasmania)',
- 'dstlongname' => 'Eastern Summer Time (Tasmania)',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 10,
- 'summertimestartday' => 'Sun>=1',
- 'summertimestarttime' => -28800000,
- 'summertimeendmonth' => 4,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => -28800000 ),
- 'Australia/LHI' => array(
- 'offset' => 37800000,
- 'shortname' => 'LHST',
- 'dstshortname' => 'LHST',
- 'longname' => 'Load Howe Standard Time',
- 'dstlongname' => 'Load Howe Summer Time',
- 'summertimeoffset' => 1800000,
- 'summertimestartmonth' => 10,
- 'summertimestartday' => 'Sun>=1',
- 'summertimestarttime' => 7200000,
- 'summertimeendmonth' => 4,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 7200000 ),
- 'Australia/Lindeman' => array(
- 'offset' => 36000000,
- 'shortname' => 'EST',
- 'dstshortname' => null,
- 'longname' => 'Eastern Standard Time (Queensland)' ),
- 'Australia/Lord_Howe' => array(
- 'offset' => 37800000,
- 'shortname' => 'LHST',
- 'dstshortname' => 'LHST',
- 'longname' => 'Load Howe Standard Time',
- 'dstlongname' => 'Load Howe Summer Time',
- 'summertimeoffset' => 1800000,
- 'summertimestartmonth' => 10,
- 'summertimestartday' => 'Sun>=1',
- 'summertimestarttime' => 7200000,
- 'summertimeendmonth' => 4,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 7200000 ),
- 'Australia/Melbourne' => array(
- 'offset' => 36000000,
- 'shortname' => 'EST',
- 'dstshortname' => 'EST',
- 'longname' => 'Eastern Standard Time (Victoria)',
- 'dstlongname' => 'Eastern Summer Time (Victoria)',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 10,
- 'summertimestartday' => 'Sun>=1',
- 'summertimestarttime' => -28800000,
- 'summertimeendmonth' => 4,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => -28800000 ),
- 'Australia/NSW' => array(
- 'offset' => 36000000,
- 'shortname' => 'EST',
- 'dstshortname' => 'EST',
- 'longname' => 'Eastern Standard Time (New South Wales)',
- 'dstlongname' => 'Eastern Summer Time (New South Wales)',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 10,
- 'summertimestartday' => 'Sun>=1',
- 'summertimestarttime' => -28800000,
- 'summertimeendmonth' => 4,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => -28800000 ),
- 'Australia/North' => array(
- 'offset' => 34200000,
- 'shortname' => 'CST',
- 'dstshortname' => null,
- 'longname' => 'Central Standard Time (Northern Territory)' ),
- 'Australia/Perth' => array(
- 'offset' => 28800000,
- 'shortname' => 'WST',
- 'dstshortname' => 'WST',
- 'longname' => 'Western Standard Time (Australia)',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 10,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => -21600000,
- 'summertimeendmonth' => 3,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => -21600000 ),
- 'Australia/Queensland' => array(
- 'offset' => 36000000,
- 'shortname' => 'EST',
- 'dstshortname' => null,
- 'longname' => 'Eastern Standard Time (Queensland)' ),
- 'Australia/South' => array(
- 'offset' => 34200000,
- 'shortname' => 'CST',
- 'dstshortname' => 'CST',
- 'longname' => 'Central Standard Time (South Australia)',
- 'dstlongname' => 'Central Summer Time (South Australia)',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 10,
- 'summertimestartday' => 'Sun>=1',
- 'summertimestarttime' => -27000000,
- 'summertimeendmonth' => 4,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => -27000000 ),
- 'Australia/Sydney' => array(
- 'offset' => 36000000,
- 'shortname' => 'EST',
- 'dstshortname' => 'EST',
- 'longname' => 'Eastern Standard Time (New South Wales)',
- 'dstlongname' => 'Eastern Summer Time (New South Wales)',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 10,
- 'summertimestartday' => 'Sun>=1',
- 'summertimestarttime' => -28800000,
- 'summertimeendmonth' => 4,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => -28800000 ),
- 'Australia/Tasmania' => array(
- 'offset' => 36000000,
- 'shortname' => 'EST',
- 'dstshortname' => 'EST',
- 'longname' => 'Eastern Standard Time (Tasmania)',
- 'dstlongname' => 'Eastern Summer Time (Tasmania)',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 10,
- 'summertimestartday' => 'Sun>=1',
- 'summertimestarttime' => -28800000,
- 'summertimeendmonth' => 4,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => -28800000 ),
- 'Australia/Victoria' => array(
- 'offset' => 36000000,
- 'shortname' => 'EST',
- 'dstshortname' => 'EST',
- 'longname' => 'Eastern Standard Time (Victoria)',
- 'dstlongname' => 'Eastern Summer Time (Victoria)',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 10,
- 'summertimestartday' => 'Sun>=1',
- 'summertimestarttime' => -28800000,
- 'summertimeendmonth' => 4,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => -28800000 ),
- 'Australia/West' => array(
- 'offset' => 28800000,
- 'shortname' => 'WST',
- 'dstshortname' => 'WST',
- 'longname' => 'Western Standard Time (Australia)',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 10,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => -21600000,
- 'summertimeendmonth' => 3,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => -21600000 ),
- 'Australia/Yancowinna' => array(
- 'offset' => 34200000,
- 'shortname' => 'CST',
- 'dstshortname' => 'CST',
- 'longname' => 'Central Standard Time (South Australia/New South Wales)',
- 'dstlongname' => 'Central Summer Time (South Australia/New South Wales)',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 10,
- 'summertimestartday' => 'Sun>=1',
- 'summertimestarttime' => -27000000,
- 'summertimeendmonth' => 4,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => -27000000 ),
- 'Brazil/Acre' => array(
- 'offset' => -18000000,
- 'shortname' => 'ACT',
- 'dstshortname' => null,
- 'longname' => 'Acre Time' ),
- 'Brazil/DeNoronha' => array(
- 'offset' => -7200000,
- 'shortname' => 'FNT',
- 'dstshortname' => null,
- 'longname' => 'Fernando de Noronha Time' ),
- 'Brazil/East' => array(
- 'offset' => -10800000,
- 'shortname' => 'BRT',
- 'dstshortname' => 'BRST',
- 'longname' => 'Brazil Time',
- 'dstlongname' => 'Brazil Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 10,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 10800000,
- 'summertimeendmonth' => 2,
- 'summertimeendday' => 'Sun>=15',
- 'summertimeendtime' => 7200000 ),
- 'Brazil/West' => array(
- 'offset' => -14400000,
- 'shortname' => 'AMT',
- 'dstshortname' => null,
- 'longname' => 'Amazon Standard Time' ),
- 'CET' => array(
- 'offset' => 3600000,
- 'shortname' => 'CET',
- 'dstshortname' => 'CEST',
- 'longname' => 'Central European Time',
- 'dstlongname' => 'Central European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'CST6CDT' => array(
- 'offset' => -21600000,
- 'shortname' => 'CST',
- 'dstshortname' => 'CDT',
- 'longname' => 'Central Standard Time',
- 'dstlongname' => 'Central Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 28800000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 25200000 ),
- 'Canada/Atlantic' => array(
- 'offset' => -14400000,
- 'shortname' => 'AST',
- 'dstshortname' => 'ADT',
- 'longname' => 'Atlantic Standard Time',
- 'dstlongname' => 'Atlantic Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 21600000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 18000000 ),
- 'Canada/Central' => array(
- 'offset' => -21600000,
- 'shortname' => 'CST',
- 'dstshortname' => 'CDT',
- 'longname' => 'Central Standard Time',
- 'dstlongname' => 'Central Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 28800000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 25200000 ),
- 'Canada/East-Saskatchewan' => array(
- 'offset' => -21600000,
- 'shortname' => 'CST',
- 'dstshortname' => null,
- 'longname' => 'Central Standard Time' ),
- 'Canada/Eastern' => array(
- 'offset' => -18000000,
- 'shortname' => 'EST',
- 'dstshortname' => 'EDT',
- 'longname' => 'Eastern Standard Time',
- 'dstlongname' => 'Eastern Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 25200000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 21600000 ),
- 'Canada/Mountain' => array(
- 'offset' => -25200000,
- 'shortname' => 'MST',
- 'dstshortname' => 'MDT',
- 'longname' => 'Mountain Standard Time',
- 'dstlongname' => 'Mountain Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 32400000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 28800000 ),
- 'Canada/Newfoundland' => array(
- 'offset' => -12600000,
- 'shortname' => 'NST',
- 'dstshortname' => 'NDT',
- 'longname' => 'Newfoundland Standard Time',
- 'dstlongname' => 'Newfoundland Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 12660000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 9060000 ),
- 'Canada/Pacific' => array(
- 'offset' => -28800000,
- 'shortname' => 'PST',
- 'dstshortname' => 'PDT',
- 'longname' => 'Pacific Standard Time',
- 'dstlongname' => 'Pacific Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 36000000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 32400000 ),
- 'Canada/Saskatchewan' => array(
- 'offset' => -21600000,
- 'shortname' => 'CST',
- 'dstshortname' => null,
- 'longname' => 'Central Standard Time' ),
- 'Canada/Yukon' => array(
- 'offset' => -28800000,
- 'shortname' => 'PST',
- 'dstshortname' => 'PDT',
- 'longname' => 'Pacific Standard Time',
- 'dstlongname' => 'Pacific Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 36000000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 32400000 ),
- 'Chile/Continental' => array(
- 'offset' => -14400000,
- 'shortname' => 'CLT',
- 'dstshortname' => 'CLST',
- 'longname' => 'Chile Time',
- 'dstlongname' => 'Chile Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 10,
- 'summertimestartday' => 'Sun>=9',
- 'summertimestarttime' => 14400000,
- 'summertimeendmonth' => 3,
- 'summertimeendday' => '30',
- 'summertimeendtime' => 10800000 ),
- 'Chile/EasterIsland' => array(
- 'offset' => -21600000,
- 'shortname' => 'EAST',
- 'dstshortname' => 'EASST',
- 'longname' => 'Easter Is. Time',
- 'dstlongname' => 'Easter Is. Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 10,
- 'summertimestartday' => 'Sun>=9',
- 'summertimestarttime' => 14400000,
- 'summertimeendmonth' => 3,
- 'summertimeendday' => '30',
- 'summertimeendtime' => 10800000 ),
- 'Cuba' => array(
- 'offset' => -18000000,
- 'shortname' => 'CST',
- 'dstshortname' => 'CDT',
- 'longname' => 'Central Standard Time',
- 'dstlongname' => 'Central Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 18000000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 18000000 ),
- 'EET' => array(
- 'offset' => 7200000,
- 'shortname' => 'EET',
- 'dstshortname' => 'EEST',
- 'longname' => 'Eastern European Time',
- 'dstlongname' => 'Eastern European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'EST' => array(
- 'offset' => -18000000,
- 'shortname' => 'EST',
- 'dstshortname' => null,
- 'longname' => 'Eastern Standard Time',
- 'dstlongname' => 'Eastern Daylight Time' ),
- 'EST5EDT' => array(
- 'offset' => -18000000,
- 'shortname' => 'EST',
- 'dstshortname' => 'EDT',
- 'longname' => 'Eastern Standard Time',
- 'dstlongname' => 'Eastern Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 25200000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 21600000 ),
- 'Egypt' => array(
- 'offset' => 7200000,
- 'shortname' => 'EET',
- 'dstshortname' => 'EEST',
- 'longname' => 'Eastern European Time',
- 'dstlongname' => 'Eastern European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 4,
- 'summertimestartday' => 'lastFri',
- 'summertimestarttime' => -7200000,
- 'summertimeendmonth' => 8,
- 'summertimeendday' => 'lastThu',
- 'summertimeendtime' => 75600000 ),
- 'Eire' => array(
- 'offset' => 0,
- 'shortname' => 'GMT',
- 'dstshortname' => 'IST',
- 'longname' => 'Greenwich Mean Time',
- 'dstlongname' => 'Irish Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Etc/GMT' => array(
- 'offset' => 0,
- 'shortname' => 'GMT',
- 'dstshortname' => null,
- 'longname' => 'GMT+00:00' ),
- 'Etc/GMT+0' => array(
- 'offset' => 0,
- 'shortname' => 'GMT',
- 'dstshortname' => null,
- 'longname' => 'GMT+00:00' ),
- 'Etc/GMT+1' => array(
- 'offset' => -3600000,
- 'shortname' => 'GMT+1',
- 'dstshortname' => null,
- 'longname' => 'GMT-01:00' ),
- 'Etc/GMT+10' => array(
- 'offset' => -36000000,
- 'shortname' => 'GMT+10',
- 'dstshortname' => null,
- 'longname' => 'GMT-10:00' ),
- 'Etc/GMT+11' => array(
- 'offset' => -39600000,
- 'shortname' => 'GMT+11',
- 'dstshortname' => null,
- 'longname' => 'GMT-11:00' ),
- 'Etc/GMT+12' => array(
- 'offset' => -43200000,
- 'shortname' => 'GMT+12',
- 'dstshortname' => null,
- 'longname' => 'GMT-12:00' ),
- 'Etc/GMT+2' => array(
- 'offset' => -7200000,
- 'shortname' => 'GMT+2',
- 'dstshortname' => null,
- 'longname' => 'GMT-02:00' ),
- 'Etc/GMT+3' => array(
- 'offset' => -10800000,
- 'shortname' => 'GMT+3',
- 'dstshortname' => null,
- 'longname' => 'GMT-03:00' ),
- 'Etc/GMT+4' => array(
- 'offset' => -14400000,
- 'shortname' => 'GMT+4',
- 'dstshortname' => null,
- 'longname' => 'GMT-04:00' ),
- 'Etc/GMT+5' => array(
- 'offset' => -18000000,
- 'shortname' => 'GMT+5',
- 'dstshortname' => null,
- 'longname' => 'GMT-05:00' ),
- 'Etc/GMT+6' => array(
- 'offset' => -21600000,
- 'shortname' => 'GMT+6',
- 'dstshortname' => null,
- 'longname' => 'GMT-06:00' ),
- 'Etc/GMT+7' => array(
- 'offset' => -25200000,
- 'shortname' => 'GMT+7',
- 'dstshortname' => null,
- 'longname' => 'GMT-07:00' ),
- 'Etc/GMT+8' => array(
- 'offset' => -28800000,
- 'shortname' => 'GMT+8',
- 'dstshortname' => null,
- 'longname' => 'GMT-08:00' ),
- 'Etc/GMT+9' => array(
- 'offset' => -32400000,
- 'shortname' => 'GMT+9',
- 'dstshortname' => null,
- 'longname' => 'GMT-09:00' ),
- 'Etc/GMT-0' => array(
- 'offset' => 0,
- 'shortname' => 'GMT',
- 'dstshortname' => null,
- 'longname' => 'GMT+00:00' ),
- 'Etc/GMT-1' => array(
- 'offset' => 3600000,
- 'shortname' => 'GMT-1',
- 'dstshortname' => null,
- 'longname' => 'GMT+01:00' ),
- 'Etc/GMT-10' => array(
- 'offset' => 36000000,
- 'shortname' => 'GMT-10',
- 'dstshortname' => null,
- 'longname' => 'GMT+10:00' ),
- 'Etc/GMT-11' => array(
- 'offset' => 39600000,
- 'shortname' => 'GMT-11',
- 'dstshortname' => null,
- 'longname' => 'GMT+11:00' ),
- 'Etc/GMT-12' => array(
- 'offset' => 43200000,
- 'shortname' => 'GMT-12',
- 'dstshortname' => null,
- 'longname' => 'GMT+12:00' ),
- 'Etc/GMT-13' => array(
- 'offset' => 46800000,
- 'shortname' => 'GMT-13',
- 'dstshortname' => null,
- 'longname' => 'GMT+13:00' ),
- 'Etc/GMT-14' => array(
- 'offset' => 50400000,
- 'shortname' => 'GMT-14',
- 'dstshortname' => null,
- 'longname' => 'GMT+14:00' ),
- 'Etc/GMT-2' => array(
- 'offset' => 7200000,
- 'shortname' => 'GMT-2',
- 'dstshortname' => null,
- 'longname' => 'GMT+02:00' ),
- 'Etc/GMT-3' => array(
- 'offset' => 10800000,
- 'shortname' => 'GMT-3',
- 'dstshortname' => null,
- 'longname' => 'GMT+03:00' ),
- 'Etc/GMT-4' => array(
- 'offset' => 14400000,
- 'shortname' => 'GMT-4',
- 'dstshortname' => null,
- 'longname' => 'GMT+04:00' ),
- 'Etc/GMT-5' => array(
- 'offset' => 18000000,
- 'shortname' => 'GMT-5',
- 'dstshortname' => null,
- 'longname' => 'GMT+05:00' ),
- 'Etc/GMT-6' => array(
- 'offset' => 21600000,
- 'shortname' => 'GMT-6',
- 'dstshortname' => null,
- 'longname' => 'GMT+06:00' ),
- 'Etc/GMT-7' => array(
- 'offset' => 25200000,
- 'shortname' => 'GMT-7',
- 'dstshortname' => null,
- 'longname' => 'GMT+07:00' ),
- 'Etc/GMT-8' => array(
- 'offset' => 28800000,
- 'shortname' => 'GMT-8',
- 'dstshortname' => null,
- 'longname' => 'GMT+08:00' ),
- 'Etc/GMT-9' => array(
- 'offset' => 32400000,
- 'shortname' => 'GMT-9',
- 'dstshortname' => null,
- 'longname' => 'GMT+09:00' ),
- 'Etc/GMT0' => array(
- 'offset' => 0,
- 'shortname' => 'GMT',
- 'dstshortname' => null,
- 'longname' => 'GMT+00:00' ),
- 'Etc/Greenwich' => array(
- 'offset' => 0,
- 'shortname' => 'GMT',
- 'dstshortname' => null,
- 'longname' => 'Greenwich Mean Time' ),
- 'Etc/UCT' => array(
- 'offset' => 0,
- 'shortname' => 'UCT',
- 'dstshortname' => null,
- 'longname' => 'Coordinated Universal Time' ),
- 'Etc/UTC' => array(
- 'offset' => 0,
- 'shortname' => 'UTC',
- 'dstshortname' => null,
- 'longname' => 'Coordinated Universal Time' ),
- 'Etc/Universal' => array(
- 'offset' => 0,
- 'shortname' => 'UTC',
- 'dstshortname' => null,
- 'longname' => 'Coordinated Universal Time' ),
- 'Etc/Zulu' => array(
- 'offset' => 0,
- 'shortname' => 'UTC',
- 'dstshortname' => null,
- 'longname' => 'Coordinated Universal Time' ),
- 'Europe/Amsterdam' => array(
- 'offset' => 3600000,
- 'shortname' => 'CET',
- 'dstshortname' => 'CEST',
- 'longname' => 'Central European Time',
- 'dstlongname' => 'Central European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Europe/Andorra' => array(
- 'offset' => 3600000,
- 'shortname' => 'CET',
- 'dstshortname' => 'CEST',
- 'longname' => 'Central European Time',
- 'dstlongname' => 'Central European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Europe/Athens' => array(
- 'offset' => 7200000,
- 'shortname' => 'EET',
- 'dstshortname' => 'EEST',
- 'longname' => 'Eastern European Time',
- 'dstlongname' => 'Eastern European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Europe/Belfast' => array(
- 'offset' => 0,
- 'shortname' => 'GMT',
- 'dstshortname' => 'BST',
- 'longname' => 'Greenwich Mean Time',
- 'dstlongname' => 'British Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Europe/Belgrade' => array(
- 'offset' => 3600000,
- 'shortname' => 'CET',
- 'dstshortname' => 'CEST',
- 'longname' => 'Central European Time',
- 'dstlongname' => 'Central European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Europe/Berlin' => array(
- 'offset' => 3600000,
- 'shortname' => 'CET',
- 'dstshortname' => 'CEST',
- 'longname' => 'Central European Time',
- 'dstlongname' => 'Central European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Europe/Bratislava' => array(
- 'offset' => 3600000,
- 'shortname' => 'CET',
- 'dstshortname' => 'CEST',
- 'longname' => 'Central European Time',
- 'dstlongname' => 'Central European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Europe/Brussels' => array(
- 'offset' => 3600000,
- 'shortname' => 'CET',
- 'dstshortname' => 'CEST',
- 'longname' => 'Central European Time',
- 'dstlongname' => 'Central European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Europe/Bucharest' => array(
- 'offset' => 7200000,
- 'shortname' => 'EET',
- 'dstshortname' => 'EEST',
- 'longname' => 'Eastern European Time',
- 'dstlongname' => 'Eastern European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Europe/Budapest' => array(
- 'offset' => 3600000,
- 'shortname' => 'CET',
- 'dstshortname' => 'CEST',
- 'longname' => 'Central European Time',
- 'dstlongname' => 'Central European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Europe/Chisinau' => array(
- 'offset' => 7200000,
- 'shortname' => 'EET',
- 'dstshortname' => 'EEST',
- 'longname' => 'Eastern European Time',
- 'dstlongname' => 'Eastern European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Europe/Copenhagen' => array(
- 'offset' => 3600000,
- 'shortname' => 'CET',
- 'dstshortname' => 'CEST',
- 'longname' => 'Central European Time',
- 'dstlongname' => 'Central European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Europe/Dublin' => array(
- 'offset' => 0,
- 'shortname' => 'GMT',
- 'dstshortname' => 'IST',
- 'longname' => 'Greenwich Mean Time',
- 'dstlongname' => 'Irish Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Europe/Gibraltar' => array(
- 'offset' => 3600000,
- 'shortname' => 'CET',
- 'dstshortname' => 'CEST',
- 'longname' => 'Central European Time',
- 'dstlongname' => 'Central European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Europe/Guernsey' => array(
- 'offset' => 0,
- 'shortname' => 'GMT',
- 'dstshortname' => 'BST',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Europe/Helsinki' => array(
- 'offset' => 7200000,
- 'shortname' => 'EET',
- 'dstshortname' => 'EEST',
- 'longname' => 'Eastern European Time',
- 'dstlongname' => 'Eastern European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Europe/Isle_of_Man' => array(
- 'offset' => 0,
- 'shortname' => 'GMT',
- 'dstshortname' => 'BST',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Europe/Istanbul' => array(
- 'offset' => 7200000,
- 'shortname' => 'EET',
- 'dstshortname' => 'EEST',
- 'longname' => 'Eastern European Time',
- 'dstlongname' => 'Eastern European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Europe/Jersey' => array(
- 'offset' => 0,
- 'shortname' => 'GMT',
- 'dstshortname' => 'BST',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Europe/Kaliningrad' => array(
- 'offset' => 7200000,
- 'shortname' => 'EET',
- 'dstshortname' => 'EEST',
- 'longname' => 'Eastern European Time',
- 'dstlongname' => 'Eastern European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 0,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 0 ),
- 'Europe/Kiev' => array(
- 'offset' => 7200000,
- 'shortname' => 'EET',
- 'dstshortname' => 'EEST',
- 'longname' => 'Eastern European Time',
- 'dstlongname' => 'Eastern European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Europe/Lisbon' => array(
- 'offset' => 0,
- 'shortname' => 'WET',
- 'dstshortname' => 'WEST',
- 'longname' => 'Western European Time',
- 'dstlongname' => 'Western European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Europe/Ljubljana' => array(
- 'offset' => 3600000,
- 'shortname' => 'CET',
- 'dstshortname' => 'CEST',
- 'longname' => 'Central European Time',
- 'dstlongname' => 'Central European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Europe/London' => array(
- 'offset' => 0,
- 'shortname' => 'GMT',
- 'dstshortname' => 'BST',
- 'longname' => 'Greenwich Mean Time',
- 'dstlongname' => 'British Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Europe/Luxembourg' => array(
- 'offset' => 3600000,
- 'shortname' => 'CET',
- 'dstshortname' => 'CEST',
- 'longname' => 'Central European Time',
- 'dstlongname' => 'Central European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Europe/Madrid' => array(
- 'offset' => 3600000,
- 'shortname' => 'CET',
- 'dstshortname' => 'CEST',
- 'longname' => 'Central European Time',
- 'dstlongname' => 'Central European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Europe/Malta' => array(
- 'offset' => 3600000,
- 'shortname' => 'CET',
- 'dstshortname' => 'CEST',
- 'longname' => 'Central European Time',
- 'dstlongname' => 'Central European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Europe/Mariehamn' => array(
- 'offset' => 7200000,
- 'shortname' => 'EET',
- 'dstshortname' => 'EEST',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Europe/Minsk' => array(
- 'offset' => 7200000,
- 'shortname' => 'EET',
- 'dstshortname' => 'EEST',
- 'longname' => 'Eastern European Time',
- 'dstlongname' => 'Eastern European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 0,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 0 ),
- 'Europe/Monaco' => array(
- 'offset' => 3600000,
- 'shortname' => 'CET',
- 'dstshortname' => 'CEST',
- 'longname' => 'Central European Time',
- 'dstlongname' => 'Central European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Europe/Moscow' => array(
- 'offset' => 10800000,
- 'shortname' => 'MSK',
- 'dstshortname' => 'MSD',
- 'longname' => 'Moscow Standard Time',
- 'dstlongname' => 'Moscow Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => -3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => -3600000 ),
- 'Europe/Nicosia' => array(
- 'offset' => 7200000,
- 'shortname' => 'EET',
- 'dstshortname' => 'EEST',
- 'longname' => 'Eastern European Time',
- 'dstlongname' => 'Eastern European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Europe/Oslo' => array(
- 'offset' => 3600000,
- 'shortname' => 'CET',
- 'dstshortname' => 'CEST',
- 'longname' => 'Central European Time',
- 'dstlongname' => 'Central European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Europe/Paris' => array(
- 'offset' => 3600000,
- 'shortname' => 'CET',
- 'dstshortname' => 'CEST',
- 'longname' => 'Central European Time',
- 'dstlongname' => 'Central European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Europe/Podgorica' => array(
- 'offset' => 3600000,
- 'shortname' => 'CET',
- 'dstshortname' => 'CEST',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Europe/Prague' => array(
- 'offset' => 3600000,
- 'shortname' => 'CET',
- 'dstshortname' => 'CEST',
- 'longname' => 'Central European Time',
- 'dstlongname' => 'Central European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Europe/Riga' => array(
- 'offset' => 7200000,
- 'shortname' => 'EET',
- 'dstshortname' => 'EEST',
- 'longname' => 'Eastern European Time',
- 'dstlongname' => 'Eastern European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Europe/Rome' => array(
- 'offset' => 3600000,
- 'shortname' => 'CET',
- 'dstshortname' => 'CEST',
- 'longname' => 'Central European Time',
- 'dstlongname' => 'Central European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Europe/Samara' => array(
- 'offset' => 14400000,
- 'shortname' => 'SAMT',
- 'dstshortname' => 'SAMST',
- 'longname' => 'Samara Time',
- 'dstlongname' => 'Samara Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => -7200000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => -7200000 ),
- 'Europe/San_Marino' => array(
- 'offset' => 3600000,
- 'shortname' => 'CET',
- 'dstshortname' => 'CEST',
- 'longname' => 'Central European Time',
- 'dstlongname' => 'Central European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Europe/Sarajevo' => array(
- 'offset' => 3600000,
- 'shortname' => 'CET',
- 'dstshortname' => 'CEST',
- 'longname' => 'Central European Time',
- 'dstlongname' => 'Central European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Europe/Simferopol' => array(
- 'offset' => 7200000,
- 'shortname' => 'EET',
- 'dstshortname' => 'EEST',
- 'longname' => 'Eastern European Time',
- 'dstlongname' => 'Eastern European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Europe/Skopje' => array(
- 'offset' => 3600000,
- 'shortname' => 'CET',
- 'dstshortname' => 'CEST',
- 'longname' => 'Central European Time',
- 'dstlongname' => 'Central European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Europe/Sofia' => array(
- 'offset' => 7200000,
- 'shortname' => 'EET',
- 'dstshortname' => 'EEST',
- 'longname' => 'Eastern European Time',
- 'dstlongname' => 'Eastern European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Europe/Stockholm' => array(
- 'offset' => 3600000,
- 'shortname' => 'CET',
- 'dstshortname' => 'CEST',
- 'longname' => 'Central European Time',
- 'dstlongname' => 'Central European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Europe/Tallinn' => array(
- 'offset' => 7200000,
- 'shortname' => 'EET',
- 'dstshortname' => 'EEST',
- 'longname' => 'Eastern European Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Europe/Tirane' => array(
- 'offset' => 3600000,
- 'shortname' => 'CET',
- 'dstshortname' => 'CEST',
- 'longname' => 'Central European Time',
- 'dstlongname' => 'Central European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Europe/Tiraspol' => array(
- 'offset' => 7200000,
- 'shortname' => 'EET',
- 'dstshortname' => 'EEST',
- 'longname' => 'Eastern European Time',
- 'dstlongname' => 'Eastern European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Europe/Uzhgorod' => array(
- 'offset' => 7200000,
- 'shortname' => 'EET',
- 'dstshortname' => 'EEST',
- 'longname' => 'Eastern European Time',
- 'dstlongname' => 'Eastern European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Europe/Vaduz' => array(
- 'offset' => 3600000,
- 'shortname' => 'CET',
- 'dstshortname' => 'CEST',
- 'longname' => 'Central European Time',
- 'dstlongname' => 'Central European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Europe/Vatican' => array(
- 'offset' => 3600000,
- 'shortname' => 'CET',
- 'dstshortname' => 'CEST',
- 'longname' => 'Central European Time',
- 'dstlongname' => 'Central European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Europe/Vienna' => array(
- 'offset' => 3600000,
- 'shortname' => 'CET',
- 'dstshortname' => 'CEST',
- 'longname' => 'Central European Time',
- 'dstlongname' => 'Central European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Europe/Vilnius' => array(
- 'offset' => 7200000,
- 'shortname' => 'EET',
- 'dstshortname' => 'EEST',
- 'longname' => 'Eastern European Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Europe/Volgograd' => array(
- 'offset' => 10800000,
- 'shortname' => 'VOLT',
- 'dstshortname' => 'VOLST',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => -3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => -3600000 ),
- 'Europe/Warsaw' => array(
- 'offset' => 3600000,
- 'shortname' => 'CET',
- 'dstshortname' => 'CEST',
- 'longname' => 'Central European Time',
- 'dstlongname' => 'Central European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Europe/Zagreb' => array(
- 'offset' => 3600000,
- 'shortname' => 'CET',
- 'dstshortname' => 'CEST',
- 'longname' => 'Central European Time',
- 'dstlongname' => 'Central European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Europe/Zaporozhye' => array(
- 'offset' => 7200000,
- 'shortname' => 'EET',
- 'dstshortname' => 'EEST',
- 'longname' => 'Eastern European Time',
- 'dstlongname' => 'Eastern European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Europe/Zurich' => array(
- 'offset' => 3600000,
- 'shortname' => 'CET',
- 'dstshortname' => 'CEST',
- 'longname' => 'Central European Time',
- 'dstlongname' => 'Central European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'GB' => array(
- 'offset' => 0,
- 'shortname' => 'GMT',
- 'dstshortname' => 'BST',
- 'longname' => 'Greenwich Mean Time',
- 'dstlongname' => 'British Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'GB-Eire' => array(
- 'offset' => 0,
- 'shortname' => 'GMT',
- 'dstshortname' => 'BST',
- 'longname' => 'Greenwich Mean Time',
- 'dstlongname' => 'British Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'GMT' => array(
- 'offset' => 0,
- 'shortname' => 'GMT',
- 'dstshortname' => null,
- 'longname' => 'Greenwich Mean Time' ),
- 'GMT+0' => array(
- 'offset' => 0,
- 'shortname' => 'GMT+0',
- 'dstshortname' => null ),
- 'GMT+00:00' => array(
- 'offset' => 0,
- 'shortname' => 'GMT+00:00',
- 'dstshortname' => null,
- 'longname' => 'GMT+00:00' ),
- 'GMT+01:00' => array(
- 'offset' => 3600000,
- 'shortname' => 'GMT+01:00',
- 'dstshortname' => null,
- 'longname' => 'GMT+01:00' ),
- 'GMT+02:00' => array(
- 'offset' => 7200000,
- 'shortname' => 'GMT+02:00',
- 'dstshortname' => null,
- 'longname' => 'GMT+02:00' ),
- 'GMT+03:00' => array(
- 'offset' => 10800000,
- 'shortname' => 'GMT+03:00',
- 'dstshortname' => null,
- 'longname' => 'GMT+03:00' ),
- 'GMT+04:00' => array(
- 'offset' => 14400000,
- 'shortname' => 'GMT+04:00',
- 'dstshortname' => null,
- 'longname' => 'GMT+04:00' ),
- 'GMT+05:00' => array(
- 'offset' => 18000000,
- 'shortname' => 'GMT+05:00',
- 'dstshortname' => null,
- 'longname' => 'GMT+05:00' ),
- 'GMT+06:00' => array(
- 'offset' => 21600000,
- 'shortname' => 'GMT+06:00',
- 'dstshortname' => null,
- 'longname' => 'GMT+06:00' ),
- 'GMT+07:00' => array(
- 'offset' => 25200000,
- 'shortname' => 'GMT+07:00',
- 'dstshortname' => null,
- 'longname' => 'GMT+07:00' ),
- 'GMT+08:00' => array(
- 'offset' => 28800000,
- 'shortname' => 'GMT+08:00',
- 'dstshortname' => null,
- 'longname' => 'GMT+08:00' ),
- 'GMT+09:00' => array(
- 'offset' => 32400000,
- 'shortname' => 'GMT+09:00',
- 'dstshortname' => null,
- 'longname' => 'GMT+09:00' ),
- 'GMT+1' => array(
- 'offset' => 3600000,
- 'shortname' => 'GMT+1',
- 'dstshortname' => null ),
- 'GMT+10' => array(
- 'offset' => 36000000,
- 'shortname' => 'GMT+10',
- 'dstshortname' => null ),
- 'GMT+10:00' => array(
- 'offset' => 36000000,
- 'shortname' => 'GMT+10:00',
- 'dstshortname' => null,
- 'longname' => 'GMT+10:00' ),
- 'GMT+11' => array(
- 'offset' => 39600000,
- 'shortname' => 'GMT+11',
- 'dstshortname' => null ),
- 'GMT+11:00' => array(
- 'offset' => 39600000,
- 'shortname' => 'GMT+11:00',
- 'dstshortname' => null,
- 'longname' => 'GMT+11:00' ),
- 'GMT+12' => array(
- 'offset' => 43200000,
- 'shortname' => 'GMT+12',
- 'dstshortname' => null ),
- 'GMT+12:00' => array(
- 'offset' => 43200000,
- 'shortname' => 'GMT+12:00',
- 'dstshortname' => null,
- 'longname' => 'GMT+12:00' ),
- 'GMT+13' => array(
- 'offset' => 46800000,
- 'shortname' => 'GMT+13',
- 'dstshortname' => null ),
- 'GMT+13:00' => array(
- 'offset' => 46800000,
- 'shortname' => 'GMT+13:00',
- 'dstshortname' => null,
- 'longname' => 'GMT+13:00' ),
- 'GMT+14' => array(
- 'offset' => 50400000,
- 'shortname' => 'GMT+14',
- 'dstshortname' => null ),
- 'GMT+14:00' => array(
- 'offset' => 50400000,
- 'shortname' => 'GMT+14:00',
- 'dstshortname' => null,
- 'longname' => 'GMT+14:00' ),
- 'GMT+2' => array(
- 'offset' => 7200000,
- 'shortname' => 'GMT+2',
- 'dstshortname' => null ),
- 'GMT+3' => array(
- 'offset' => 10800000,
- 'shortname' => 'GMT+3',
- 'dstshortname' => null ),
- 'GMT+4' => array(
- 'offset' => 14400000,
- 'shortname' => 'GMT+4',
- 'dstshortname' => null ),
- 'GMT+5' => array(
- 'offset' => 18000000,
- 'shortname' => 'GMT+5',
- 'dstshortname' => null ),
- 'GMT+6' => array(
- 'offset' => 21600000,
- 'shortname' => 'GMT+6',
- 'dstshortname' => null ),
- 'GMT+7' => array(
- 'offset' => 25200000,
- 'shortname' => 'GMT+7',
- 'dstshortname' => null ),
- 'GMT+8' => array(
- 'offset' => 28800000,
- 'shortname' => 'GMT+8',
- 'dstshortname' => null ),
- 'GMT+9' => array(
- 'offset' => 32400000,
- 'shortname' => 'GMT+9',
- 'dstshortname' => null ),
- 'GMT-0' => array(
- 'offset' => 0,
- 'shortname' => 'GMT-0',
- 'dstshortname' => null ),
- 'GMT-00:00' => array(
- 'offset' => 0,
- 'shortname' => 'GMT-00:00',
- 'dstshortname' => null ),
- 'GMT-01:00' => array(
- 'offset' => -3600000,
- 'shortname' => 'GMT-01:00',
- 'dstshortname' => null,
- 'longname' => 'GMT-01:00' ),
- 'GMT-02:00' => array(
- 'offset' => -7200000,
- 'shortname' => 'GMT-02:00',
- 'dstshortname' => null,
- 'longname' => 'GMT-02:00' ),
- 'GMT-03:00' => array(
- 'offset' => -10800000,
- 'shortname' => 'GMT-03:00',
- 'dstshortname' => null,
- 'longname' => 'GMT-03:00' ),
- 'GMT-04:00' => array(
- 'offset' => -14400000,
- 'shortname' => 'GMT-04:00',
- 'dstshortname' => null,
- 'longname' => 'GMT-04:00' ),
- 'GMT-05:00' => array(
- 'offset' => -18000000,
- 'shortname' => 'GMT-05:00',
- 'dstshortname' => null,
- 'longname' => 'GMT-05:00' ),
- 'GMT-06:00' => array(
- 'offset' => -21600000,
- 'shortname' => 'GMT-06:00',
- 'dstshortname' => null,
- 'longname' => 'GMT-06:00' ),
- 'GMT-07:00' => array(
- 'offset' => -25200000,
- 'shortname' => 'GMT-07:00',
- 'dstshortname' => null,
- 'longname' => 'GMT-07:00' ),
- 'GMT-08:00' => array(
- 'offset' => -28800000,
- 'shortname' => 'GMT-08:00',
- 'dstshortname' => null,
- 'longname' => 'GMT-08:00' ),
- 'GMT-09:00' => array(
- 'offset' => -32400000,
- 'shortname' => 'GMT-09:00',
- 'dstshortname' => null,
- 'longname' => 'GMT-09:00' ),
- 'GMT-1' => array(
- 'offset' => -3600000,
- 'shortname' => 'GMT-1',
- 'dstshortname' => null ),
- 'GMT-10' => array(
- 'offset' => -36000000,
- 'shortname' => 'GMT-10',
- 'dstshortname' => null ),
- 'GMT-10:00' => array(
- 'offset' => -36000000,
- 'shortname' => 'GMT-10:00',
- 'dstshortname' => null,
- 'longname' => 'GMT-10:00' ),
- 'GMT-11' => array(
- 'offset' => -39600000,
- 'shortname' => 'GMT-11',
- 'dstshortname' => null ),
- 'GMT-11:00' => array(
- 'offset' => -39600000,
- 'shortname' => 'GMT-11:00',
- 'dstshortname' => null,
- 'longname' => 'GMT-11:00' ),
- 'GMT-12' => array(
- 'offset' => -43200000,
- 'shortname' => 'GMT-12',
- 'dstshortname' => null ),
- 'GMT-12:00' => array(
- 'offset' => -43200000,
- 'shortname' => 'GMT-12:00',
- 'dstshortname' => null,
- 'longname' => 'GMT-12:00' ),
- 'GMT-2' => array(
- 'offset' => -7200000,
- 'shortname' => 'GMT-2',
- 'dstshortname' => null ),
- 'GMT-3' => array(
- 'offset' => -10800000,
- 'shortname' => 'GMT-3',
- 'dstshortname' => null ),
- 'GMT-4' => array(
- 'offset' => -14400000,
- 'shortname' => 'GMT-4',
- 'dstshortname' => null ),
- 'GMT-5' => array(
- 'offset' => -18000000,
- 'shortname' => 'GMT-5',
- 'dstshortname' => null ),
- 'GMT-6' => array(
- 'offset' => -21600000,
- 'shortname' => 'GMT-6',
- 'dstshortname' => null ),
- 'GMT-7' => array(
- 'offset' => -25200000,
- 'shortname' => 'GMT-7',
- 'dstshortname' => null ),
- 'GMT-8' => array(
- 'offset' => -28800000,
- 'shortname' => 'GMT-8',
- 'dstshortname' => null ),
- 'GMT-9' => array(
- 'offset' => -32400000,
- 'shortname' => 'GMT-9',
- 'dstshortname' => null ),
- 'GMT0' => array(
- 'offset' => 0,
- 'shortname' => 'GMT',
- 'dstshortname' => null,
- 'longname' => 'GMT+00:00' ),
- 'Greenwich' => array(
- 'offset' => 0,
- 'shortname' => 'GMT',
- 'dstshortname' => null,
- 'longname' => 'Greenwich Mean Time' ),
- 'HST' => array(
- 'offset' => -36000000,
- 'shortname' => 'HST',
- 'dstshortname' => null,
- 'longname' => 'Hawaii Standard Time' ),
- 'Hongkong' => array(
- 'offset' => 28800000,
- 'shortname' => 'HKT',
- 'dstshortname' => null,
- 'longname' => 'Hong Kong Time' ),
- 'Iceland' => array(
- 'offset' => 0,
- 'shortname' => 'GMT',
- 'dstshortname' => null,
- 'longname' => 'Greenwich Mean Time' ),
- 'Indian/Antananarivo' => array(
- 'offset' => 10800000,
- 'shortname' => 'EAT',
- 'dstshortname' => null,
- 'longname' => 'Eastern African Time' ),
- 'Indian/Chagos' => array(
- 'offset' => 21600000,
- 'shortname' => 'IOT',
- 'dstshortname' => null,
- 'longname' => 'Indian Ocean Territory Time' ),
- 'Indian/Christmas' => array(
- 'offset' => 25200000,
- 'shortname' => 'CXT',
- 'dstshortname' => null,
- 'longname' => 'Christmas Island Time' ),
- 'Indian/Cocos' => array(
- 'offset' => 23400000,
- 'shortname' => 'CCT',
- 'dstshortname' => null,
- 'longname' => 'Cocos Islands Time' ),
- 'Indian/Comoro' => array(
- 'offset' => 10800000,
- 'shortname' => 'EAT',
- 'dstshortname' => null,
- 'longname' => 'Eastern African Time' ),
- 'Indian/Kerguelen' => array(
- 'offset' => 18000000,
- 'shortname' => 'TFT',
- 'dstshortname' => null,
- 'longname' => 'French Southern & Antarctic Lands Time' ),
- 'Indian/Mahe' => array(
- 'offset' => 14400000,
- 'shortname' => 'SCT',
- 'dstshortname' => null,
- 'longname' => 'Seychelles Time' ),
- 'Indian/Maldives' => array(
- 'offset' => 18000000,
- 'shortname' => 'MVT',
- 'dstshortname' => null,
- 'longname' => 'Maldives Time' ),
- 'Indian/Mauritius' => array(
- 'offset' => 14400000,
- 'shortname' => 'MUT',
- 'dstshortname' => null,
- 'longname' => 'Mauritius Time' ),
- 'Indian/Mayotte' => array(
- 'offset' => 10800000,
- 'shortname' => 'EAT',
- 'dstshortname' => null,
- 'longname' => 'Eastern African Time' ),
- 'Indian/Reunion' => array(
- 'offset' => 14400000,
- 'shortname' => 'RET',
- 'dstshortname' => null,
- 'longname' => 'Reunion Time' ),
- 'Iran' => array(
- 'offset' => 12600000,
- 'shortname' => 'IRST',
- 'dstshortname' => 'IRDT',
- 'longname' => 'Iran Time',
- 'dstlongname' => 'Iran Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => '21',
- 'summertimestarttime' => -12600000,
- 'summertimeendmonth' => 9,
- 'summertimeendday' => '21',
- 'summertimeendtime' => -16200000 ),
- 'Israel' => array(
- 'offset' => 7200000,
- 'shortname' => 'IST',
- 'dstshortname' => 'IDT',
- 'longname' => 'Israel Standard Time',
- 'dstlongname' => 'Israel Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Fri>=26',
- 'summertimestarttime' => 0,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => '5',
- 'summertimeendtime' => -3600000 ),
- 'Jamaica' => array(
- 'offset' => -18000000,
- 'shortname' => 'EST',
- 'dstshortname' => null,
- 'longname' => 'Eastern Standard Time' ),
- 'Japan' => array(
- 'offset' => 32400000,
- 'shortname' => 'JST',
- 'dstshortname' => null,
- 'longname' => 'Japan Standard Time' ),
- 'Kwajalein' => array(
- 'offset' => 43200000,
- 'shortname' => 'MHT',
- 'dstshortname' => null,
- 'longname' => 'Marshall Islands Time' ),
- 'Libya' => array(
- 'offset' => 7200000,
- 'shortname' => 'EET',
- 'dstshortname' => null,
- 'longname' => 'Eastern European Time' ),
- 'MET' => array(
- 'offset' => 3600000,
- 'shortname' => 'MET',
- 'dstshortname' => 'MEST',
- 'longname' => 'Middle Europe Time',
- 'dstlongname' => 'Middle Europe Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'MST' => array(
- 'offset' => -25200000,
- 'shortname' => 'MST',
- 'dstshortname' => null,
- 'longname' => 'Mountain Standard Time',
- 'dstlongname' => 'Mountain Daylight Time' ),
- 'MST7MDT' => array(
- 'offset' => -25200000,
- 'shortname' => 'MST',
- 'dstshortname' => 'MDT',
- 'longname' => 'Mountain Standard Time',
- 'dstlongname' => 'Mountain Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 32400000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 28800000 ),
- 'Mexico/BajaNorte' => array(
- 'offset' => -28800000,
- 'shortname' => 'PST',
- 'dstshortname' => 'PDT',
- 'longname' => 'Pacific Standard Time',
- 'dstlongname' => 'Pacific Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 4,
- 'summertimestartday' => 'Sun>=1',
- 'summertimestarttime' => 36000000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 32400000 ),
- 'Mexico/BajaSur' => array(
- 'offset' => -25200000,
- 'shortname' => 'MST',
- 'dstshortname' => 'MDT',
- 'longname' => 'Mountain Standard Time',
- 'dstlongname' => 'Mountain Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 4,
- 'summertimestartday' => 'Sun>=1',
- 'summertimestarttime' => 32400000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 28800000 ),
- 'Mexico/General' => array(
- 'offset' => -21600000,
- 'shortname' => 'CST',
- 'dstshortname' => 'CDT',
- 'longname' => 'Central Standard Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 4,
- 'summertimestartday' => 'Sun>=1',
- 'summertimestarttime' => 28800000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 25200000 ),
- 'Mideast/Riyadh87' => array(
- 'offset' => 11224000,
- 'shortname' => '',
- 'dstshortname' => null,
- 'longname' => 'GMT+03:07' ),
- 'Mideast/Riyadh88' => array(
- 'offset' => 11224000,
- 'shortname' => '',
- 'dstshortname' => null,
- 'longname' => 'GMT+03:07' ),
- 'Mideast/Riyadh89' => array(
- 'offset' => 11224000,
- 'shortname' => '',
- 'dstshortname' => null,
- 'longname' => 'GMT+03:07' ),
- 'NZ' => array(
- 'offset' => 43200000,
- 'shortname' => 'NZST',
- 'dstshortname' => 'NZDT',
- 'longname' => 'New Zealand Standard Time',
- 'dstlongname' => 'New Zealand Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 9,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => -36000000,
- 'summertimeendmonth' => 4,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => -36000000 ),
- 'NZ-CHAT' => array(
- 'offset' => 45900000,
- 'shortname' => 'CHAST',
- 'dstshortname' => 'CHADT',
- 'longname' => 'Chatham Standard Time',
- 'dstlongname' => 'Chatham Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 9,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => -36000000,
- 'summertimeendmonth' => 4,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => -36000000 ),
- 'Navajo' => array(
- 'offset' => -25200000,
- 'shortname' => 'MST',
- 'dstshortname' => 'MDT',
- 'longname' => 'Mountain Standard Time',
- 'dstlongname' => 'Mountain Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 32400000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 28800000 ),
- 'PRC' => array(
- 'offset' => 28800000,
- 'shortname' => 'CST',
- 'dstshortname' => null,
- 'longname' => 'China Standard Time' ),
- 'PST8PDT' => array(
- 'offset' => -28800000,
- 'shortname' => 'PST',
- 'dstshortname' => 'PDT',
- 'longname' => 'Pacific Standard Time',
- 'dstlongname' => 'Pacific Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 36000000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 32400000 ),
- 'Pacific/Apia' => array(
- 'offset' => -39600000,
- 'shortname' => 'WST',
- 'dstshortname' => null,
- 'longname' => 'West Samoa Time' ),
- 'Pacific/Auckland' => array(
- 'offset' => 43200000,
- 'shortname' => 'NZST',
- 'dstshortname' => 'NZDT',
- 'longname' => 'New Zealand Standard Time',
- 'dstlongname' => 'New Zealand Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 9,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => -36000000,
- 'summertimeendmonth' => 4,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => -36000000 ),
- 'Pacific/Chatham' => array(
- 'offset' => 45900000,
- 'shortname' => 'CHAST',
- 'dstshortname' => 'CHADT',
- 'longname' => 'Chatham Standard Time',
- 'dstlongname' => 'Chatham Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 9,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => -36000000,
- 'summertimeendmonth' => 4,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => -36000000 ),
- 'Pacific/Easter' => array(
- 'offset' => -21600000,
- 'shortname' => 'EAST',
- 'dstshortname' => 'EASST',
- 'longname' => 'Easter Is. Time',
- 'dstlongname' => 'Easter Is. Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 10,
- 'summertimestartday' => 'Sun>=9',
- 'summertimestarttime' => 14400000,
- 'summertimeendmonth' => 3,
- 'summertimeendday' => '30',
- 'summertimeendtime' => 10800000 ),
- 'Pacific/Efate' => array(
- 'offset' => 39600000,
- 'shortname' => 'VUT',
- 'dstshortname' => null,
- 'longname' => 'Vanuatu Time' ),
- 'Pacific/Enderbury' => array(
- 'offset' => 46800000,
- 'shortname' => 'PHOT',
- 'dstshortname' => null,
- 'longname' => 'Phoenix Is. Time' ),
- 'Pacific/Fakaofo' => array(
- 'offset' => -36000000,
- 'shortname' => 'TKT',
- 'dstshortname' => null,
- 'longname' => 'Tokelau Time' ),
- 'Pacific/Fiji' => array(
- 'offset' => 43200000,
- 'shortname' => 'FJT',
- 'dstshortname' => null,
- 'longname' => 'Fiji Time' ),
- 'Pacific/Funafuti' => array(
- 'offset' => 43200000,
- 'shortname' => 'TVT',
- 'dstshortname' => null,
- 'longname' => 'Tuvalu Time' ),
- 'Pacific/Galapagos' => array(
- 'offset' => -21600000,
- 'shortname' => 'GALT',
- 'dstshortname' => null,
- 'longname' => 'Galapagos Time' ),
- 'Pacific/Gambier' => array(
- 'offset' => -32400000,
- 'shortname' => 'GAMT',
- 'dstshortname' => null,
- 'longname' => 'Gambier Time' ),
- 'Pacific/Guadalcanal' => array(
- 'offset' => 39600000,
- 'shortname' => 'SBT',
- 'dstshortname' => null,
- 'longname' => 'Solomon Is. Time' ),
- 'Pacific/Guam' => array(
- 'offset' => 36000000,
- 'shortname' => 'ChST',
- 'dstshortname' => null,
- 'longname' => 'Chamorro Standard Time' ),
- 'Pacific/Honolulu' => array(
- 'offset' => -36000000,
- 'shortname' => 'HST',
- 'dstshortname' => null,
- 'longname' => 'Hawaii Standard Time' ),
- 'Pacific/Johnston' => array(
- 'offset' => -36000000,
- 'shortname' => 'HST',
- 'dstshortname' => null,
- 'longname' => 'Hawaii Standard Time' ),
- 'Pacific/Kiritimati' => array(
- 'offset' => 50400000,
- 'shortname' => 'LINT',
- 'dstshortname' => null,
- 'longname' => 'Line Is. Time' ),
- 'Pacific/Kosrae' => array(
- 'offset' => 39600000,
- 'shortname' => 'KOST',
- 'dstshortname' => null,
- 'longname' => 'Kosrae Time' ),
- 'Pacific/Kwajalein' => array(
- 'offset' => 43200000,
- 'shortname' => 'MHT',
- 'dstshortname' => null,
- 'longname' => 'Marshall Islands Time' ),
- 'Pacific/Majuro' => array(
- 'offset' => 43200000,
- 'shortname' => 'MHT',
- 'dstshortname' => null,
- 'longname' => 'Marshall Islands Time' ),
- 'Pacific/Marquesas' => array(
- 'offset' => -34200000,
- 'shortname' => 'MART',
- 'dstshortname' => null,
- 'longname' => 'Marquesas Time' ),
- 'Pacific/Midway' => array(
- 'offset' => -39600000,
- 'shortname' => 'SST',
- 'dstshortname' => null,
- 'longname' => 'Samoa Standard Time' ),
- 'Pacific/Nauru' => array(
- 'offset' => 43200000,
- 'shortname' => 'NRT',
- 'dstshortname' => null,
- 'longname' => 'Nauru Time' ),
- 'Pacific/Niue' => array(
- 'offset' => -39600000,
- 'shortname' => 'NUT',
- 'dstshortname' => null,
- 'longname' => 'Niue Time' ),
- 'Pacific/Norfolk' => array(
- 'offset' => 41400000,
- 'shortname' => 'NFT',
- 'dstshortname' => null,
- 'longname' => 'Norfolk Time' ),
- 'Pacific/Noumea' => array(
- 'offset' => 39600000,
- 'shortname' => 'NCT',
- 'dstshortname' => null,
- 'longname' => 'New Caledonia Time' ),
- 'Pacific/Pago_Pago' => array(
- 'offset' => -39600000,
- 'shortname' => 'SST',
- 'dstshortname' => null,
- 'longname' => 'Samoa Standard Time' ),
- 'Pacific/Palau' => array(
- 'offset' => 32400000,
- 'shortname' => 'PWT',
- 'dstshortname' => null,
- 'longname' => 'Palau Time' ),
- 'Pacific/Pitcairn' => array(
- 'offset' => -28800000,
- 'shortname' => 'PST',
- 'dstshortname' => null,
- 'longname' => 'Pitcairn Standard Time' ),
- 'Pacific/Ponape' => array(
- 'offset' => 39600000,
- 'shortname' => 'PONT',
- 'dstshortname' => null,
- 'longname' => 'Ponape Time' ),
- 'Pacific/Port_Moresby' => array(
- 'offset' => 36000000,
- 'shortname' => 'PGT',
- 'dstshortname' => null,
- 'longname' => 'Papua New Guinea Time' ),
- 'Pacific/Rarotonga' => array(
- 'offset' => -36000000,
- 'shortname' => 'CKT',
- 'dstshortname' => null,
- 'longname' => 'Cook Is. Time' ),
- 'Pacific/Saipan' => array(
- 'offset' => 36000000,
- 'shortname' => 'ChST',
- 'dstshortname' => null,
- 'longname' => 'Chamorro Standard Time' ),
- 'Pacific/Samoa' => array(
- 'offset' => -39600000,
- 'shortname' => 'SST',
- 'dstshortname' => null,
- 'longname' => 'Samoa Standard Time' ),
- 'Pacific/Tahiti' => array(
- 'offset' => -36000000,
- 'shortname' => 'TAHT',
- 'dstshortname' => null,
- 'longname' => 'Tahiti Time' ),
- 'Pacific/Tarawa' => array(
- 'offset' => 43200000,
- 'shortname' => 'GILT',
- 'dstshortname' => null,
- 'longname' => 'Gilbert Is. Time' ),
- 'Pacific/Tongatapu' => array(
- 'offset' => 46800000,
- 'shortname' => 'TOT',
- 'dstshortname' => null,
- 'longname' => 'Tonga Time' ),
- 'Pacific/Truk' => array(
- 'offset' => 36000000,
- 'shortname' => 'TRUT',
- 'dstshortname' => null,
- 'longname' => 'Truk Time' ),
- 'Pacific/Wake' => array(
- 'offset' => 43200000,
- 'shortname' => 'WAKT',
- 'dstshortname' => null,
- 'longname' => 'Wake Time' ),
- 'Pacific/Wallis' => array(
- 'offset' => 43200000,
- 'shortname' => 'WFT',
- 'dstshortname' => null,
- 'longname' => 'Wallis & Futuna Time' ),
- 'Pacific/Yap' => array(
- 'offset' => 36000000,
- 'shortname' => 'TRUT',
- 'dstshortname' => null,
- 'longname' => 'Yap Time' ),
- 'Poland' => array(
- 'offset' => 3600000,
- 'shortname' => 'CET',
- 'dstshortname' => 'CEST',
- 'longname' => 'Central European Time',
- 'dstlongname' => 'Central European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Portugal' => array(
- 'offset' => 0,
- 'shortname' => 'WET',
- 'dstshortname' => 'WEST',
- 'longname' => 'Western European Time',
- 'dstlongname' => 'Western European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'ROC' => array(
- 'offset' => 28800000,
- 'shortname' => 'CST',
- 'dstshortname' => null ),
- 'ROK' => array(
- 'offset' => 32400000,
- 'shortname' => 'KST',
- 'dstshortname' => null,
- 'longname' => 'Korea Standard Time' ),
- 'Singapore' => array(
- 'offset' => 28800000,
- 'shortname' => 'SGT',
- 'dstshortname' => null,
- 'longname' => 'Singapore Time' ),
- 'Turkey' => array(
- 'offset' => 7200000,
- 'shortname' => 'EET',
- 'dstshortname' => 'EEST',
- 'longname' => 'Eastern European Time',
- 'dstlongname' => 'Eastern European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'UCT' => array(
- 'offset' => 0,
- 'shortname' => 'UCT',
- 'dstshortname' => null,
- 'longname' => 'Coordinated Universal Time' ),
- 'US/Alaska' => array(
- 'offset' => -32400000,
- 'shortname' => 'AKST',
- 'dstshortname' => 'AKDT',
- 'longname' => 'Alaska Standard Time',
- 'dstlongname' => 'Alaska Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 39600000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 36000000 ),
- 'US/Aleutian' => array(
- 'offset' => -36000000,
- 'shortname' => 'HAST',
- 'dstshortname' => 'HADT',
- 'longname' => 'Hawaii-Aleutian Standard Time',
- 'dstlongname' => 'Hawaii-Aleutian Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 43200000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 39600000 ),
- 'US/Arizona' => array(
- 'offset' => -25200000,
- 'shortname' => 'MST',
- 'dstshortname' => null,
- 'longname' => 'Mountain Standard Time' ),
- 'US/Central' => array(
- 'offset' => -21600000,
- 'shortname' => 'CST',
- 'dstshortname' => 'CDT',
- 'longname' => 'Central Standard Time',
- 'dstlongname' => 'Central Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 28800000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 25200000 ),
- 'US/East-Indiana' => array(
- 'offset' => -18000000,
- 'shortname' => 'EST',
- 'dstshortname' => 'EDT',
- 'longname' => 'Eastern Standard Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 25200000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 21600000 ),
- 'US/Eastern' => array(
- 'offset' => -18000000,
- 'shortname' => 'EST',
- 'dstshortname' => 'EDT',
- 'longname' => 'Eastern Standard Time',
- 'dstlongname' => 'Eastern Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 25200000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 21600000 ),
- 'US/Hawaii' => array(
- 'offset' => -36000000,
- 'shortname' => 'HST',
- 'dstshortname' => null,
- 'longname' => 'Hawaii Standard Time' ),
- 'US/Indiana-Starke' => array(
- 'offset' => -21600000,
- 'shortname' => 'CST',
- 'dstshortname' => 'CDT',
- 'longname' => 'Central Standard Time',
- 'dstlongname' => 'Central Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 28800000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 25200000 ),
- 'US/Michigan' => array(
- 'offset' => -18000000,
- 'shortname' => 'EST',
- 'dstshortname' => 'EDT',
- 'longname' => 'Eastern Standard Time',
- 'dstlongname' => 'Eastern Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 25200000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 21600000 ),
- 'US/Mountain' => array(
- 'offset' => -25200000,
- 'shortname' => 'MST',
- 'dstshortname' => 'MDT',
- 'longname' => 'Mountain Standard Time',
- 'dstlongname' => 'Mountain Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 32400000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 28800000 ),
- 'US/Pacific' => array(
- 'offset' => -28800000,
- 'shortname' => 'PST',
- 'dstshortname' => 'PDT',
- 'longname' => 'Pacific Standard Time',
- 'dstlongname' => 'Pacific Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 36000000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 32400000 ),
- 'US/Pacific-New' => array(
- 'offset' => -28800000,
- 'shortname' => 'PST',
- 'dstshortname' => 'PDT',
- 'longname' => 'Pacific Standard Time',
- 'dstlongname' => 'Pacific Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'Sun>=8',
- 'summertimestarttime' => 36000000,
- 'summertimeendmonth' => 11,
- 'summertimeendday' => 'Sun>=1',
- 'summertimeendtime' => 32400000 ),
- 'US/Samoa' => array(
- 'offset' => -39600000,
- 'shortname' => 'SST',
- 'dstshortname' => null,
- 'longname' => 'Samoa Standard Time' ),
- 'UTC' => array(
- 'offset' => 0,
- 'shortname' => 'UTC',
- 'dstshortname' => null,
- 'longname' => 'Coordinated Universal Time' ),
- 'Universal' => array(
- 'offset' => 0,
- 'shortname' => 'UTC',
- 'dstshortname' => null,
- 'longname' => 'Coordinated Universal Time' ),
- 'W-SU' => array(
- 'offset' => 10800000,
- 'shortname' => 'MSK',
- 'dstshortname' => 'MSD',
- 'longname' => 'Moscow Standard Time',
- 'dstlongname' => 'Moscow Daylight Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => -3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => -3600000 ),
- 'WET' => array(
- 'offset' => 0,
- 'shortname' => 'WET',
- 'dstshortname' => 'WEST',
- 'longname' => 'Western European Time',
- 'dstlongname' => 'Western European Summer Time',
- 'summertimeoffset' => 3600000,
- 'summertimestartmonth' => 3,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 3600000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 3600000 ),
- 'Zulu' => array(
- 'offset' => 0,
- 'shortname' => 'UTC',
- 'dstshortname' => null,
- 'longname' => 'Coordinated Universal Time' ),
- //
- // Following time-zones are the long names for the time-zones above, thus N.B.
- // that the Summer-Time for each zone cannot really be reliable, because two
- // zones may share the same zone name, but differ in Summer-Time arrangements;
- // and also that the data cannot be maintained as easily and thus may also
- // be inaccurate or out-of-date
- //
- 'ACT' => array(
- 'offset' => 34200000,
- 'shortname' => 'CST',
- 'longname' => 'Central Standard Time (Northern Territory)' ),
- 'AET' => array(
- 'offset' => 36000000,
- 'shortname' => 'EST',
- 'dstshortname' => 'EST',
- 'longname' => 'Eastern Standard Time (New South Wales)',
- 'dstlongname' => 'Eastern Summer Time (New South Wales)' ),
- 'AGT' => array(
- 'offset' => -10800000,
- 'shortname' => 'ART',
- 'longname' => 'Argentine Time' ),
- 'ART' => array(
- 'offset' => 7200000,
- 'shortname' => 'EET',
- 'dstshortname' => 'EEST',
- 'longname' => 'Eastern European Time',
- 'dstlongname' => 'Eastern European Summer Time' ),
- 'AST' => array(
- 'offset' => -32400000,
- 'shortname' => 'AKST',
- 'dstshortname' => 'AKDT',
- 'longname' => 'Alaska Standard Time',
- 'dstlongname' => 'Alaska Daylight Time' ),
- 'Acre Time' => array(
- 'offset' => -18000000,
- 'shortname' => 'ACT',
- 'longname' => 'Acre Time' ),
- 'Afghanistan Time' => array(
- 'offset' => 16200000,
- 'shortname' => 'AFT',
- 'longname' => 'Afghanistan Time' ),
- 'Alaska Standard Time' => array(
- 'offset' => -32400000,
- 'shortname' => 'AKST',
- 'dstshortname' => 'AKDT',
- 'longname' => 'Alaska Standard Time',
- 'dstlongname' => 'Alaska Daylight Time' ),
- 'Alma-Ata Time' => array(
- 'offset' => 21600000,
- 'shortname' => 'ALMT',
- 'dstshortname' => 'ALMST',
- 'longname' => 'Alma-Ata Time',
- 'dstlongname' => 'Alma-Ata Summer Time' ),
- 'Amazon Standard Time' => array(
- 'offset' => -14400000,
- 'shortname' => 'AMT',
- 'longname' => 'Amazon Standard Time' ),
- 'Anadyr Time' => array(
- 'offset' => 43200000,
- 'shortname' => 'ANAT',
- 'dstshortname' => 'ANAST',
- 'longname' => 'Anadyr Time',
- 'dstlongname' => 'Anadyr Summer Time' ),
- 'Aqtau Time' => array(
- 'offset' => 14400000,
- 'shortname' => 'AQTT',
- 'dstshortname' => 'AQTST',
- 'longname' => 'Aqtau Time',
- 'dstlongname' => 'Aqtau Summer Time' ),
- 'Aqtobe Time' => array(
- 'offset' => 18000000,
- 'shortname' => 'AQTT',
- 'dstshortname' => 'AQTST',
- 'longname' => 'Aqtobe Time',
- 'dstlongname' => 'Aqtobe Summer Time' ),
- 'Arabia Standard Time' => array(
- 'offset' => 10800000,
- 'shortname' => 'AST',
- 'longname' => 'Arabia Standard Time' ),
- 'Argentine Time' => array(
- 'offset' => -10800000,
- 'shortname' => 'ART',
- 'longname' => 'Argentine Time' ),
- 'Armenia Time' => array(
- 'offset' => 14400000,
- 'shortname' => 'AMT',
- 'dstshortname' => 'AMST',
- 'longname' => 'Armenia Time',
- 'dstlongname' => 'Armenia Summer Time' ),
- 'Atlantic Standard Time' => array(
- 'offset' => -14400000,
- 'shortname' => 'AST',
- 'dstshortname' => 'ADT',
- 'longname' => 'Atlantic Standard Time',
- 'dstlongname' => 'Atlantic Daylight Time' ),
- 'Azerbaijan Time' => array(
- 'offset' => 14400000,
- 'shortname' => 'AZT',
- 'dstshortname' => 'AZST',
- 'longname' => 'Azerbaijan Time',
- 'dstlongname' => 'Azerbaijan Summer Time' ),
- 'Azores Time' => array(
- 'offset' => -3600000,
- 'shortname' => 'AZOT',
- 'dstshortname' => 'AZOST',
- 'longname' => 'Azores Time',
- 'dstlongname' => 'Azores Summer Time' ),
- 'BDT' => array(
- 'offset' => 21600000,
- 'shortname' => 'BDT',
- 'longname' => 'Bangladesh Time' ),
- 'BET' => array(
- 'offset' => -10800000,
- 'shortname' => 'BRT',
- 'dstshortname' => 'BRST',
- 'longname' => 'Brazil Time',
- 'dstlongname' => 'Brazil Summer Time' ),
- 'Bangladesh Time' => array(
- 'offset' => 21600000,
- 'shortname' => 'BDT',
- 'longname' => 'Bangladesh Time' ),
- 'Bhutan Time' => array(
- 'offset' => 21600000,
- 'shortname' => 'BTT',
- 'longname' => 'Bhutan Time' ),
- 'Bolivia Time' => array(
- 'offset' => -14400000,
- 'shortname' => 'BOT',
- 'longname' => 'Bolivia Time' ),
- 'Brazil Time' => array(
- 'offset' => -10800000,
- 'shortname' => 'BRT',
- 'dstshortname' => 'BRST',
- 'longname' => 'Brazil Time',
- 'dstlongname' => 'Brazil Summer Time' ),
- 'Brunei Time' => array(
- 'offset' => 28800000,
- 'shortname' => 'BNT',
- 'longname' => 'Brunei Time' ),
- 'CAT' => array(
- 'offset' => 7200000,
- 'shortname' => 'CAT',
- 'longname' => 'Central African Time' ),
- 'CEST' => array(
- 'offset' => 3600000,
- 'shortname' => 'CET',
- 'dstshortname' => 'CEST',
- 'longname' => 'Central European Time',
- 'dstlongname' => 'Central European Summer Time' ),
- 'CNT' => array(
- 'offset' => -12600000,
- 'shortname' => 'NST',
- 'dstshortname' => 'NDT',
- 'longname' => 'Newfoundland Standard Time',
- 'dstlongname' => 'Newfoundland Daylight Time' ),
- 'CST' => array(
- 'offset' => -21600000,
- 'shortname' => 'CST',
- 'dstshortname' => 'CDT',
- 'longname' => 'Central Standard Time',
- 'dstlongname' => 'Central Daylight Time' ),
- 'CTT' => array(
- 'offset' => 28800000,
- 'shortname' => 'CST',
- 'longname' => 'China Standard Time' ),
- 'Cape Verde Time' => array(
- 'offset' => -3600000,
- 'shortname' => 'CVT',
- 'longname' => 'Cape Verde Time' ),
- 'Central African Time' => array(
- 'offset' => 7200000,
- 'shortname' => 'CAT',
- 'longname' => 'Central African Time' ),
- 'Central European Time' => array(
- 'offset' => 3600000,
- 'shortname' => 'CET',
- 'dstshortname' => 'CEST',
- 'longname' => 'Central European Time',
- 'dstlongname' => 'Central European Summer Time' ),
- 'Central Indonesia Time' => array(
- 'offset' => 28800000,
- 'shortname' => 'CIT',
- 'longname' => 'Central Indonesia Time' ),
- 'Central Standard Time' => array(
- 'offset' => -18000000,
- 'shortname' => 'CST',
- 'dstshortname' => 'CDT',
- 'longname' => 'Central Standard Time',
- 'dstlongname' => 'Central Daylight Time' ),
- 'Central Standard Time (Northern Territory)' => array(
- 'offset' => 34200000,
- 'shortname' => 'CST',
- 'longname' => 'Central Standard Time (Northern Territory)' ),
- 'Central Standard Time (South Australia)' => array(
- 'offset' => 34200000,
- 'shortname' => 'CST',
- 'dstshortname' => 'CST',
- 'longname' => 'Central Standard Time (South Australia)',
- 'dstlongname' => 'Central Summer Time (South Australia)' ),
- 'Central Standard Time (South Australia/New South Wales)' => array(
- 'offset' => 34200000,
- 'shortname' => 'CST',
- 'dstshortname' => 'CST',
- 'longname' => 'Central Standard Time (South Australia/New South Wales)',
- 'dstlongname' => 'Central Summer Time (South Australia/New South Wales)' ),
- 'Chamorro Standard Time' => array(
- 'offset' => 36000000,
- 'shortname' => 'ChST',
- 'longname' => 'Chamorro Standard Time' ),
- 'Chatham Standard Time' => array(
- 'offset' => 45900000,
- 'shortname' => 'CHAST',
- 'dstshortname' => 'CHADT',
- 'longname' => 'Chatham Standard Time',
- 'dstlongname' => 'Chatham Daylight Time' ),
- 'Chile Time' => array(
- 'offset' => -14400000,
- 'shortname' => 'CLT',
- 'dstshortname' => 'CLST',
- 'longname' => 'Chile Time',
- 'dstlongname' => 'Chile Summer Time' ),
- 'China Standard Time' => array(
- 'offset' => 28800000,
- 'shortname' => 'CST',
- 'longname' => 'China Standard Time' ),
- 'Choibalsan Time' => array(
- 'offset' => 32400000,
- 'shortname' => 'CHOT',
- 'longname' => 'Choibalsan Time' ),
- 'Christmas Island Time' => array(
- 'offset' => 25200000,
- 'shortname' => 'CXT',
- 'longname' => 'Christmas Island Time' ),
- 'Cocos Islands Time' => array(
- 'offset' => 23400000,
- 'shortname' => 'CCT',
- 'longname' => 'Cocos Islands Time' ),
- 'Colombia Time' => array(
- 'offset' => -18000000,
- 'shortname' => 'COT',
- 'longname' => 'Colombia Time' ),
- 'Cook Is. Time' => array(
- 'offset' => -36000000,
- 'shortname' => 'CKT',
- 'longname' => 'Cook Is. Time' ),
- 'Coordinated Universal Time' => array(
- 'offset' => 0,
- 'shortname' => 'UTC',
- 'longname' => 'Coordinated Universal Time' ),
- 'Davis Time' => array(
- 'offset' => 25200000,
- 'shortname' => 'DAVT',
- 'longname' => 'Davis Time' ),
- 'Dumont-d\'Urville Time' => array(
- 'offset' => 36000000,
- 'shortname' => 'DDUT',
- 'longname' => 'Dumont-d\'Urville Time' ),
- 'EAT' => array(
- 'offset' => 10800000,
- 'shortname' => 'EAT',
- 'longname' => 'Eastern African Time' ),
- 'ECT' => array(
- 'offset' => 3600000,
- 'shortname' => 'CET',
- 'dstshortname' => 'CEST',
- 'longname' => 'Central European Time',
- 'dstlongname' => 'Central European Summer Time' ),
- 'East Indonesia Time' => array(
- 'offset' => 32400000,
- 'shortname' => 'EIT',
- 'longname' => 'East Indonesia Time' ),
- 'East Timor Time' => array(
- 'offset' => 32400000,
- 'shortname' => 'TPT',
- 'longname' => 'East Timor Time' ),
- 'Easter Is. Time' => array(
- 'offset' => -21600000,
- 'shortname' => 'EAST',
- 'dstshortname' => 'EASST',
- 'longname' => 'Easter Is. Time',
- 'dstlongname' => 'Easter Is. Summer Time' ),
- 'Eastern African Time' => array(
- 'offset' => 10800000,
- 'shortname' => 'EAT',
- 'longname' => 'Eastern African Time' ),
- 'Eastern European Time' => array(
- 'offset' => 7200000,
- 'shortname' => 'EET',
- 'dstshortname' => 'EEST',
- 'longname' => 'Eastern European Time',
- 'dstlongname' => 'Eastern European Summer Time' ),
- 'Eastern Greenland Time' => array(
- 'offset' => 3600000,
- 'shortname' => 'EGT',
- 'dstshortname' => 'EGST',
- 'longname' => 'Eastern Greenland Time',
- 'dstlongname' => 'Eastern Greenland Summer Time' ),
- 'Eastern Standard Time' => array(
- 'offset' => -18000000,
- 'shortname' => 'EST',
- 'dstshortname' => 'EDT',
- 'longname' => 'Eastern Standard Time',
- 'dstlongname' => 'Eastern Daylight Time' ),
- 'Eastern Standard Time (New South Wales)' => array(
- 'offset' => 36000000,
- 'shortname' => 'EST',
- 'dstshortname' => 'EST',
- 'longname' => 'Eastern Standard Time (New South Wales)',
- 'dstlongname' => 'Eastern Summer Time (New South Wales)' ),
- 'Eastern Standard Time (Queensland)' => array(
- 'offset' => 36000000,
- 'shortname' => 'EST',
- 'longname' => 'Eastern Standard Time (Queensland)' ),
- 'Eastern Standard Time (Tasmania)' => array(
- 'offset' => 36000000,
- 'shortname' => 'EST',
- 'dstshortname' => 'EST',
- 'longname' => 'Eastern Standard Time (Tasmania)',
- 'dstlongname' => 'Eastern Summer Time (Tasmania)' ),
- 'Eastern Standard Time (Victoria)' => array(
- 'offset' => 36000000,
- 'shortname' => 'EST',
- 'dstshortname' => 'EST',
- 'longname' => 'Eastern Standard Time (Victoria)',
- 'dstlongname' => 'Eastern Summer Time (Victoria)' ),
- 'Ecuador Time' => array(
- 'offset' => -18000000,
- 'shortname' => 'ECT',
- 'longname' => 'Ecuador Time' ),
- 'Falkland Is. Time' => array(
- 'offset' => -14400000,
- 'shortname' => 'FKT',
- 'dstshortname' => 'FKST',
- 'longname' => 'Falkland Is. Time',
- 'dstlongname' => 'Falkland Is. Summer Time' ),
- 'Fernando de Noronha Time' => array(
- 'offset' => -7200000,
- 'shortname' => 'FNT',
- 'longname' => 'Fernando de Noronha Time' ),
- 'Fiji Time' => array(
- 'offset' => 43200000,
- 'shortname' => 'FJT',
- 'longname' => 'Fiji Time' ),
- 'French Guiana Time' => array(
- 'offset' => -10800000,
- 'shortname' => 'GFT',
- 'longname' => 'French Guiana Time' ),
- 'French Southern & Antarctic Lands Time' => array(
- 'offset' => 18000000,
- 'shortname' => 'TFT',
- 'longname' => 'French Southern & Antarctic Lands Time' ),
- 'GMT+03:07' => array(
- 'offset' => 11224000,
- 'shortname' => 'GMT+03:07',
- 'longname' => 'GMT+03:07' ),
- 'Galapagos Time' => array(
- 'offset' => -21600000,
- 'shortname' => 'GALT',
- 'longname' => 'Galapagos Time' ),
- 'Gambier Time' => array(
- 'offset' => -32400000,
- 'shortname' => 'GAMT',
- 'longname' => 'Gambier Time' ),
- 'Georgia Time' => array(
- 'offset' => 14400000,
- 'shortname' => 'GET',
- 'dstshortname' => 'GEST',
- 'longname' => 'Georgia Time',
- 'dstlongname' => 'Georgia Summer Time' ),
- 'Gilbert Is. Time' => array(
- 'offset' => 43200000,
- 'shortname' => 'GILT',
- 'longname' => 'Gilbert Is. Time' ),
- 'Greenwich Mean Time' => array(
- 'offset' => 0,
- 'shortname' => 'GMT',
- 'longname' => 'Greenwich Mean Time' ),
- 'Gulf Standard Time' => array(
- 'offset' => 14400000,
- 'shortname' => 'GST',
- 'longname' => 'Gulf Standard Time' ),
- 'Guyana Time' => array(
- 'offset' => -14400000,
- 'shortname' => 'GYT',
- 'longname' => 'Guyana Time' ),
- 'Hawaii Standard Time' => array(
- 'offset' => -36000000,
- 'shortname' => 'HST',
- 'longname' => 'Hawaii Standard Time' ),
- 'Hawaii-Aleutian Standard Time' => array(
- 'offset' => -36000000,
- 'shortname' => 'HAST',
- 'dstshortname' => 'HADT',
- 'longname' => 'Hawaii-Aleutian Standard Time',
- 'dstlongname' => 'Hawaii-Aleutian Daylight Time' ),
- 'Hong Kong Time' => array(
- 'offset' => 28800000,
- 'shortname' => 'HKT',
- 'longname' => 'Hong Kong Time' ),
- 'Hovd Time' => array(
- 'offset' => 25200000,
- 'shortname' => 'HOVT',
- 'longname' => 'Hovd Time' ),
- 'IET' => array(
- 'offset' => -18000000,
- 'shortname' => 'EST',
- 'longname' => 'Eastern Standard Time' ),
- 'IST' => array(
- 'offset' => 19800000,
- 'shortname' => 'IST',
- 'longname' => 'India Standard Time' ),
- 'India Standard Time' => array(
- 'offset' => 19800000,
- 'shortname' => 'IST',
- 'longname' => 'India Standard Time' ),
- 'Indian Ocean Territory Time' => array(
- 'offset' => 21600000,
- 'shortname' => 'IOT',
- 'longname' => 'Indian Ocean Territory Time' ),
- 'Indochina Time' => array(
- 'offset' => 25200000,
- 'shortname' => 'ICT',
- 'longname' => 'Indochina Time' ),
- 'Iran Time' => array(
- 'offset' => 12600000,
- 'shortname' => 'IRT',
- 'dstshortname' => 'IRST',
- 'longname' => 'Iran Time',
- 'dstlongname' => 'Iran Summer Time' ),
- 'Irkutsk Time' => array(
- 'offset' => 28800000,
- 'shortname' => 'IRKT',
- 'dstshortname' => 'IRKST',
- 'longname' => 'Irkutsk Time',
- 'dstlongname' => 'Irkutsk Summer Time' ),
- 'Israel Standard Time' => array(
- 'offset' => 7200000,
- 'shortname' => 'IST',
- 'dstshortname' => 'IDT',
- 'longname' => 'Israel Standard Time',
- 'dstlongname' => 'Israel Daylight Time' ),
- 'JST' => array(
- 'offset' => 32400000,
- 'shortname' => 'JST',
- 'longname' => 'Japan Standard Time' ),
- 'Japan Standard Time' => array(
- 'offset' => 32400000,
- 'shortname' => 'JST',
- 'longname' => 'Japan Standard Time' ),
- 'Kirgizstan Time' => array(
- 'offset' => 18000000,
- 'shortname' => 'KGT',
- 'dstshortname' => 'KGST',
- 'longname' => 'Kirgizstan Time',
- 'dstlongname' => 'Kirgizstan Summer Time' ),
- 'Korea Standard Time' => array(
- 'offset' => 32400000,
- 'shortname' => 'KST',
- 'longname' => 'Korea Standard Time' ),
- 'Kosrae Time' => array(
- 'offset' => 39600000,
- 'shortname' => 'KOST',
- 'longname' => 'Kosrae Time' ),
- 'Krasnoyarsk Time' => array(
- 'offset' => 25200000,
- 'shortname' => 'KRAT',
- 'dstshortname' => 'KRAST',
- 'longname' => 'Krasnoyarsk Time',
- 'dstlongname' => 'Krasnoyarsk Summer Time' ),
- 'Line Is. Time' => array(
- 'offset' => 50400000,
- 'shortname' => 'LINT',
- 'longname' => 'Line Is. Time' ),
- 'Load Howe Standard Time' => array(
- 'offset' => 37800000,
- 'shortname' => 'LHST',
- 'dstshortname' => 'LHST',
- 'longname' => 'Load Howe Standard Time',
- 'dstlongname' => 'Load Howe Summer Time' ),
- 'MIT' => array(
- 'offset' => -39600000,
- 'shortname' => 'WST',
- 'longname' => 'West Samoa Time' ),
- 'Magadan Time' => array(
- 'offset' => 39600000,
- 'shortname' => 'MAGT',
- 'dstshortname' => 'MAGST',
- 'longname' => 'Magadan Time',
- 'dstlongname' => 'Magadan Summer Time' ),
- 'Malaysia Time' => array(
- 'offset' => 28800000,
- 'shortname' => 'MYT',
- 'longname' => 'Malaysia Time' ),
- 'Maldives Time' => array(
- 'offset' => 18000000,
- 'shortname' => 'MVT',
- 'longname' => 'Maldives Time' ),
- 'Marquesas Time' => array(
- 'offset' => -34200000,
- 'shortname' => 'MART',
- 'longname' => 'Marquesas Time' ),
- 'Marshall Islands Time' => array(
- 'offset' => 43200000,
- 'shortname' => 'MHT',
- 'longname' => 'Marshall Islands Time' ),
- 'Mauritius Time' => array(
- 'offset' => 14400000,
- 'shortname' => 'MUT',
- 'longname' => 'Mauritius Time' ),
- 'Mawson Time' => array(
- 'offset' => 21600000,
- 'shortname' => 'MAWT',
- 'longname' => 'Mawson Time' ),
- 'Middle Europe Time' => array(
- 'offset' => 3600000,
- 'shortname' => 'MET',
- 'dstshortname' => 'MEST',
- 'longname' => 'Middle Europe Time',
- 'dstlongname' => 'Middle Europe Summer Time' ),
- 'Moscow Standard Time' => array(
- 'offset' => 10800000,
- 'shortname' => 'MSK',
- 'dstshortname' => 'MSD',
- 'longname' => 'Moscow Standard Time',
- 'dstlongname' => 'Moscow Daylight Time' ),
- 'Mountain Standard Time' => array(
- 'offset' => -25200000,
- 'shortname' => 'MST',
- 'dstshortname' => 'MDT',
- 'longname' => 'Mountain Standard Time',
- 'dstlongname' => 'Mountain Daylight Time' ),
- 'Myanmar Time' => array(
- 'offset' => 23400000,
- 'shortname' => 'MMT',
- 'longname' => 'Myanmar Time' ),
- 'NET' => array(
- 'offset' => 14400000,
- 'shortname' => 'AMT',
- 'dstshortname' => 'AMST',
- 'longname' => 'Armenia Time',
- 'dstlongname' => 'Armenia Summer Time' ),
- 'NST' => array(
- 'offset' => 43200000,
- 'shortname' => 'NZST',
- 'dstshortname' => 'NZDT',
- 'longname' => 'New Zealand Standard Time',
- 'dstlongname' => 'New Zealand Daylight Time' ),
- 'Nauru Time' => array(
- 'offset' => 43200000,
- 'shortname' => 'NRT',
- 'longname' => 'Nauru Time' ),
- 'Nepal Time' => array(
- 'offset' => 20700000,
- 'shortname' => 'NPT',
- 'longname' => 'Nepal Time' ),
- 'New Caledonia Time' => array(
- 'offset' => 39600000,
- 'shortname' => 'NCT',
- 'longname' => 'New Caledonia Time' ),
- 'New Zealand Standard Time' => array(
- 'offset' => 43200000,
- 'shortname' => 'NZST',
- 'dstshortname' => 'NZDT',
- 'longname' => 'New Zealand Standard Time',
- 'dstlongname' => 'New Zealand Daylight Time' ),
- 'Newfoundland Standard Time' => array(
- 'offset' => -12600000,
- 'shortname' => 'NST',
- 'dstshortname' => 'NDT',
- 'longname' => 'Newfoundland Standard Time',
- 'dstlongname' => 'Newfoundland Daylight Time' ),
- 'Niue Time' => array(
- 'offset' => -39600000,
- 'shortname' => 'NUT',
- 'longname' => 'Niue Time' ),
- 'Norfolk Time' => array(
- 'offset' => 41400000,
- 'shortname' => 'NFT',
- 'longname' => 'Norfolk Time' ),
- 'Novosibirsk Time' => array(
- 'offset' => 21600000,
- 'shortname' => 'NOVT',
- 'dstshortname' => 'NOVST',
- 'longname' => 'Novosibirsk Time',
- 'dstlongname' => 'Novosibirsk Summer Time' ),
- 'Omsk Time' => array(
- 'offset' => 21600000,
- 'shortname' => 'OMST',
- 'dstshortname' => 'OMSST',
- 'longname' => 'Omsk Time',
- 'dstlongname' => 'Omsk Summer Time' ),
- 'PLT' => array(
- 'offset' => 18000000,
- 'shortname' => 'PKT',
- 'longname' => 'Pakistan Time' ),
- 'PNT' => array(
- 'offset' => -25200000,
- 'shortname' => 'MST',
- 'longname' => 'Mountain Standard Time' ),
- 'PRT' => array(
- 'offset' => -14400000,
- 'shortname' => 'AST',
- 'longname' => 'Atlantic Standard Time' ),
- 'PST' => array(
- 'offset' => -28800000,
- 'shortname' => 'PST',
- 'dstshortname' => 'PDT',
- 'longname' => 'Pacific Standard Time',
- 'dstlongname' => 'Pacific Daylight Time' ),
- 'Pacific Standard Time' => array(
- 'offset' => -28800000,
- 'shortname' => 'PST',
- 'dstshortname' => 'PDT',
- 'longname' => 'Pacific Standard Time',
- 'dstlongname' => 'Pacific Daylight Time' ),
- 'Pakistan Time' => array(
- 'offset' => 18000000,
- 'shortname' => 'PKT',
- 'longname' => 'Pakistan Time' ),
- 'Palau Time' => array(
- 'offset' => 32400000,
- 'shortname' => 'PWT',
- 'longname' => 'Palau Time' ),
- 'Papua New Guinea Time' => array(
- 'offset' => 36000000,
- 'shortname' => 'PGT',
- 'longname' => 'Papua New Guinea Time' ),
- 'Paraguay Time' => array(
- 'offset' => -14400000,
- 'shortname' => 'PYT',
- 'dstshortname' => 'PYST',
- 'longname' => 'Paraguay Time',
- 'dstlongname' => 'Paraguay Summer Time' ),
- 'Peru Time' => array(
- 'offset' => -18000000,
- 'shortname' => 'PET',
- 'longname' => 'Peru Time' ),
- 'Petropavlovsk-Kamchatski Time' => array(
- 'offset' => 43200000,
- 'shortname' => 'PETT',
- 'dstshortname' => 'PETST',
- 'longname' => 'Petropavlovsk-Kamchatski Time',
- 'dstlongname' => 'Petropavlovsk-Kamchatski Summer Time' ),
- 'Philippines Time' => array(
- 'offset' => 28800000,
- 'shortname' => 'PHT',
- 'longname' => 'Philippines Time' ),
- 'Phoenix Is. Time' => array(
- 'offset' => 46800000,
- 'shortname' => 'PHOT',
- 'longname' => 'Phoenix Is. Time' ),
- 'Pierre & Miquelon Standard Time' => array(
- 'offset' => -10800000,
- 'shortname' => 'PMST',
- 'dstshortname' => 'PMDT',
- 'longname' => 'Pierre & Miquelon Standard Time',
- 'dstlongname' => 'Pierre & Miquelon Daylight Time' ),
- 'Pitcairn Standard Time' => array(
- 'offset' => -28800000,
- 'shortname' => 'PST',
- 'longname' => 'Pitcairn Standard Time' ),
- 'Ponape Time' => array(
- 'offset' => 39600000,
- 'shortname' => 'PONT',
- 'longname' => 'Ponape Time' ),
- 'Reunion Time' => array(
- 'offset' => 14400000,
- 'shortname' => 'RET',
- 'longname' => 'Reunion Time' ),
- 'SST' => array(
- 'offset' => 39600000,
- 'shortname' => 'SBT',
- 'longname' => 'Solomon Is. Time' ),
- 'Sakhalin Time' => array(
- 'offset' => 36000000,
- 'shortname' => 'SAKT',
- 'dstshortname' => 'SAKST',
- 'longname' => 'Sakhalin Time',
- 'dstlongname' => 'Sakhalin Summer Time' ),
- 'Samara Time' => array(
- 'offset' => 14400000,
- 'shortname' => 'SAMT',
- 'dstshortname' => 'SAMST',
- 'longname' => 'Samara Time',
- 'dstlongname' => 'Samara Summer Time' ),
- 'Samoa Standard Time' => array(
- 'offset' => -39600000,
- 'shortname' => 'SST',
- 'longname' => 'Samoa Standard Time' ),
- 'Seychelles Time' => array(
- 'offset' => 14400000,
- 'shortname' => 'SCT',
- 'longname' => 'Seychelles Time' ),
- 'Singapore Time' => array(
- 'offset' => 28800000,
- 'shortname' => 'SGT',
- 'longname' => 'Singapore Time' ),
- 'Solomon Is. Time' => array(
- 'offset' => 39600000,
- 'shortname' => 'SBT',
- 'longname' => 'Solomon Is. Time' ),
- 'South Africa Standard Time' => array(
- 'offset' => 7200000,
- 'shortname' => 'SAST',
- 'longname' => 'South Africa Standard Time' ),
- 'South Georgia Standard Time' => array(
- 'offset' => -7200000,
- 'shortname' => 'GST',
- 'longname' => 'South Georgia Standard Time' ),
- 'Sri Lanka Time' => array(
- 'offset' => 21600000,
- 'shortname' => 'LKT',
- 'longname' => 'Sri Lanka Time' ),
- 'Suriname Time' => array(
- 'offset' => -10800000,
- 'shortname' => 'SRT',
- 'longname' => 'Suriname Time' ),
- 'Syowa Time' => array(
- 'offset' => 10800000,
- 'shortname' => 'SYOT',
- 'longname' => 'Syowa Time' ),
- 'SystemV/AST4' => array(
- 'offset' => -14400000,
- 'shortname' => 'AST',
- 'dstshortname' => '',
- 'longname' => 'Atlantic Standard Time' ),
- 'SystemV/AST4ADT' => array(
- 'offset' => -14400000,
- 'shortname' => 'AST',
- 'dstshortname' => 'ADT',
- 'longname' => 'Atlantic Standard Time',
- 'dstlongname' => 'Atlantic Daylight Time',
- 'summertimeoffset' => 3600000000,
- 'summertimestartmonth' => 4,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 21600000000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 18000000000 ),
- 'SystemV/CST6' => array(
- 'offset' => -21600000,
- 'shortname' => 'CST',
- 'dstshortname' => '',
- 'longname' => 'Central Standard Time' ),
- 'SystemV/CST6CDT' => array(
- 'offset' => -21600000,
- 'shortname' => 'CST',
- 'dstshortname' => 'CDT',
- 'longname' => 'Central Standard Time',
- 'dstlongname' => 'Central Daylight Time',
- 'summertimeoffset' => 3600000000,
- 'summertimestartmonth' => 4,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 28800000000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 25200000000 ),
- 'SystemV/EST5' => array(
- 'offset' => -18000000,
- 'shortname' => 'EST',
- 'dstshortname' => '',
- 'longname' => 'Eastern Standard Time' ),
- 'SystemV/EST5EDT' => array(
- 'offset' => -18000000,
- 'shortname' => 'EST',
- 'dstshortname' => 'EDT',
- 'longname' => 'Eastern Standard Time',
- 'dstlongname' => 'Eastern Daylight Time',
- 'summertimeoffset' => 3600000000,
- 'summertimestartmonth' => 4,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 25200000000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 21600000000 ),
- 'SystemV/HST10' => array(
- 'offset' => -36000000,
- 'shortname' => 'HST',
- 'dstshortname' => '',
- 'longname' => 'Hawaii Standard Time' ),
- 'SystemV/MST7' => array(
- 'offset' => -25200000,
- 'shortname' => 'MST',
- 'dstshortname' => '',
- 'longname' => 'Mountain Standard Time' ),
- 'SystemV/MST7MDT' => array(
- 'offset' => -25200000,
- 'shortname' => 'MST',
- 'dstshortname' => 'MDT',
- 'longname' => 'Mountain Standard Time',
- 'dstlongname' => 'Mountain Daylight Time',
- 'summertimeoffset' => 3600000000,
- 'summertimestartmonth' => 4,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 32400000000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 28800000000 ),
- 'SystemV/PST8' => array(
- 'offset' => -28800000,
- 'shortname' => 'PST',
- 'dstshortname' => '',
- 'longname' => 'Pitcairn Standard Time' ),
- 'SystemV/PST8PDT' => array(
- 'offset' => -28800000,
- 'shortname' => 'PST',
- 'dstshortname' => 'PDT',
- 'longname' => 'Pacific Standard Time',
- 'dstlongname' => 'Pacific Daylight Time',
- 'summertimeoffset' => 3600000000,
- 'summertimestartmonth' => 4,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 36000000000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 32400000000 ),
- 'SystemV/YST9' => array(
- 'offset' => -32400000,
- 'shortname' => 'YST',
- 'dstshortname' => '',
- 'longname' => 'Gambier Time' ),
- 'SystemV/YST9YDT' => array(
- 'offset' => -32400000,
- 'shortname' => 'YST',
- 'dstshortname' => 'YDT',
- 'longname' => 'Alaska Standard Time',
- 'dstlongname' => 'Alaska Daylight Time',
- 'summertimeoffset' => 3600000000,
- 'summertimestartmonth' => 4,
- 'summertimestartday' => 'lastSun',
- 'summertimestarttime' => 39600000000,
- 'summertimeendmonth' => 10,
- 'summertimeendday' => 'lastSun',
- 'summertimeendtime' => 36000000000 ),
- 'Tahiti Time' => array(
- 'offset' => -36000000,
- 'shortname' => 'TAHT',
- 'longname' => 'Tahiti Time' ),
- 'Tajikistan Time' => array(
- 'offset' => 18000000,
- 'shortname' => 'TJT',
- 'longname' => 'Tajikistan Time' ),
- 'Tokelau Time' => array(
- 'offset' => -36000000,
- 'shortname' => 'TKT',
- 'longname' => 'Tokelau Time' ),
- 'Tonga Time' => array(
- 'offset' => 46800000,
- 'shortname' => 'TOT',
- 'longname' => 'Tonga Time' ),
- 'Truk Time' => array(
- 'offset' => 36000000,
- 'shortname' => 'TRUT',
- 'longname' => 'Truk Time' ),
- 'Turkmenistan Time' => array(
- 'offset' => 18000000,
- 'shortname' => 'TMT',
- 'longname' => 'Turkmenistan Time' ),
- 'Tuvalu Time' => array(
- 'offset' => 43200000,
- 'shortname' => 'TVT',
- 'longname' => 'Tuvalu Time' ),
- 'Ulaanbaatar Time' => array(
- 'offset' => 28800000,
- 'shortname' => 'ULAT',
- 'longname' => 'Ulaanbaatar Time' ),
- 'Uruguay Time' => array(
- 'offset' => -10800000,
- 'shortname' => 'UYT',
- 'longname' => 'Uruguay Time' ),
- 'Uzbekistan Time' => array(
- 'offset' => 18000000,
- 'shortname' => 'UZT',
- 'longname' => 'Uzbekistan Time' ),
- 'VST' => array(
- 'offset' => 25200000,
- 'shortname' => 'ICT',
- 'longname' => 'Indochina Time' ),
- 'Vanuatu Time' => array(
- 'offset' => 39600000,
- 'shortname' => 'VUT',
- 'longname' => 'Vanuatu Time' ),
- 'Venezuela Time' => array(
- 'offset' => -14400000,
- 'shortname' => 'VET',
- 'longname' => 'Venezuela Time' ),
- 'Vladivostok Time' => array(
- 'offset' => 36000000,
- 'shortname' => 'VLAT',
- 'dstshortname' => 'VLAST',
- 'longname' => 'Vladivostok Time',
- 'dstlongname' => 'Vladivostok Summer Time' ),
- 'Vostok time' => array(
- 'offset' => 21600000,
- 'shortname' => 'VOST',
- 'longname' => 'Vostok time' ),
- 'Wake Time' => array(
- 'offset' => 43200000,
- 'shortname' => 'WAKT',
- 'longname' => 'Wake Time' ),
- 'Wallis & Futuna Time' => array(
- 'offset' => 43200000,
- 'shortname' => 'WFT',
- 'longname' => 'Wallis & Futuna Time' ),
- 'West Indonesia Time' => array(
- 'offset' => 25200000,
- 'shortname' => 'WIT',
- 'longname' => 'West Indonesia Time' ),
- 'West Samoa Time' => array(
- 'offset' => -39600000,
- 'shortname' => 'WST',
- 'longname' => 'West Samoa Time' ),
- 'Western African Time' => array(
- 'offset' => 3600000,
- 'shortname' => 'WAT',
- 'dstshortname' => 'WAST',
- 'longname' => 'Western African Time',
- 'dstlongname' => 'Western African Summer Time' ),
- 'Western European Time' => array(
- 'offset' => 0,
- 'shortname' => 'WET',
- 'dstshortname' => 'WEST',
- 'longname' => 'Western European Time',
- 'dstlongname' => 'Western European Summer Time' ),
- 'Western Greenland Time' => array(
- 'offset' => -10800000,
- 'shortname' => 'WGT',
- 'dstshortname' => 'WGST',
- 'longname' => 'Western Greenland Time',
- 'dstlongname' => 'Western Greenland Summer Time' ),
- 'Western Standard Time (Australia)' => array(
- 'offset' => 28800000,
- 'shortname' => 'WST',
- 'longname' => 'Western Standard Time (Australia)' ),
- 'Yakutsk Time' => array(
- 'offset' => 32400000,
- 'shortname' => 'YAKT',
- 'dstshortname' => 'YAKST',
- 'longname' => 'Yakutsk Time',
- 'dstlongname' => 'Yaktsk Summer Time' ),
- 'Yap Time' => array(
- 'offset' => 36000000,
- 'shortname' => 'YAPT',
- 'longname' => 'Yap Time' ),
- 'Yekaterinburg Time' => array(
- 'offset' => 18000000,
- 'shortname' => 'YEKT',
- 'dstshortname' => 'YEKST',
- 'longname' => 'Yekaterinburg Time',
- 'dstlongname' => 'Yekaterinburg Summer Time' ),
-);
-
-/**
- * Initialize default timezone
- *
- * First try php.ini directive, then the value returned by date("e"), then
- * _DATE_TIMEZONE_DEFAULT global, then PHP_TZ environment variable, then TZ
- * environment variable.
- */
-if (isset($GLOBALS['_DATE_TIMEZONE_DEFAULT'])
- && Date_TimeZone::isValidID($GLOBALS['_DATE_TIMEZONE_DEFAULT'])) {
- Date_TimeZone::setDefault($GLOBALS['_DATE_TIMEZONE_DEFAULT']);
-} else if (function_exists('version_compare') &&
- version_compare(phpversion(), "5.1.0", ">=") &&
- (Date_TimeZone::isValidID($ps_id = ini_get("date.timezone")) ||
- Date_TimeZone::isValidID($ps_id = date("e"))
- )
- ) {
- Date_TimeZone::setDefault($ps_id);
-} else if (getenv('PHP_TZ') && Date_TimeZone::isValidID(getenv('PHP_TZ'))) {
- Date_TimeZone::setDefault(getenv('PHP_TZ'));
-} else if (getenv('TZ') && Date_TimeZone::isValidID(getenv('TZ'))) {
- Date_TimeZone::setDefault(getenv('TZ'));
-} else if (Date_TimeZone::isValidID(date('T'))) {
- Date_TimeZone::setDefault(date('T'));
-} else {
- Date_TimeZone::setDefault('UTC');
-}
-
-/*
- * Local variables:
- * mode: php
- * tab-width: 4
- * c-basic-offset: 4
- * c-hanging-comment-ender-p: nil
- * End:
- */
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */
-
-/**
- * Standard Html Login form
- *
- * PHP versions 4 and 5
- *
- * LICENSE: This source file is subject to version 3.01 of the PHP license
- * that is available through the world-wide-web at the following URI:
- * http://www.php.net/license/3_01.txt. If you did not receive a copy of
- * the PHP License and are unable to obtain it through the web, please
- * send a note to license@php.net so we can mail you a copy immediately.
- *
- * @category Authentication
- * @package Auth
- * @author Martin Jansen <mj@php.net>
- * @author Adam Ashley <aashley@php.net>
- * @copyright 2001-2006 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version CVS: $Id: Html.php,v 1.1.1.1 2008/04/28 15:20:46 jamie Exp $
- * @link http://pear.php.net/package/Auth
- * @since File available since Release 1.3.0
- */
-
-/**
- * Standard Html Login form
- *
- * @category Authentication
- * @package Auth
- * @author Yavor Shahpasov <yavo@netsmart.com.cy>
- * @author Adam Ashley <aashley@php.net>
- * @copyright 2001-2006 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version Release: 1.5.4 File: $Revision: 1.1.1.1 $
- * @link http://pear.php.net/package/Auth
- * @since Class available since Release 1.3.0
- */
-class Auth_Frontend_Html {
-
- // {{{ render()
-
- /**
- * Displays the login form
- *
- * @param object The calling auth instance
- * @param string The previously used username
- * @return void
- */
- function render(&$caller, $username = '') {
- $loginOnClick = 'return true;';
-
- // Try To Use Challene response
- // TODO javascript might need some improvement for work on other browsers
- if($caller->advancedsecurity && $caller->storage->supportsChallengeResponse() ) {
-
- // Init the secret cookie
- $caller->session['loginchallenege'] = md5(microtime());
-
- print "\n";
- print '<script language="JavaScript">'."\n";
-
- include 'Auth/Frontend/md5.js';
-
- print "\n";
- print ' function securePassword() { '."\n";
- print ' var pass = document.getElementById(\''.$caller->getPostPasswordField().'\');'."\n";
- print ' var secret = document.getElementById(\'authsecret\')'."\n";
- //print ' alert(pass);alert(secret); '."\n";
-
- // If using md5 for password storage md5 the password before
- // we hash it with the secret
- // print ' alert(pass.value);';
- if ($caller->storage->getCryptType() == 'md5' ) {
- print ' pass.value = hex_md5(pass.value); '."\n";
- #print ' alert(pass.value);';
- }
-
- print ' pass.value = hex_md5(pass.value+\''.$caller->session['loginchallenege'].'\'); '."\n";
- // print ' alert(pass.value);';
- print ' secret.value = 1;'."\n";
- print ' var doLogin = document.getElementById(\'doLogin\')'."\n";
- print ' doLogin.disabled = true;'."\n";
- print ' return true;';
- print ' } '."\n";
- print '</script>'."\n";;
- print "\n";
-
- $loginOnClick = ' return securePassword(); ';
- }
-
- print '<center>'."\n";
-
- $status = '';
- if (!empty($caller->status) && $caller->status == AUTH_EXPIRED) {
- $status = '<i>Your session has expired. Please login again!</i>'."\n";
- } else if (!empty($caller->status) && $caller->status == AUTH_IDLED) {
- $status = '<i>You have been idle for too long. Please login again!</i>'."\n";
- } else if (!empty ($caller->status) && $caller->status == AUTH_WRONG_LOGIN) {
- $status = '<i>Wrong login data!</i>'."\n";
- } else if (!empty ($caller->status) && $caller->status == AUTH_SECURITY_BREACH) {
- $status = '<i>Security problem detected. </i>'."\n";
- }
-
- print '<form method="post" action="'.$caller->server['PHP_SELF'].'" '
- .'onSubmit="'.$loginOnClick.'">'."\n";
- print '<table border="0" cellpadding="2" cellspacing="0" '
- .'summary="login form" align="center" >'."\n";
- print '<tr>'."\n";
- print ' <td colspan="2" bgcolor="#eeeeee"><strong>Login </strong>'
- .$status.'</td>'."\n";
- print '</tr>'."\n";
- print '<tr>'."\n";
- print ' <td>Username:</td>'."\n";
- print ' <td><input type="text" id="'.$caller->getPostUsernameField()
- .'" name="'.$caller->getPostUsernameField().'" value="' . $username
- .'" /></td>'."\n";
- print '</tr>'."\n";
- print '<tr>'."\n";
- print ' <td>Password:</td>'."\n";
- print ' <td><input type="password" id="'.$caller->getPostPasswordField()
- .'" name="'.$caller->getPostPasswordField().'" /></td>'."\n";
- print '</tr>'."\n";
- print '<tr>'."\n";
-
- //onClick=" '.$loginOnClick.' "
- print ' <td colspan="2" bgcolor="#eeeeee"><input value="Login" '
- .'id="doLogin" name="doLogin" type="submit" /></td>'."\n";
- print '</tr>'."\n";
- print '</table>'."\n";
-
- // Might be a good idea to make the variable name variable
- print '<input type="hidden" id="authsecret" name="authsecret" value="" />';
- print '</form>'."\n";
- print '</center>'."\n";
- }
-
- // }}}
-
-}
-
-?>
+++ /dev/null
-/*
- * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
- * Digest Algorithm, as defined in RFC 1321.
- * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
- * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
- * Distributed under the BSD License
- * See http://pajhome.org.uk/crypt/md5 for more info.
- */
-
-/*
- * Configurable variables. You may need to tweak these to be compatible with
- * the server-side, but the defaults work in most cases.
- */
-var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */
-var b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance */
-var chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode */
-
-/*
- * These are the functions you'll usually want to call
- * They take string arguments and return either hex or base-64 encoded strings
- */
-function hex_md5(s){ return binl2hex(core_md5(str2binl(s), s.length * chrsz));}
-function b64_md5(s){ return binl2b64(core_md5(str2binl(s), s.length * chrsz));}
-function str_md5(s){ return binl2str(core_md5(str2binl(s), s.length * chrsz));}
-function hex_hmac_md5(key, data) { return binl2hex(core_hmac_md5(key, data)); }
-function b64_hmac_md5(key, data) { return binl2b64(core_hmac_md5(key, data)); }
-function str_hmac_md5(key, data) { return binl2str(core_hmac_md5(key, data)); }
-
-/*
- * Perform a simple self-test to see if the VM is working
- */
-function md5_vm_test()
-{
- return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72";
-}
-
-/*
- * Calculate the MD5 of an array of little-endian words, and a bit length
- */
-function core_md5(x, len)
-{
- /* append padding */
- x[len >> 5] |= 0x80 << ((len) % 32);
- x[(((len + 64) >>> 9) << 4) + 14] = len;
-
- var a = 1732584193;
- var b = -271733879;
- var c = -1732584194;
- var d = 271733878;
-
- for(var i = 0; i < x.length; i += 16)
- {
- var olda = a;
- var oldb = b;
- var oldc = c;
- var oldd = d;
-
- a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
- d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
- c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819);
- b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
- a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
- d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426);
- c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
- b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
- a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416);
- d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
- c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
- b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
- a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682);
- d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
- c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
- b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329);
-
- a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
- d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
- c = md5_gg(c, d, a, b, x[i+11], 14, 643717713);
- b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
- a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
- d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083);
- c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
- b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
- a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438);
- d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
- c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
- b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501);
- a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
- d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
- c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473);
- b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);
-
- a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
- d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
- c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562);
- b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
- a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
- d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353);
- c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
- b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
- a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174);
- d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
- c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
- b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189);
- a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
- d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
- c = md5_hh(c, d, a, b, x[i+15], 16, 530742520);
- b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);
-
- a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
- d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415);
- c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
- b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
- a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571);
- d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
- c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
- b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
- a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359);
- d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
- c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
- b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649);
- a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
- d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
- c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259);
- b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);
-
- a = safe_add(a, olda);
- b = safe_add(b, oldb);
- c = safe_add(c, oldc);
- d = safe_add(d, oldd);
- }
- return Array(a, b, c, d);
-
-}
-
-/*
- * These functions implement the four basic operations the algorithm uses.
- */
-function md5_cmn(q, a, b, x, s, t)
-{
- return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
-}
-function md5_ff(a, b, c, d, x, s, t)
-{
- return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
-}
-function md5_gg(a, b, c, d, x, s, t)
-{
- return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
-}
-function md5_hh(a, b, c, d, x, s, t)
-{
- return md5_cmn(b ^ c ^ d, a, b, x, s, t);
-}
-function md5_ii(a, b, c, d, x, s, t)
-{
- return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
-}
-
-/*
- * Calculate the HMAC-MD5, of a key and some data
- */
-function core_hmac_md5(key, data)
-{
- var bkey = str2binl(key);
- if(bkey.length > 16) bkey = core_md5(bkey, key.length * chrsz);
-
- var ipad = Array(16), opad = Array(16);
- for(var i = 0; i < 16; i++)
- {
- ipad[i] = bkey[i] ^ 0x36363636;
- opad[i] = bkey[i] ^ 0x5C5C5C5C;
- }
-
- var hash = core_md5(ipad.concat(str2binl(data)), 512 + data.length * chrsz);
- return core_md5(opad.concat(hash), 512 + 128);
-}
-
-/*
- * Add integers, wrapping at 2^32. This uses 16-bit operations internally
- * to work around bugs in some JS interpreters.
- */
-function safe_add(x, y)
-{
- var lsw = (x & 0xFFFF) + (y & 0xFFFF);
- var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
- return (msw << 16) | (lsw & 0xFFFF);
-}
-
-/*
- * Bitwise rotate a 32-bit number to the left.
- */
-function bit_rol(num, cnt)
-{
- return (num << cnt) | (num >>> (32 - cnt));
-}
-
-/*
- * Convert a string to an array of little-endian words
- * If chrsz is ASCII, characters >255 have their hi-byte silently ignored.
- */
-function str2binl(str)
-{
- var bin = Array();
- var mask = (1 << chrsz) - 1;
- for(var i = 0; i < str.length * chrsz; i += chrsz)
- bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32);
- return bin;
-}
-
-/*
- * Convert an array of little-endian words to a string
- */
-function binl2str(bin)
-{
- var str = "";
- var mask = (1 << chrsz) - 1;
- for(var i = 0; i < bin.length * 32; i += chrsz)
- str += String.fromCharCode((bin[i>>5] >>> (i % 32)) & mask);
- return str;
-}
-
-/*
- * Convert an array of little-endian words to a hex string.
- */
-function binl2hex(binarray)
-{
- var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
- var str = "";
- for(var i = 0; i < binarray.length * 4; i++)
- {
- str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +
- hex_tab.charAt((binarray[i>>2] >> ((i%4)*8 )) & 0xF);
- }
- return str;
-}
-
-/*
- * Convert an array of little-endian words to a base-64 string
- */
-function binl2b64(binarray)
-{
- var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
- var str = "";
- for(var i = 0; i < binarray.length * 4; i += 3)
- {
- var triplet = (((binarray[i >> 2] >> 8 * ( i %4)) & 0xFF) << 16)
- | (((binarray[i+1 >> 2] >> 8 * ((i+1)%4)) & 0xFF) << 8 )
- | ((binarray[i+2 >> 2] >> 8 * ((i+2)%4)) & 0xFF);
- for(var j = 0; j < 4; j++)
- {
- if(i * 8 + j * 6 > binarray.length * 32) str += b64pad;
- else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
- }
- }
- return str;
-}
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997, 1998, 1999, 2000, 2001 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Adam Daniel <adaniel1@eesus.jnj.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Common.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-/**
- * Base class for all HTML classes
- *
- * @author Adam Daniel <adaniel1@eesus.jnj.com>
- * @version 1.7
- * @since PHP 4.0.3pl1
- * @abstract
- */
-class HTML_Common {
-
- /**
- * Associative array of table attributes
- * @var array
- * @access private
- */
- var $_attributes = array();
-
- /**
- * Tab offset of the table
- * @var int
- * @access private
- */
- var $_tabOffset = 0;
-
- /**
- * Tab string
- * @var string
- * @since 1.7
- * @access private
- */
- var $_tab = "\11";
-
- /**
- * Contains the line end string
- * @var string
- * @since 1.7
- * @access private
- */
- var $_lineEnd = "\12";
-
- /**
- * HTML comment on the object
- * @var string
- * @since 1.5
- * @access private
- */
- var $_comment = '';
-
- /**
- * Class constructor
- * @param mixed $attributes Associative array of table tag attributes
- * or HTML attributes name="value" pairs
- * @param int $tabOffset Indent offset in tabs
- * @access public
- */
- function HTML_Common($attributes = null, $tabOffset = 0)
- {
- $this->setAttributes($attributes);
- $this->setTabOffset($tabOffset);
- } // end constructor
-
- /**
- * Returns the current API version
- * @access public
- * @returns double
- */
- function apiVersion()
- {
- return 1.7;
- } // end func apiVersion
-
- /**
- * Returns the lineEnd
- *
- * @since 1.7
- * @access private
- * @return string
- * @throws
- */
- function _getLineEnd()
- {
- return $this->_lineEnd;
- } // end func getLineEnd
-
- /**
- * Returns a string containing the unit for indenting HTML
- *
- * @since 1.7
- * @access private
- * @return string
- */
- function _getTab()
- {
- return $this->_tab;
- } // end func _getTab
-
- /**
- * Returns a string containing the offset for the whole HTML code
- *
- * @return string
- * @access private
- */
- function _getTabs()
- {
- return str_repeat($this->_getTab(), $this->_tabOffset);
- } // end func _getTabs
-
- /**
- * Returns an HTML formatted attribute string
- * @param array $attributes
- * @return string
- * @access private
- */
- function _getAttrString($attributes)
- {
- $strAttr = '';
-
- if (is_array($attributes)) {
- foreach ($attributes as $key => $value) {
- $strAttr .= ' ' . $key . '="' . htmlspecialchars($value) . '"';
- }
- }
- return $strAttr;
- } // end func _getAttrString
-
- /**
- * Returns a valid atrributes array from either a string or array
- * @param mixed $attributes Either a typical HTML attribute string or an associative array
- * @access private
- */
- function _parseAttributes($attributes)
- {
- if (is_array($attributes)) {
- $ret = array();
- foreach ($attributes as $key => $value) {
- if (is_int($key)) {
- $key = $value = strtolower($value);
- } else {
- $key = strtolower($key);
- }
- $ret[$key] = $value;
- }
- return $ret;
-
- } elseif (is_string($attributes)) {
- $preg = "/(([A-Za-z_:]|[^\\x00-\\x7F])([A-Za-z0-9_:.-]|[^\\x00-\\x7F])*)" .
- "([ \\n\\t\\r]+)?(=([ \\n\\t\\r]+)?(\"[^\"]*\"|'[^']*'|[^ \\n\\t\\r]*))?/";
- if (preg_match_all($preg, $attributes, $regs)) {
- for ($counter=0; $counter<count($regs[1]); $counter++) {
- $name = $regs[1][$counter];
- $check = $regs[0][$counter];
- $value = $regs[7][$counter];
- if (trim($name) == trim($check)) {
- $arrAttr[strtolower(trim($name))] = strtolower(trim($name));
- } else {
- if (substr($value, 0, 1) == "\"" || substr($value, 0, 1) == "'") {
- $value = substr($value, 1, -1);
- }
- $arrAttr[strtolower(trim($name))] = trim($value);
- }
- }
- return $arrAttr;
- }
- }
- } // end func _parseAttributes
-
- /**
- * Returns the array key for the given non-name-value pair attribute
- *
- * @param string $attr Attribute
- * @param array $attributes Array of attribute
- * @since 1.0
- * @access private
- * @return array key
- * @throws
- */
- function _getAttrKey($attr, $attributes)
- {
- if (isset($attributes[strtolower($attr)])) {
- return true;
- } else {
- return null;
- }
- } //end func _getAttrKey
-
- /**
- * Updates the attributes in $attr1 with the values in $attr2 without changing the other existing attributes
- * @param array $attr1 Original attributes array
- * @param array $attr2 New attributes array
- * @access private
- * @return array
- */
- function _updateAttrArray(&$attr1, $attr2)
- {
- if (!is_array($attr2)) {
- return false;
- }
- foreach ($attr2 as $key => $value) {
- $attr1[$key] = $value;
- }
- } // end func _updateAtrrArray
-
- /**
- * Removes the given attribute from the given array
- *
- * @param string $attr Attribute name
- * @param array $attributes Attribute array
- * @since 1.4
- * @access public
- * @return void
- * @throws
- */
- function _removeAttr($attr, &$attributes)
- {
- $attr = strtolower($attr);
- if (isset($attributes[$attr])) {
- unset($attributes[$attr]);
- }
- } //end func _removeAttr
-
- /**
- * Returns the value of the given attribute
- *
- * @param string $attr Attribute name
- * @since 1.5
- * @access public
- * @return void
- * @throws
- */
- function getAttribute($attr)
- {
- $attr = strtolower($attr);
- if (isset($this->_attributes[$attr])) {
- return $this->_attributes[$attr];
- }
- return null;
- } //end func getAttribute
-
- /**
- * Sets the HTML attributes
- * @param mixed $attributes Either a typical HTML attribute string or an associative array
- * @access public
- */
- function setAttributes($attributes)
- {
- $this->_attributes = $this->_parseAttributes($attributes);
- } // end func setAttributes
-
- /**
- * Returns the assoc array (default) or string of attributes
- *
- * @param bool Whether to return the attributes as string
- * @since 1.6
- * @access public
- * @return mixed attributes
- */
- function getAttributes($asString = false)
- {
- if ($asString) {
- return $this->_getAttrString($this->_attributes);
- } else {
- return $this->_attributes;
- }
- } //end func getAttributes
-
- /**
- * Updates the passed attributes without changing the other existing attributes
- * @param mixed $attributes Either a typical HTML attribute string or an associative array
- * @access public
- */
- function updateAttributes($attributes)
- {
- $this->_updateAttrArray($this->_attributes, $this->_parseAttributes($attributes));
- } // end func updateAttributes
-
- /**
- * Removes an attribute
- *
- * @param string $attr Attribute name
- * @since 1.4
- * @access public
- * @return void
- * @throws
- */
- function removeAttribute($attr)
- {
- $this->_removeAttr($attr, $this->_attributes);
- } //end func removeAttribute
-
- /**
- * Sets the line end style to Windows, Mac, Unix or a custom string.
- *
- * @param string $style "win", "mac", "unix" or custom string.
- * @since 1.7
- * @access public
- * @return void
- */
- function setLineEnd($style)
- {
- switch ($style) {
- case 'win':
- $this->_lineEnd = "\15\12";
- break;
- case 'unix':
- $this->_lineEnd = "\12";
- break;
- case 'mac';
- $this->_lineEnd = "\15";
- break;
- default:
- $this->_lineEnd = $style;
- }
- } // end func setLineEnd
-
- /**
- * Sets the tab offset
- *
- * @param int $offset
- * @access public
- */
- function setTabOffset($offset)
- {
- $this->_tabOffset = $offset;
- } // end func setTabOffset
-
- /**
- * Returns the tabOffset
- *
- * @since 1.5
- * @access public
- * @return int
- */
- function getTabOffset()
- {
- return $this->_tabOffset;
- } //end func getTabOffset
-
- /**
- * Sets the string used to indent HTML
- *
- * @since 1.7
- * @param string $string String used to indent ("\11", "\t", ' ', etc.).
- * @access public
- * @return void
- */
- function setTab($string)
- {
- $this->_tab = $string;
- } // end func setTab
-
- /**
- * Sets the HTML comment to be displayed at the beginning of the HTML string
- *
- * @param string
- * @since 1.4
- * @access public
- * @return void
- */
- function setComment($comment)
- {
- $this->_comment = $comment;
- } // end func setHtmlComment
-
- /**
- * Returns the HTML comment
- *
- * @since 1.5
- * @access public
- * @return string
- */
- function getComment()
- {
- return $this->_comment;
- } //end func getComment
-
- /**
- * Abstract method. Must be extended to return the objects HTML
- *
- * @access public
- * @return string
- * @abstract
- */
- function toHtml()
- {
- return '';
- } // end func toHtml
-
- /**
- * Displays the HTML to the screen
- *
- * @access public
- */
- function display()
- {
- print $this->toHtml();
- } // end func display
-
-} // end class HTML_Common
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/**
- * HTML_Common2: port of HTML_Common package to PHP5
- *
- * PHP version 5
- *
- * LICENSE:
- *
- * Copyright (c) 2004-2007, Alexey Borzov <avb@php.net>
- *
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * The names of the authors may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * @category HTML
- * @package HTML_Common2
- * @author Alexey Borzov <avb@php.net>
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: Common2.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_Common2
- */
-
-/**
- * Base class for HTML classes
- *
- * Implements methods for working with HTML attributes, parsing and generating
- * attribute strings. Port of HTML_Common class for PHP4 originally written by
- * Adam Daniel with contributions from numerous other developers.
- *
- * @category HTML
- * @package HTML_Common2
- * @author Alexey Borzov <avb@php.net>
- * @version Release: 2.0.0beta1
- */
-abstract class HTML_Common2
-{
- /**
- * Associative array of attributes
- * @var array
- */
- protected $attributes = array();
-
- /**
- * List of attribites changes to which will be announced via onAttributeChange()
- * method rather than performed by HTML_Common2 class itself
- * @var array
- * @see onAttributeChange()
- */
- protected $watchedAttributes = array();
-
- /**
- * Indentation level of the element
- * @var int
- */
- private $_indentLevel = 0;
-
- /**
- * Comment associated with the element
- * @var string
- */
- private $_comment = null;
-
- /**
- * Global options for all elements generated by subclasses of HTML_Common2
- *
- * Preset options are
- * - 'charset': charset parameter used in htmlspecialchars() calls,
- * defaults to 'ISO-8859-1'
- * - 'indent': string used to indent HTML elements, defaults to "\11"
- * - 'linebreak': string used to indicate linebreak, defaults to "\12"
- *
- * @var array
- */
- private static $_options = array(
- 'charset' => 'ISO-8859-1',
- 'indent' => "\11",
- 'linebreak' => "\12"
- );
-
- /**
- * Sets a global option
- *
- * @param string Option name
- * @param mixed Option value
- */
- public static function setOption($name, $value)
- {
- $linebreaks = array('win' => "\15\12", 'unix' => "\12", 'mac' => "\15");
- if ('linebreak' == $name && isset($linebreaks[$value])) {
- $value = $linebreaks[$value];
- }
- self::$_options[$name] = $value;
- }
-
- /**
- * Gets a global option
- *
- * @param string Option name
- * @return mixed Option value, null if option does not exist
- */
- public static function getOption($name)
- {
- return isset(self::$_options[$name])? self::$_options[$name]: null;
- }
-
- /**
- * Parses the HTML attributes given as string
- *
- * @param string HTML attribute string
- * @return array An associative aray of attributes
- */
- protected static function parseAttributes($attrString)
- {
- $attributes = array();
- if (preg_match_all(
- "/(([A-Za-z_:]|[^\\x00-\\x7F])([A-Za-z0-9_:.-]|[^\\x00-\\x7F])*)" .
- "([ \\n\\t\\r]+)?(=([ \\n\\t\\r]+)?(\"[^\"]*\"|'[^']*'|[^ \\n\\t\\r]*))?/",
- $attrString,
- $regs
- )) {
- for ($i = 0; $i < count($regs[1]); $i++) {
- $name = trim($regs[1][$i]);
- $check = trim($regs[0][$i]);
- $value = trim($regs[7][$i]);
- if ($name == $check) {
- $attributes[strtolower($name)] = strtolower($name);
- } else {
- if (!empty($value) && ($value[0] == '\'' || $value[0] == '"')) {
- $value = substr($value, 1, -1);
- }
- $attributes[strtolower($name)] = $value;
- }
- }
- }
- return $attributes;
- }
-
- /**
- * Creates a valid attribute array from either a string or an array
- *
- * @param mixed Array of attributes or HTML attribute string
- * @return array An associative aray of attributes
- */
- protected static function prepareAttributes($attributes)
- {
- $prepared = array();
- if (is_string($attributes)) {
- return self::parseAttributes($attributes);
-
- } elseif (is_array($attributes)) {
- foreach ($attributes as $key => $value) {
- if (is_int($key)) {
- $key = strtolower($value);
- $prepared[$key] = $key;
- } else {
- $prepared[strtolower($key)] = (string)$value;
- }
- }
- }
- return $prepared;
- }
-
- /**
- * Removes an attribute from an attribute array
- *
- * @param array Attribute array
- * @param string Name of attribute to remove
- */
- protected static function removeAttributeArray(&$attributes, $name)
- {
- unset($attributes[strtolower($name)]);
- }
-
- /**
- * Creates HTML attribute string from array
- *
- * @param array Attribute array
- * @return string Attribute string
- */
- protected static function getAttributesString($attributes)
- {
- $str = '';
- if (is_array($attributes)) {
- $charset = self::getOption('charset');
- foreach ($attributes as $key => $value) {
- $str .= ' ' . $key . '="' . htmlspecialchars($value, ENT_QUOTES, $charset) . '"';
- }
- }
- return $str;
- }
-
- /**
- * Class constructor, sets default attributes
- *
- * @param mixed Array of attribute 'name' => 'value' pairs or HTML attribute string
- */
- public function __construct($attributes = null)
- {
- $this->mergeAttributes($attributes);
- }
-
- /**
- * Sets the value of the attribute
- *
- * @param string Attribute name
- * @param string Attribute value (will be set to $name if omitted)
- * @return HTML_Common2
- */
- public function setAttribute($name, $value = null)
- {
- $name = strtolower($name);
- if (is_null($value)) {
- $value = $name;
- }
- if (in_array($name, $this->watchedAttributes)) {
- $this->onAttributeChange($name, $value);
- } else {
- $this->attributes[$name] = (string)$value;
- }
- return $this;
- }
-
- /**
- * Returns the value of an attribute
- *
- * @param string Attribute name
- * @return string Attribute value, null if attribute does not exist
- */
- public function getAttribute($name)
- {
- $name = strtolower($name);
- return isset($this->attributes[$name])? $this->attributes[$name]: null;
- }
-
- /**
- * Sets the attributes
- *
- * @param mixed Array of attribute 'name' => 'value' pairs or HTML attribute string
- * @return HTML_Common2
- */
- public function setAttributes($attributes)
- {
- $attributes = self::prepareAttributes($attributes);
- $watched = array();
- foreach ($this->watchedAttributes as $watchedKey) {
- if (isset($attributes[$watchedKey])) {
- $this->setAttribute($watchedKey, $attributes[$watchedKey]);
- unset($attributes[$watchedKey]);
- } else {
- $this->removeAttribute($watchedKey);
- }
- if (isset($this->attributes[$watchedKey])) {
- $watched[$watchedKey] = $this->attributes[$watchedKey];
- }
- }
- $this->attributes = array_merge($watched, $attributes);
- return $this;
- }
-
- /**
- * Returns the attribute array or string
- *
- * @param bool Whether to return attributes as string
- * @return mixed Either an array or string of attributes
- */
- public function getAttributes($asString = false)
- {
- if ($asString) {
- return self::getAttributesString($this->attributes);
- } else {
- return $this->attributes;
- }
- }
-
- /**
- * Merges the existing attributes with the new ones
- *
- * @param mixed Array of attribute 'name' => 'value' pairs or HTML attribute string
- * @return HTML_Common2
- */
- public function mergeAttributes($attributes)
- {
- $attributes = self::prepareAttributes($attributes);
- foreach ($this->watchedAttributes as $watchedKey) {
- if (isset($attributes[$watchedKey])) {
- $this->onAttributeChange($watchedKey, $attributes[$watchedKey]);
- unset($attributes[$watchedKey]);
- }
- }
- $this->attributes = array_merge($this->attributes, $attributes);
- return $this;
- }
-
- /**
- * Removes an attribute
- *
- * @param string Name of attribute to remove
- * @return HTML_Common2
- */
- public function removeAttribute($attribute)
- {
- if (in_array(strtolower($attribute), $this->watchedAttributes)) {
- $this->onAttributeChange(strtolower($attribute), null);
- } else {
- self::removeAttributeArray($this->attributes, $attribute);
- }
- return $this;
- }
-
- /**
- * Sets the indentation level
- *
- * @param int
- * @return HTML_Common2
- */
- public function setIndentLevel($level)
- {
- $level = intval($level);
- if (0 <= $level) {
- $this->_indentLevel = $level;
- }
- return $this;
- }
-
- /**
- * Gets the indentation level
- *
- * @return int
- */
- public function getIndentLevel()
- {
- return $this->_indentLevel;
- }
-
- /**
- * Returns the string to indent the element
- *
- * @return string
- */
- protected function getIndent()
- {
- return str_repeat(self::getOption('indent'), $this->getIndentLevel());
- }
-
- /**
- * Sets the comment for the element
- *
- * @param string
- * @return HTML_Common2
- */
- public function setComment($comment)
- {
- $this->_comment = $comment;
- return $this;
- }
-
- /**
- * Returns the comment associated with the element
- *
- * @return string
- */
- public function getComment()
- {
- return $this->_comment;
- }
-
- /**
- * Returns the HTML representation of the element
- *
- * This magic method allows using the instances of HTML_Common2 in string
- * contexts
- *
- * @return string
- */
- abstract public function __toString();
-
- /**
- * Called if trying to change an attribute with name in $watchedAttributes
- *
- * This method is called for each attribute whose name is in the
- * $watchedAttributes array and which is being changed by setAttribute(),
- * setAttributes() or mergeAttributes() or removed via removeAttribute().
- * Note that the operation for the attribute is not carried on after calling
- * this method, it is the responsibility of this method to change or remove
- * (or not) the attribute.
- *
- * @param string Attribute name
- * @param string Attribute value, null if attribute is being removed
- */
- protected function onAttributeChange($name, $value = null)
- {
- }
-}
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP version 4.0 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Adam Daniel <adaniel1@eesus.jnj.com> |
-// | Bertrand Mansion <bmansion@mamasam.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: QuickForm.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-require_once('PEAR.php');
-require_once('HTML/Common.php');
-
-$GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] =
- array(
- 'group' =>array('HTML/QuickForm/group.php','HTML_QuickForm_group'),
- 'hidden' =>array('HTML/QuickForm/hidden.php','HTML_QuickForm_hidden'),
- 'reset' =>array('HTML/QuickForm/reset.php','HTML_QuickForm_reset'),
- 'checkbox' =>array('HTML/QuickForm/checkbox.php','HTML_QuickForm_checkbox'),
- 'file' =>array('HTML/QuickForm/file.php','HTML_QuickForm_file'),
- 'image' =>array('HTML/QuickForm/image.php','HTML_QuickForm_image'),
- 'password' =>array('HTML/QuickForm/password.php','HTML_QuickForm_password'),
- 'radio' =>array('HTML/QuickForm/radio.php','HTML_QuickForm_radio'),
- 'button' =>array('HTML/QuickForm/button.php','HTML_QuickForm_button'),
- 'submit' =>array('HTML/QuickForm/submit.php','HTML_QuickForm_submit'),
- 'select' =>array('HTML/QuickForm/select.php','HTML_QuickForm_select'),
- 'hiddenselect' =>array('HTML/QuickForm/hiddenselect.php','HTML_QuickForm_hiddenselect'),
- 'text' =>array('HTML/QuickForm/text.php','HTML_QuickForm_text'),
- 'textarea' =>array('HTML/QuickForm/textarea.php','HTML_QuickForm_textarea'),
- 'link' =>array('HTML/QuickForm/link.php','HTML_QuickForm_link'),
- 'advcheckbox' =>array('HTML/QuickForm/advcheckbox.php','HTML_QuickForm_advcheckbox'),
- 'date' =>array('HTML/QuickForm/date.php','HTML_QuickForm_date'),
- 'static' =>array('HTML/QuickForm/static.php','HTML_QuickForm_static'),
- 'header' =>array('HTML/QuickForm/header.php', 'HTML_QuickForm_header'),
- 'html' =>array('HTML/QuickForm/html.php', 'HTML_QuickForm_html'),
- 'hierselect' =>array('HTML/QuickForm/hierselect.php', 'HTML_QuickForm_hierselect'),
- 'autocomplete' =>array('HTML/QuickForm/autocomplete.php', 'HTML_QuickForm_autocomplete'),
- 'xbutton' =>array('HTML/QuickForm/xbutton.php','HTML_QuickForm_xbutton')
- );
-
-$GLOBALS['_HTML_QuickForm_registered_rules'] = array(
- 'required' => array('html_quickform_rule_required', 'HTML/QuickForm/Rule/Required.php'),
- 'maxlength' => array('html_quickform_rule_range', 'HTML/QuickForm/Rule/Range.php'),
- 'minlength' => array('html_quickform_rule_range', 'HTML/QuickForm/Rule/Range.php'),
- 'rangelength' => array('html_quickform_rule_range', 'HTML/QuickForm/Rule/Range.php'),
- 'email' => array('html_quickform_rule_email', 'HTML/QuickForm/Rule/Email.php'),
- 'regex' => array('html_quickform_rule_regex', 'HTML/QuickForm/Rule/Regex.php'),
- 'lettersonly' => array('html_quickform_rule_regex', 'HTML/QuickForm/Rule/Regex.php'),
- 'alphanumeric' => array('html_quickform_rule_regex', 'HTML/QuickForm/Rule/Regex.php'),
- 'numeric' => array('html_quickform_rule_regex', 'HTML/QuickForm/Rule/Regex.php'),
- 'nopunctuation' => array('html_quickform_rule_regex', 'HTML/QuickForm/Rule/Regex.php'),
- 'nonzero' => array('html_quickform_rule_regex', 'HTML/QuickForm/Rule/Regex.php'),
- 'callback' => array('html_quickform_rule_callback', 'HTML/QuickForm/Rule/Callback.php'),
- 'compare' => array('html_quickform_rule_compare', 'HTML/QuickForm/Rule/Compare.php')
-);
-
-// {{{ error codes
-
-/*
- * Error codes for the QuickForm interface, which will be mapped to textual messages
- * in the QuickForm::errorMessage() function. If you are to add a new error code, be
- * sure to add the textual messages to the QuickForm::errorMessage() function as well
- */
-
-define('QUICKFORM_OK', 1);
-define('QUICKFORM_ERROR', -1);
-define('QUICKFORM_INVALID_RULE', -2);
-define('QUICKFORM_NONEXIST_ELEMENT', -3);
-define('QUICKFORM_INVALID_FILTER', -4);
-define('QUICKFORM_UNREGISTERED_ELEMENT', -5);
-define('QUICKFORM_INVALID_ELEMENT_NAME', -6);
-define('QUICKFORM_INVALID_PROCESS', -7);
-define('QUICKFORM_DEPRECATED', -8);
-define('QUICKFORM_INVALID_DATASOURCE', -9);
-
-// }}}
-
-/**
-* Create, validate and process HTML forms
-*
-* @author Adam Daniel <adaniel1@eesus.jnj.com>
-* @author Bertrand Mansion <bmansion@mamasam.com>
-* @version 2.0
-* @since PHP 4.0.3pl1
-*/
-class HTML_QuickForm extends HTML_Common {
- // {{{ properties
-
- /**
- * Array containing the form fields
- * @since 1.0
- * @var array
- * @access private
- */
- var $_elements = array();
-
- /**
- * Array containing element name to index map
- * @since 1.1
- * @var array
- * @access private
- */
- var $_elementIndex = array();
-
- /**
- * Array containing indexes of duplicate elements
- * @since 2.10
- * @var array
- * @access private
- */
- var $_duplicateIndex = array();
-
- /**
- * Array containing required field IDs
- * @since 1.0
- * @var array
- * @access private
- */
- var $_required = array();
-
- /**
- * Prefix message in javascript alert if error
- * @since 1.0
- * @var string
- * @access public
- */
- var $_jsPrefix = 'Invalid information entered.';
-
- /**
- * Postfix message in javascript alert if error
- * @since 1.0
- * @var string
- * @access public
- */
- var $_jsPostfix = 'Please correct these fields.';
-
- /**
- * Datasource object implementing the informal
- * datasource protocol
- * @since 3.3
- * @var object
- * @access private
- */
- var $_datasource;
-
- /**
- * Array of default form values
- * @since 2.0
- * @var array
- * @access private
- */
- var $_defaultValues = array();
-
- /**
- * Array of constant form values
- * @since 2.0
- * @var array
- * @access private
- */
- var $_constantValues = array();
-
- /**
- * Array of submitted form values
- * @since 1.0
- * @var array
- * @access private
- */
- var $_submitValues = array();
-
- /**
- * Array of submitted form files
- * @since 1.0
- * @var integer
- * @access public
- */
- var $_submitFiles = array();
-
- /**
- * Value for maxfilesize hidden element if form contains file input
- * @since 1.0
- * @var integer
- * @access public
- */
- var $_maxFileSize = 1048576; // 1 Mb = 1048576
-
- /**
- * Flag to know if all fields are frozen
- * @since 1.0
- * @var boolean
- * @access private
- */
- var $_freezeAll = false;
-
- /**
- * Array containing the form rules
- * @since 1.0
- * @var array
- * @access private
- */
- var $_rules = array();
-
- /**
- * Form rules, global variety
- * @var array
- * @access private
- */
- var $_formRules = array();
-
- /**
- * Array containing the validation errors
- * @since 1.0
- * @var array
- * @access private
- */
- var $_errors = array();
-
- /**
- * Note for required fields in the form
- * @var string
- * @since 1.0
- * @access public
- */
- var $_requiredNote = '<span style="font-size:80%; color:#ff0000;">*</span><span style="font-size:80%;"> denotes required field</span>';
-
- /**
- * Whether the form was submitted
- * @var boolean
- * @access private
- */
- var $_flagSubmitted = false;
-
- // }}}
- // {{{ constructor
-
- /**
- * Class constructor
- * @param string $formName Form's name.
- * @param string $method (optional)Form's method defaults to 'POST'
- * @param string $action (optional)Form's action
- * @param string $target (optional)Form's target defaults to '_self'
- * @param mixed $attributes (optional)Extra attributes for <form> tag
- * @param bool $trackSubmit (optional)Whether to track if the form was submitted by adding a special hidden field
- * @access public
- */
- function HTML_QuickForm($formName='', $method='post', $action='', $target='_self', $attributes=null, $trackSubmit = false)
- {
- HTML_Common::HTML_Common($attributes);
- $method = (strtoupper($method) == 'GET') ? 'get' : 'post';
- $action = ($action == '') ? $_SERVER['PHP_SELF'] : $action;
- $target = (empty($target) || $target == '_self') ? array() : array('target' => $target);
- $attributes = array('action'=>$action, 'method'=>$method, 'name'=>$formName, 'id'=>$formName) + $target;
- $this->updateAttributes($attributes);
- if (!$trackSubmit || isset($_REQUEST['_qf__' . $formName])) {
- if (1 == get_magic_quotes_gpc()) {
- $this->_submitValues = $this->_recursiveFilter('stripslashes', 'get' == $method? $_GET: $_POST);
- foreach ($_FILES as $keyFirst => $valFirst) {
- foreach ($valFirst as $keySecond => $valSecond) {
- if ('name' == $keySecond) {
- $this->_submitFiles[$keyFirst][$keySecond] = $this->_recursiveFilter('stripslashes', $valSecond);
- } else {
- $this->_submitFiles[$keyFirst][$keySecond] = $valSecond;
- }
- }
- }
- } else {
- $this->_submitValues = 'get' == $method? $_GET: $_POST;
- $this->_submitFiles = $_FILES;
- }
- }
-
- $this->_flagSubmitted = count($this->_submitValues) > 0 || count($this->_submitFiles) > 0;
-
- if ($trackSubmit) {
- unset($this->_submitValues['_qf__' . $formName]);
- $this->addElement('hidden', '_qf__' . $formName, null);
- }
- } // end constructor
-
- // }}}
- // {{{ apiVersion()
-
- /**
- * Returns the current API version
- *
- * @since 1.0
- * @access public
- * @return float
- */
- function apiVersion()
- {
- return 3.2;
- } // end func apiVersion
-
- // }}}
- // {{{ registerElementType()
-
- /**
- * Registers a new element type
- *
- * @param string $typeName Name of element type
- * @param string $include Include path for element type
- * @param string $className Element class name
- * @since 1.0
- * @access public
- * @return void
- */
- function registerElementType($typeName, $include, $className)
- {
- $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'][strtolower($typeName)] = array($include, $className);
- } // end func registerElementType
-
- // }}}
- // {{{ registerRule()
-
- /**
- * Registers a new validation rule
- *
- * @param string $ruleName Name of validation rule
- * @param string $type Either: 'regex', 'function' or 'rule' for an HTML_QuickForm_Rule object
- * @param string $data1 Name of function, regular expression or HTML_QuickForm_Rule classname
- * @param string $data2 Object parent of above function or HTML_QuickForm_Rule file path
- * @since 1.0
- * @access public
- * @return void
- */
- function registerRule($ruleName, $type, $data1, $data2 = null)
- {
- include_once('HTML/QuickForm/RuleRegistry.php');
- $registry =& HTML_QuickForm_RuleRegistry::singleton();
- $registry->registerRule($ruleName, $type, $data1, $data2);
- } // end func registerRule
-
- // }}}
- // {{{ elementExists()
-
- /**
- * Returns true if element is in the form
- *
- * @param string $element form name of element to check
- * @since 1.0
- * @access public
- * @return boolean
- */
- function elementExists($element=null)
- {
- return isset($this->_elementIndex[$element]);
- } // end func elementExists
-
- // }}}
- // {{{ setDatasource()
-
- /**
- * Sets a datasource object for this form object
- *
- * Datasource default and constant values will feed the QuickForm object if
- * the datasource implements defaultValues() and constantValues() methods.
- *
- * @param object $datasource datasource object implementing the informal datasource protocol
- * @param mixed $defaultsFilter string or array of filter(s) to apply to default values
- * @param mixed $constantsFilter string or array of filter(s) to apply to constants values
- * @since 3.3
- * @access public
- * @return void
- */
- function setDatasource(&$datasource, $defaultsFilter = null, $constantsFilter = null)
- {
- if (is_object($datasource)) {
- $this->_datasource =& $datasource;
- if (is_callable(array($datasource, 'defaultValues'))) {
- $this->setDefaults($datasource->defaultValues($this), $defaultsFilter);
- }
- if (is_callable(array($datasource, 'constantValues'))) {
- $this->setConstants($datasource->constantValues($this), $constantsFilter);
- }
- } else {
- return PEAR::raiseError(null, QUICKFORM_INVALID_DATASOURCE, null, E_USER_WARNING, "Datasource is not an object in QuickForm::setDatasource()", 'HTML_QuickForm_Error', true);
- }
- } // end func setDatasource
-
- // }}}
- // {{{ setDefaults()
-
- /**
- * Initializes default form values
- *
- * @param array $defaultValues values used to fill the form
- * @param mixed $filter (optional) filter(s) to apply to all default values
- * @since 1.0
- * @access public
- * @return void
- */
- function setDefaults($defaultValues = null, $filter = null)
- {
- if (is_array($defaultValues)) {
- if (isset($filter)) {
- if (is_array($filter) && (2 != count($filter) || !is_callable($filter))) {
- foreach ($filter as $val) {
- if (!is_callable($val)) {
- return PEAR::raiseError(null, QUICKFORM_INVALID_FILTER, null, E_USER_WARNING, "Callback function does not exist in QuickForm::setDefaults()", 'HTML_QuickForm_Error', true);
- } else {
- $defaultValues = $this->_recursiveFilter($val, $defaultValues);
- }
- }
- } elseif (!is_callable($filter)) {
- return PEAR::raiseError(null, QUICKFORM_INVALID_FILTER, null, E_USER_WARNING, "Callback function does not exist in QuickForm::setDefaults()", 'HTML_QuickForm_Error', true);
- } else {
- $defaultValues = $this->_recursiveFilter($filter, $defaultValues);
- }
- }
- $this->_defaultValues = HTML_QuickForm::arrayMerge($this->_defaultValues, $defaultValues);
- foreach (array_keys($this->_elements) as $key) {
- $this->_elements[$key]->onQuickFormEvent('updateValue', null, $this);
- }
- }
- } // end func setDefaults
-
- // }}}
- // {{{ setConstants()
-
- /**
- * Initializes constant form values.
- * These values won't get overridden by POST or GET vars
- *
- * @param array $constantValues values used to fill the form
- * @param mixed $filter (optional) filter(s) to apply to all default values
- *
- * @since 2.0
- * @access public
- * @return void
- */
- function setConstants($constantValues = null, $filter = null)
- {
- if (is_array($constantValues)) {
- if (isset($filter)) {
- if (is_array($filter) && (2 != count($filter) || !is_callable($filter))) {
- foreach ($filter as $val) {
- if (!is_callable($val)) {
- return PEAR::raiseError(null, QUICKFORM_INVALID_FILTER, null, E_USER_WARNING, "Callback function does not exist in QuickForm::setConstants()", 'HTML_QuickForm_Error', true);
- } else {
- $constantValues = $this->_recursiveFilter($val, $constantValues);
- }
- }
- } elseif (!is_callable($filter)) {
- return PEAR::raiseError(null, QUICKFORM_INVALID_FILTER, null, E_USER_WARNING, "Callback function does not exist in QuickForm::setConstants()", 'HTML_QuickForm_Error', true);
- } else {
- $constantValues = $this->_recursiveFilter($filter, $constantValues);
- }
- }
- $this->_constantValues = HTML_QuickForm::arrayMerge($this->_constantValues, $constantValues);
- foreach (array_keys($this->_elements) as $key) {
- $this->_elements[$key]->onQuickFormEvent('updateValue', null, $this);
- }
- }
- } // end func setConstants
-
- // }}}
- // {{{ setMaxFileSize()
-
- /**
- * Sets the value of MAX_FILE_SIZE hidden element
- *
- * @param int $bytes Size in bytes
- * @since 3.0
- * @access public
- * @return void
- */
- function setMaxFileSize($bytes = 0)
- {
- if ($bytes > 0) {
- $this->_maxFileSize = $bytes;
- }
- if (!$this->elementExists('MAX_FILE_SIZE')) {
- $this->addElement('hidden', 'MAX_FILE_SIZE', $this->_maxFileSize);
- } else {
- $el =& $this->getElement('MAX_FILE_SIZE');
- $el->updateAttributes(array('value' => $this->_maxFileSize));
- }
- } // end func setMaxFileSize
-
- // }}}
- // {{{ getMaxFileSize()
-
- /**
- * Returns the value of MAX_FILE_SIZE hidden element
- *
- * @since 3.0
- * @access public
- * @return int max file size in bytes
- */
- function getMaxFileSize()
- {
- return $this->_maxFileSize;
- } // end func getMaxFileSize
-
- // }}}
- // {{{ &createElement()
-
- /**
- * Creates a new form element of the given type.
- *
- * This method accepts variable number of parameters, their
- * meaning and count depending on $elementType
- *
- * @param string $elementType type of element to add (text, textarea, file...)
- * @since 1.0
- * @access public
- * @return object extended class of HTML_element
- * @throws HTML_QuickForm_Error
- */
- function &createElement($elementType)
- {
- $args = func_get_args();
- return HTML_QuickForm::_loadElement('createElement', $elementType, array_slice($args, 1));
- } // end func createElement
-
- // }}}
- // {{{ _loadElement()
-
- /**
- * Returns a form element of the given type
- *
- * @param string $event event to send to newly created element ('createElement' or 'addElement')
- * @param string $type element type
- * @param array $args arguments for event
- * @since 2.0
- * @access private
- * @return object a new element
- * @throws HTML_QuickForm_Error
- */
- function &_loadElement($event, $type, $args)
- {
- $type = strtolower($type);
- if (!HTML_QuickForm::isTypeRegistered($type)) {
- return PEAR::raiseError(null, QUICKFORM_UNREGISTERED_ELEMENT, null, E_USER_WARNING, "Element '$type' does not exist in HTML_QuickForm::_loadElement()", 'HTML_QuickForm_Error', true);
- }
- $className = $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'][$type][1];
- $includeFile = $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'][$type][0];
- include_once($includeFile);
- $elementObject = new $className();
- for ($i = 0; $i < 5; $i++) {
- if (!isset($args[$i])) {
- $args[$i] = null;
- }
- }
- $err = $elementObject->onQuickFormEvent($event, $args, $this);
- if ($err !== true) {
- return $err;
- }
- return $elementObject;
- } // end func _loadElement
-
- // }}}
- // {{{ addElement()
-
- /**
- * Adds an element into the form
- *
- * If $element is a string representing element type, then this
- * method accepts variable number of parameters, their meaning
- * and count depending on $element
- *
- * @param mixed $element element object or type of element to add (text, textarea, file...)
- * @since 1.0
- * @return object reference to element
- * @access public
- * @throws HTML_QuickForm_Error
- */
- function &addElement($element)
- {
- if (is_object($element) && is_subclass_of($element, 'html_quickform_element')) {
- $elementObject = &$element;
- $elementObject->onQuickFormEvent('updateValue', null, $this);
- } else {
- $args = func_get_args();
- $elementObject =& $this->_loadElement('addElement', $element, array_slice($args, 1));
- if (PEAR::isError($elementObject)) {
- return $elementObject;
- }
- }
- $elementName = $elementObject->getName();
-
- // Add the element if it is not an incompatible duplicate
- if (!empty($elementName) && isset($this->_elementIndex[$elementName])) {
- if ($this->_elements[$this->_elementIndex[$elementName]]->getType() ==
- $elementObject->getType()) {
- $this->_elements[] =& $elementObject;
- $this->_duplicateIndex[$elementName][] = end(array_keys($this->_elements));
- } else {
- return PEAR::raiseError(null, QUICKFORM_INVALID_ELEMENT_NAME, null, E_USER_WARNING, "Element '$elementName' already exists in HTML_QuickForm::addElement()", 'HTML_QuickForm_Error', true);
- }
- } else {
- $this->_elements[] =& $elementObject;
- $this->_elementIndex[$elementName] = end(array_keys($this->_elements));
- }
- if ($this->_freezeAll) {
- $elementObject->freeze();
- }
-
- return $elementObject;
- } // end func addElement
-
- // }}}
- // {{{ insertElementBefore()
-
- /**
- * Inserts a new element right before the other element
- *
- * Warning: it is not possible to check whether the $element is already
- * added to the form, therefore if you want to move the existing form
- * element to a new position, you'll have to use removeElement():
- * $form->insertElementBefore($form->removeElement('foo', false), 'bar');
- *
- * @access public
- * @since 3.2.4
- * @param object HTML_QuickForm_element Element to insert
- * @param string Name of the element before which the new one is inserted
- * @return object HTML_QuickForm_element reference to inserted element
- * @throws HTML_QuickForm_Error
- */
- function &insertElementBefore(&$element, $nameAfter)
- {
- if (!empty($this->_duplicateIndex[$nameAfter])) {
- return PEAR::raiseError(null, QUICKFORM_INVALID_ELEMENT_NAME, null, E_USER_WARNING, 'Several elements named "' . $nameAfter . '" exist in HTML_QuickForm::insertElementBefore().', 'HTML_QuickForm_Error', true);
- } elseif (!$this->elementExists($nameAfter)) {
- return PEAR::raiseError(null, QUICKFORM_NONEXIST_ELEMENT, null, E_USER_WARNING, "Element '$nameAfter' does not exist in HTML_QuickForm::insertElementBefore()", 'HTML_QuickForm_Error', true);
- }
- $elementName = $element->getName();
- $targetIdx = $this->_elementIndex[$nameAfter];
- $duplicate = false;
- // Like in addElement(), check that it's not an incompatible duplicate
- if (!empty($elementName) && isset($this->_elementIndex[$elementName])) {
- if ($this->_elements[$this->_elementIndex[$elementName]]->getType() != $element->getType()) {
- return PEAR::raiseError(null, QUICKFORM_INVALID_ELEMENT_NAME, null, E_USER_WARNING, "Element '$elementName' already exists in HTML_QuickForm::insertElementBefore()", 'HTML_QuickForm_Error', true);
- }
- $duplicate = true;
- }
- // Move all the elements after added back one place, reindex _elementIndex and/or _duplicateIndex
- for ($i = end(array_keys($this->_elements)); $i >= $targetIdx; $i--) {
- if (isset($this->_elements[$i])) {
- $currentName = $this->_elements[$i]->getName();
- $this->_elements[$i + 1] =& $this->_elements[$i];
- if ($this->_elementIndex[$currentName] == $i) {
- $this->_elementIndex[$currentName] = $i + 1;
- } else {
- $dupIdx = array_search($i, $this->_duplicateIndex[$currentName]);
- $this->_duplicateIndex[$currentName][$dupIdx] = $i + 1;
- }
- unset($this->_elements[$i]);
- }
- }
- // Put the element in place finally
- $this->_elements[$targetIdx] =& $element;
- if (!$duplicate) {
- $this->_elementIndex[$elementName] = $targetIdx;
- } else {
- $this->_duplicateIndex[$elementName][] = $targetIdx;
- }
- $element->onQuickFormEvent('updateValue', null, $this);
- if ($this->_freezeAll) {
- $element->freeze();
- }
- // If not done, the elements will appear in reverse order
- ksort($this->_elements);
- return $element;
- }
-
- // }}}
- // {{{ addGroup()
-
- /**
- * Adds an element group
- * @param array $elements array of elements composing the group
- * @param string $name (optional)group name
- * @param string $groupLabel (optional)group label
- * @param string $separator (optional)string to separate elements
- * @param string $appendName (optional)specify whether the group name should be
- * used in the form element name ex: group[element]
- * @return object reference to added group of elements
- * @since 2.8
- * @access public
- * @throws PEAR_Error
- */
- function &addGroup($elements, $name=null, $groupLabel='', $separator=null, $appendName = true)
- {
- static $anonGroups = 1;
-
- if (0 == strlen($name)) {
- $name = 'qf_group_' . $anonGroups++;
- $appendName = false;
- }
- return $this->addElement('group', $name, $groupLabel, $elements, $separator, $appendName);
- } // end func addGroup
-
- // }}}
- // {{{ &getElement()
-
- /**
- * Returns a reference to the element
- *
- * @param string $element Element name
- * @since 2.0
- * @access public
- * @return object reference to element
- * @throws HTML_QuickForm_Error
- */
- function &getElement($element)
- {
- if (isset($this->_elementIndex[$element])) {
- return $this->_elements[$this->_elementIndex[$element]];
- } else {
- return PEAR::raiseError(null, QUICKFORM_NONEXIST_ELEMENT, null, E_USER_WARNING, "Element '$element' does not exist in HTML_QuickForm::getElement()", 'HTML_QuickForm_Error', true);
- }
- } // end func getElement
-
- // }}}
- // {{{ &getElementValue()
-
- /**
- * Returns the element's raw value
- *
- * This returns the value as submitted by the form (not filtered)
- * or set via setDefaults() or setConstants()
- *
- * @param string $element Element name
- * @since 2.0
- * @access public
- * @return mixed element value
- * @throws HTML_QuickForm_Error
- */
- function &getElementValue($element)
- {
- if (!isset($this->_elementIndex[$element])) {
- return PEAR::raiseError(null, QUICKFORM_NONEXIST_ELEMENT, null, E_USER_WARNING, "Element '$element' does not exist in HTML_QuickForm::getElementValue()", 'HTML_QuickForm_Error', true);
- }
- $value = $this->_elements[$this->_elementIndex[$element]]->getValue();
- if (isset($this->_duplicateIndex[$element])) {
- foreach ($this->_duplicateIndex[$element] as $index) {
- if (null !== ($v = $this->_elements[$index]->getValue())) {
- if (is_array($value)) {
- $value[] = $v;
- } else {
- $value = (null === $value)? $v: array($value, $v);
- }
- }
- }
- }
- return $value;
- } // end func getElementValue
-
- // }}}
- // {{{ getSubmitValue()
-
- /**
- * Returns the elements value after submit and filter
- *
- * @param string Element name
- * @since 2.0
- * @access public
- * @return mixed submitted element value or null if not set
- */
- function getSubmitValue($elementName)
- {
- $value = null;
- if (isset($this->_submitValues[$elementName]) || isset($this->_submitFiles[$elementName])) {
- $value = isset($this->_submitValues[$elementName])? $this->_submitValues[$elementName]: array();
- if (is_array($value) && isset($this->_submitFiles[$elementName])) {
- foreach ($this->_submitFiles[$elementName] as $k => $v) {
- $value = HTML_QuickForm::arrayMerge($value, $this->_reindexFiles($this->_submitFiles[$elementName][$k], $k));
- }
- }
-
- } elseif ('file' == $this->getElementType($elementName)) {
- return $this->getElementValue($elementName);
-
- } elseif ('group' == $this->getElementType($elementName)) {
- $group =& $this->getElement($elementName);
- $elements =& $group->getElements();
- foreach (array_keys($elements) as $key) {
- $name = $group->getElementName($key);
- // filter out radios
- if ($name != $elementName) {
- if (null !== ($v = $this->getSubmitValue($name))) {
- $value[$name] = $v;
- }
- }
- }
-
- } elseif (false !== ($pos = strpos($elementName, '['))) {
- $base = substr($elementName, 0, $pos);
- $idx = "['" . str_replace(array(']', '['), array('', "']['"), substr($elementName, $pos + 1, -1)) . "']";
- if (isset($this->_submitValues[$base])) {
- $value = eval("return (isset(\$this->_submitValues['{$base}']{$idx})) ? \$this->_submitValues['{$base}']{$idx} : null;");
- }
-
- if (null === $value && isset($this->_submitFiles[$base])) {
- $props = array('name', 'type', 'size', 'tmp_name', 'error');
- $code = "if (!isset(\$this->_submitFiles['{$base}']['name']{$idx})) {\n" .
- " return null;\n" .
- "} else {\n" .
- " \$v = array();\n";
- foreach ($props as $prop) {
- $code .= " \$v['{$prop}'] = \$this->_submitFiles['{$base}']['{$prop}']{$idx};\n";
- }
- $value = eval($code . " return \$v;\n}\n");
- }
- }
- return $value;
- } // end func getSubmitValue
-
- // }}}
- // {{{ _reindexFiles()
-
- /**
- * A helper function to change the indexes in $_FILES array
- *
- * @param mixed Some value from the $_FILES array
- * @param string The key from the $_FILES array that should be appended
- * @return array
- */
- function _reindexFiles($value, $key)
- {
- if (!is_array($value)) {
- return array($key => $value);
- } else {
- $ret = array();
- foreach ($value as $k => $v) {
- $ret[$k] = $this->_reindexFiles($v, $key);
- }
- return $ret;
- }
- }
-
- // }}}
- // {{{ getElementError()
-
- /**
- * Returns error corresponding to validated element
- *
- * @param string $element Name of form element to check
- * @since 1.0
- * @access public
- * @return string error message corresponding to checked element
- */
- function getElementError($element)
- {
- if (isset($this->_errors[$element])) {
- return $this->_errors[$element];
- }
- } // end func getElementError
-
- // }}}
- // {{{ setElementError()
-
- /**
- * Set error message for a form element
- *
- * @param string $element Name of form element to set error for
- * @param string $message Error message
- * @since 1.0
- * @access public
- * @return void
- */
- function setElementError($element,$message)
- {
- $this->_errors[$element] = $message;
- } // end func setElementError
-
- // }}}
- // {{{ getElementType()
-
- /**
- * Returns the type of the given element
- *
- * @param string $element Name of form element
- * @since 1.1
- * @access public
- * @return string Type of the element, false if the element is not found
- */
- function getElementType($element)
- {
- if (isset($this->_elementIndex[$element])) {
- return $this->_elements[$this->_elementIndex[$element]]->getType();
- }
- return false;
- } // end func getElementType
-
- // }}}
- // {{{ updateElementAttr()
-
- /**
- * Updates Attributes for one or more elements
- *
- * @param mixed $elements Array of element names/objects or string of elements to be updated
- * @param mixed $attrs Array or sting of html attributes
- * @since 2.10
- * @access public
- * @return void
- */
- function updateElementAttr($elements, $attrs)
- {
- if (is_string($elements)) {
- $elements = split('[ ]?,[ ]?', $elements);
- }
- foreach (array_keys($elements) as $key) {
- if (is_object($elements[$key]) && is_a($elements[$key], 'HTML_QuickForm_element')) {
- $elements[$key]->updateAttributes($attrs);
- } elseif (isset($this->_elementIndex[$elements[$key]])) {
- $this->_elements[$this->_elementIndex[$elements[$key]]]->updateAttributes($attrs);
- if (isset($this->_duplicateIndex[$elements[$key]])) {
- foreach ($this->_duplicateIndex[$elements[$key]] as $index) {
- $this->_elements[$index]->updateAttributes($attrs);
- }
- }
- }
- }
- } // end func updateElementAttr
-
- // }}}
- // {{{ removeElement()
-
- /**
- * Removes an element
- *
- * The method "unlinks" an element from the form, returning the reference
- * to the element object. If several elements named $elementName exist,
- * it removes the first one, leaving the others intact.
- *
- * @param string $elementName The element name
- * @param boolean $removeRules True if rules for this element are to be removed too
- * @access public
- * @since 2.0
- * @return object HTML_QuickForm_element a reference to the removed element
- * @throws HTML_QuickForm_Error
- */
- function &removeElement($elementName, $removeRules = true)
- {
- if (!isset($this->_elementIndex[$elementName])) {
- return PEAR::raiseError(null, QUICKFORM_NONEXIST_ELEMENT, null, E_USER_WARNING, "Element '$elementName' does not exist in HTML_QuickForm::removeElement()", 'HTML_QuickForm_Error', true);
- }
- $el =& $this->_elements[$this->_elementIndex[$elementName]];
- unset($this->_elements[$this->_elementIndex[$elementName]]);
- if (empty($this->_duplicateIndex[$elementName])) {
- unset($this->_elementIndex[$elementName]);
- } else {
- $this->_elementIndex[$elementName] = array_shift($this->_duplicateIndex[$elementName]);
- }
- if ($removeRules) {
- unset($this->_rules[$elementName]);
- }
- return $el;
- } // end func removeElement
-
- // }}}
- // {{{ addRule()
-
- /**
- * Adds a validation rule for the given field
- *
- * If the element is in fact a group, it will be considered as a whole.
- * To validate grouped elements as separated entities,
- * use addGroupRule instead of addRule.
- *
- * @param string $element Form element name
- * @param string $message Message to display for invalid data
- * @param string $type Rule type, use getRegisteredRules() to get types
- * @param string $format (optional)Required for extra rule data
- * @param string $validation (optional)Where to perform validation: "server", "client"
- * @param boolean $reset Client-side validation: reset the form element to its original value if there is an error?
- * @param boolean $force Force the rule to be applied, even if the target form element does not exist
- * @since 1.0
- * @access public
- * @throws HTML_QuickForm_Error
- */
- function addRule($element, $message, $type, $format=null, $validation='server', $reset = false, $force = false)
- {
- if (!$force) {
- if (!is_array($element) && !$this->elementExists($element)) {
- return PEAR::raiseError(null, QUICKFORM_NONEXIST_ELEMENT, null, E_USER_WARNING, "Element '$element' does not exist in HTML_QuickForm::addRule()", 'HTML_QuickForm_Error', true);
- } elseif (is_array($element)) {
- foreach ($element as $el) {
- if (!$this->elementExists($el)) {
- return PEAR::raiseError(null, QUICKFORM_NONEXIST_ELEMENT, null, E_USER_WARNING, "Element '$el' does not exist in HTML_QuickForm::addRule()", 'HTML_QuickForm_Error', true);
- }
- }
- }
- }
- if (false === ($newName = $this->isRuleRegistered($type, true))) {
- return PEAR::raiseError(null, QUICKFORM_INVALID_RULE, null, E_USER_WARNING, "Rule '$type' is not registered in HTML_QuickForm::addRule()", 'HTML_QuickForm_Error', true);
- } elseif (is_string($newName)) {
- $type = $newName;
- }
- if (is_array($element)) {
- $dependent = $element;
- $element = array_shift($dependent);
- } else {
- $dependent = null;
- }
- if ($type == 'required' || $type == 'uploadedfile') {
- $this->_required[] = $element;
- }
- if (!isset($this->_rules[$element])) {
- $this->_rules[$element] = array();
- }
- if ($validation == 'client') {
- $this->updateAttributes(array('onsubmit'=>'return validate_'.$this->_attributes['id'] . '(this);'));
- }
- $this->_rules[$element][] = array(
- 'type' => $type,
- 'format' => $format,
- 'message' => $message,
- 'validation' => $validation,
- 'reset' => $reset,
- 'dependent' => $dependent
- );
- } // end func addRule
-
- // }}}
- // {{{ addGroupRule()
-
- /**
- * Adds a validation rule for the given group of elements
- *
- * Only groups with a name can be assigned a validation rule
- * Use addGroupRule when you need to validate elements inside the group.
- * Use addRule if you need to validate the group as a whole. In this case,
- * the same rule will be applied to all elements in the group.
- * Use addRule if you need to validate the group against a function.
- *
- * @param string $group Form group name
- * @param mixed $arg1 Array for multiple elements or error message string for one element
- * @param string $type (optional)Rule type use getRegisteredRules() to get types
- * @param string $format (optional)Required for extra rule data
- * @param int $howmany (optional)How many valid elements should be in the group
- * @param string $validation (optional)Where to perform validation: "server", "client"
- * @param bool $reset Client-side: whether to reset the element's value to its original state if validation failed.
- * @since 2.5
- * @access public
- * @throws HTML_QuickForm_Error
- */
- function addGroupRule($group, $arg1, $type='', $format=null, $howmany=0, $validation = 'server', $reset = false)
- {
- if (!$this->elementExists($group)) {
- return PEAR::raiseError(null, QUICKFORM_NONEXIST_ELEMENT, null, E_USER_WARNING, "Group '$group' does not exist in HTML_QuickForm::addGroupRule()", 'HTML_QuickForm_Error', true);
- }
-
- $groupObj =& $this->getElement($group);
- if (is_array($arg1)) {
- $required = 0;
- foreach ($arg1 as $elementIndex => $rules) {
- $elementName = $groupObj->getElementName($elementIndex);
- foreach ($rules as $rule) {
- $format = (isset($rule[2])) ? $rule[2] : null;
- $validation = (isset($rule[3]) && 'client' == $rule[3])? 'client': 'server';
- $reset = isset($rule[4]) && $rule[4];
- $type = $rule[1];
- if (false === ($newName = $this->isRuleRegistered($type, true))) {
- return PEAR::raiseError(null, QUICKFORM_INVALID_RULE, null, E_USER_WARNING, "Rule '$type' is not registered in HTML_QuickForm::addGroupRule()", 'HTML_QuickForm_Error', true);
- } elseif (is_string($newName)) {
- $type = $newName;
- }
-
- $this->_rules[$elementName][] = array(
- 'type' => $type,
- 'format' => $format,
- 'message' => $rule[0],
- 'validation' => $validation,
- 'reset' => $reset,
- 'group' => $group);
-
- if ('required' == $type || 'uploadedfile' == $type) {
- $groupObj->_required[] = $elementName;
- $this->_required[] = $elementName;
- $required++;
- }
- if ('client' == $validation) {
- $this->updateAttributes(array('onsubmit'=>'return validate_'.$this->_attributes['id'] . '(this);'));
- }
- }
- }
- if ($required > 0 && count($groupObj->getElements()) == $required) {
- $this->_required[] = $group;
- }
- } elseif (is_string($arg1)) {
- if (false === ($newName = $this->isRuleRegistered($type, true))) {
- return PEAR::raiseError(null, QUICKFORM_INVALID_RULE, null, E_USER_WARNING, "Rule '$type' is not registered in HTML_QuickForm::addGroupRule()", 'HTML_QuickForm_Error', true);
- } elseif (is_string($newName)) {
- $type = $newName;
- }
-
- // addGroupRule() should also handle <select multiple>
- if (is_a($groupObj, 'html_quickform_group')) {
- // Radios need to be handled differently when required
- if ($type == 'required' && $groupObj->getGroupType() == 'radio') {
- $howmany = ($howmany == 0) ? 1 : $howmany;
- } else {
- $howmany = ($howmany == 0) ? count($groupObj->getElements()) : $howmany;
- }
- }
-
- $this->_rules[$group][] = array('type' => $type,
- 'format' => $format,
- 'message' => $arg1,
- 'validation' => $validation,
- 'howmany' => $howmany,
- 'reset' => $reset);
- if ($type == 'required') {
- $this->_required[] = $group;
- }
- if ($validation == 'client') {
- $this->updateAttributes(array('onsubmit'=>'return validate_'.$this->_attributes['id'] . '(this);'));
- }
- }
- } // end func addGroupRule
-
- // }}}
- // {{{ addFormRule()
-
- /**
- * Adds a global validation rule
- *
- * This should be used when for a rule involving several fields or if
- * you want to use some completely custom validation for your form.
- * The rule function/method should return true in case of successful
- * validation and array('element name' => 'error') when there were errors.
- *
- * @access public
- * @param mixed Callback, either function name or array(&$object, 'method')
- * @throws HTML_QuickForm_Error
- */
- function addFormRule($rule)
- {
- if (!is_callable($rule)) {
- return PEAR::raiseError(null, QUICKFORM_INVALID_RULE, null, E_USER_WARNING, 'Callback function does not exist in HTML_QuickForm::addFormRule()', 'HTML_QuickForm_Error', true);
- }
- $this->_formRules[] = $rule;
- }
-
- // }}}
- // {{{ applyFilter()
-
- /**
- * Applies a data filter for the given field(s)
- *
- * @param mixed $element Form element name or array of such names
- * @param mixed $filter Callback, either function name or array(&$object, 'method')
- * @since 2.0
- * @access public
- */
- function applyFilter($element, $filter)
- {
- if (!is_callable($filter)) {
- return PEAR::raiseError(null, QUICKFORM_INVALID_FILTER, null, E_USER_WARNING, "Callback function does not exist in QuickForm::applyFilter()", 'HTML_QuickForm_Error', true);
- }
- if ($element == '__ALL__') {
- $this->_submitValues = $this->_recursiveFilter($filter, $this->_submitValues);
- } else {
- if (!is_array($element)) {
- $element = array($element);
- }
- foreach ($element as $elName) {
- $value = $this->getSubmitValue($elName);
- if (null !== $value) {
- if (false === strpos($elName, '[')) {
- $this->_submitValues[$elName] = $this->_recursiveFilter($filter, $value);
- } else {
- $idx = "['" . str_replace(array(']', '['), array('', "']['"), $elName) . "']";
- eval("\$this->_submitValues{$idx} = \$this->_recursiveFilter(\$filter, \$value);");
- }
- }
- }
- }
- } // end func applyFilter
-
- // }}}
- // {{{ _recursiveFilter()
-
- /**
- * Recursively apply a filter function
- *
- * @param string $filter filter to apply
- * @param mixed $value submitted values
- * @since 2.0
- * @access private
- * @return cleaned values
- */
- function _recursiveFilter($filter, $value)
- {
- if (is_array($value)) {
- $cleanValues = array();
- foreach ($value as $k => $v) {
- $cleanValues[$k] = $this->_recursiveFilter($filter, $value[$k]);
- }
- return $cleanValues;
- } else {
- return call_user_func($filter, $value);
- }
- } // end func _recursiveFilter
-
- // }}}
- // {{{ arrayMerge()
-
- /**
- * Merges two arrays
- *
- * Merges two array like the PHP function array_merge but recursively.
- * The main difference is that existing keys will not be renumbered
- * if they are integers.
- *
- * @access puplic
- * @param array $a original array
- * @param array $b array which will be merged into first one
- * @return array merged array
- */
- function arrayMerge($a, $b)
- {
- foreach ($b as $k => $v) {
- if (is_array($v)) {
- if (isset($a[$k]) && !is_array($a[$k])) {
- $a[$k] = $v;
- } else {
- if (!isset($a[$k])) {
- $a[$k] = array();
- }
- $a[$k] = HTML_QuickForm::arrayMerge($a[$k], $v);
- }
- } else {
- $a[$k] = $v;
- }
- }
- return $a;
- } // end func arrayMerge
-
- // }}}
- // {{{ isTypeRegistered()
-
- /**
- * Returns whether or not the form element type is supported
- *
- * @param string $type Form element type
- * @since 1.0
- * @access public
- * @return boolean
- */
- function isTypeRegistered($type)
- {
- return isset($GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'][$type]);
- } // end func isTypeRegistered
-
- // }}}
- // {{{ getRegisteredTypes()
-
- /**
- * Returns an array of registered element types
- *
- * @since 1.0
- * @access public
- * @return array
- */
- function getRegisteredTypes()
- {
- return array_keys($GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']);
- } // end func getRegisteredTypes
-
- // }}}
- // {{{ isRuleRegistered()
-
- /**
- * Returns whether or not the given rule is supported
- *
- * @param string $name Validation rule name
- * @param bool Whether to automatically register subclasses of HTML_QuickForm_Rule
- * @since 1.0
- * @access public
- * @return mixed true if previously registered, false if not, new rule name if auto-registering worked
- */
- function isRuleRegistered($name, $autoRegister = false)
- {
- if (is_scalar($name) && isset($GLOBALS['_HTML_QuickForm_registered_rules'][$name])) {
- return true;
- } elseif (!$autoRegister) {
- return false;
- }
- // automatically register the rule if requested
- include_once 'HTML/QuickForm/RuleRegistry.php';
- $ruleName = false;
- if (is_object($name) && is_a($name, 'html_quickform_rule')) {
- $ruleName = !empty($name->name)? $name->name: strtolower(get_class($name));
- } elseif (is_string($name) && class_exists($name)) {
- $parent = strtolower($name);
- do {
- if ('html_quickform_rule' == strtolower($parent)) {
- $ruleName = strtolower($name);
- break;
- }
- } while ($parent = get_parent_class($parent));
- }
- if ($ruleName) {
- $registry =& HTML_QuickForm_RuleRegistry::singleton();
- $registry->registerRule($ruleName, null, $name);
- }
- return $ruleName;
- } // end func isRuleRegistered
-
- // }}}
- // {{{ getRegisteredRules()
-
- /**
- * Returns an array of registered validation rules
- *
- * @since 1.0
- * @access public
- * @return array
- */
- function getRegisteredRules()
- {
- return array_keys($GLOBALS['_HTML_QuickForm_registered_rules']);
- } // end func getRegisteredRules
-
- // }}}
- // {{{ isElementRequired()
-
- /**
- * Returns whether or not the form element is required
- *
- * @param string $element Form element name
- * @since 1.0
- * @access public
- * @return boolean
- */
- function isElementRequired($element)
- {
- return in_array($element, $this->_required, true);
- } // end func isElementRequired
-
- // }}}
- // {{{ isElementFrozen()
-
- /**
- * Returns whether or not the form element is frozen
- *
- * @param string $element Form element name
- * @since 1.0
- * @access public
- * @return boolean
- */
- function isElementFrozen($element)
- {
- if (isset($this->_elementIndex[$element])) {
- return $this->_elements[$this->_elementIndex[$element]]->isFrozen();
- }
- return false;
- } // end func isElementFrozen
-
- // }}}
- // {{{ setJsWarnings()
-
- /**
- * Sets JavaScript warning messages
- *
- * @param string $pref Prefix warning
- * @param string $post Postfix warning
- * @since 1.1
- * @access public
- * @return void
- */
- function setJsWarnings($pref, $post)
- {
- $this->_jsPrefix = $pref;
- $this->_jsPostfix = $post;
- } // end func setJsWarnings
-
- // }}}
- // {{{ setRequiredNote()
-
- /**
- * Sets required-note
- *
- * @param string $note Message indicating some elements are required
- * @since 1.1
- * @access public
- * @return void
- */
- function setRequiredNote($note)
- {
- $this->_requiredNote = $note;
- } // end func setRequiredNote
-
- // }}}
- // {{{ getRequiredNote()
-
- /**
- * Returns the required note
- *
- * @since 2.0
- * @access public
- * @return string
- */
- function getRequiredNote()
- {
- return $this->_requiredNote;
- } // end func getRequiredNote
-
- // }}}
- // {{{ validate()
-
- /**
- * Performs the server side validation
- * @access public
- * @since 1.0
- * @return boolean true if no error found
- */
- function validate()
- {
- if (count($this->_rules) == 0 && count($this->_formRules) == 0 &&
- (count($this->_submitValues) > 0 || count($this->_submitFiles) > 0)) {
- return true;
- } elseif (count($this->_submitValues) == 0 && count($this->_submitFiles) == 0) {
- return false;
- }
-
- include_once('HTML/QuickForm/RuleRegistry.php');
- $registry =& HTML_QuickForm_RuleRegistry::singleton();
-
- foreach ($this->_rules as $target => $rules) {
- $submitValue = $this->getSubmitValue($target);
-
- foreach ($rules as $elementName => $rule) {
- if ((isset($rule['group']) && isset($this->_errors[$rule['group']])) ||
- isset($this->_errors[$target])) {
- continue 2;
- }
- if ((!isset($submitValue) || $submitValue == '') &&
- !$this->isElementRequired($target)) {
- // Element is not required
- continue 2;
- }
- if (isset($rule['dependent']) && is_array($rule['dependent'])) {
- $values = array($submitValue);
- foreach ($rule['dependent'] as $elName) {
- $values[] = $this->getSubmitValue($elName);
- }
- $result = $registry->validate($rule['type'], $values, $rule['format'], true);
- } elseif (is_array($submitValue) && !isset($rule['howmany'])) {
- $result = $registry->validate($rule['type'], $submitValue, $rule['format'], true);
- } else {
- $result = $registry->validate($rule['type'], $submitValue, $rule['format'], false);
- }
-
- if (!$result || (!empty($rule['howmany']) && $rule['howmany'] > (int)$result)) {
- if (isset($rule['group'])) {
- $this->_errors[$rule['group']] = $rule['message'];
- } else {
- $this->_errors[$target] = $rule['message'];
- }
- }
- }
- }
-
- // process the global rules now
- foreach ($this->_formRules as $rule) {
- if (true !== ($res = call_user_func($rule, $this->_submitValues, $this->_submitFiles))) {
- if (is_array($res)) {
- $this->_errors += $res;
- } else {
- return PEAR::raiseError(null, QUICKFORM_ERROR, null, E_USER_WARNING, 'Form rule callback returned invalid value in HTML_QuickForm::validate()', 'HTML_QuickForm_Error', true);
- }
- }
- }
-
- return (0 == count($this->_errors));
- } // end func validate
-
- // }}}
- // {{{ freeze()
-
- /**
- * Displays elements without HTML input tags
- *
- * @param mixed $elementList array or string of element(s) to be frozen
- * @since 1.0
- * @access public
- * @throws HTML_QuickForm_Error
- */
- function freeze($elementList=null)
- {
- if (!isset($elementList)) {
- $this->_freezeAll = true;
- $elementList = array();
- } else {
- if (!is_array($elementList)) {
- $elementList = preg_split('/[ ]*,[ ]*/', $elementList);
- }
- $elementList = array_flip($elementList);
- }
-
- foreach (array_keys($this->_elements) as $key) {
- $name = $this->_elements[$key]->getName();
- if ($this->_freezeAll || isset($elementList[$name])) {
- $this->_elements[$key]->freeze();
- unset($elementList[$name]);
- }
- }
-
- if (!empty($elementList)) {
- return PEAR::raiseError(null, QUICKFORM_NONEXIST_ELEMENT, null, E_USER_WARNING, "Nonexistant element(s): '" . implode("', '", array_keys($elementList)) . "' in HTML_QuickForm::freeze()", 'HTML_QuickForm_Error', true);
- }
- return true;
- } // end func freeze
-
- // }}}
- // {{{ isFrozen()
-
- /**
- * Returns whether or not the whole form is frozen
- *
- * @since 3.0
- * @access public
- * @return boolean
- */
- function isFrozen()
- {
- return $this->_freezeAll;
- } // end func isFrozen
-
- // }}}
- // {{{ process()
-
- /**
- * Performs the form data processing
- *
- * @param mixed $callback Callback, either function name or array(&$object, 'method')
- * @param bool $mergeFiles Whether uploaded files should be processed too
- * @since 1.0
- * @access public
- * @throws HTML_QuickForm_Error
- */
- function process($callback, $mergeFiles = true)
- {
- if (!is_callable($callback)) {
- return PEAR::raiseError(null, QUICKFORM_INVALID_PROCESS, null, E_USER_WARNING, "Callback function does not exist in QuickForm::process()", 'HTML_QuickForm_Error', true);
- }
- $values = ($mergeFiles === true) ? HTML_QuickForm::arrayMerge($this->_submitValues, $this->_submitFiles) : $this->_submitValues;
- return call_user_func($callback, $values);
- } // end func process
-
- // }}}
- // {{{ accept()
-
- /**
- * Accepts a renderer
- *
- * @param object An HTML_QuickForm_Renderer object
- * @since 3.0
- * @access public
- * @return void
- */
- function accept(&$renderer)
- {
- $renderer->startForm($this);
- foreach (array_keys($this->_elements) as $key) {
- $element =& $this->_elements[$key];
- $elementName = $element->getName();
- $required = ($this->isElementRequired($elementName) && !$element->isFrozen());
- $error = $this->getElementError($elementName);
- $element->accept($renderer, $required, $error);
- }
- $renderer->finishForm($this);
- } // end func accept
-
- // }}}
- // {{{ defaultRenderer()
-
- /**
- * Returns a reference to default renderer object
- *
- * @access public
- * @since 3.0
- * @return object a default renderer object
- */
- function &defaultRenderer()
- {
- if (!isset($GLOBALS['_HTML_QuickForm_default_renderer'])) {
- include_once('HTML/QuickForm/Renderer/Default.php');
- $GLOBALS['_HTML_QuickForm_default_renderer'] = new HTML_QuickForm_Renderer_Default();
- }
- return $GLOBALS['_HTML_QuickForm_default_renderer'];
- } // end func defaultRenderer
-
- // }}}
- // {{{ toHtml ()
-
- /**
- * Returns an HTML version of the form
- *
- * @param string $in_data (optional) Any extra data to insert right
- * before form is rendered. Useful when using templates.
- *
- * @return string Html version of the form
- * @since 1.0
- * @access public
- */
- function toHtml ($in_data = null)
- {
- if (!is_null($in_data)) {
- $this->addElement('html', $in_data);
- }
- $renderer =& $this->defaultRenderer();
- $this->accept($renderer);
- return $renderer->toHtml();
- } // end func toHtml
-
- // }}}
- // {{{ getValidationScript()
-
- /**
- * Returns the client side validation script
- *
- * @since 2.0
- * @access public
- * @return string Javascript to perform validation, empty string if no 'client' rules were added
- */
- function getValidationScript()
- {
- if (empty($this->_rules) || empty($this->_attributes['onsubmit'])) {
- return '';
- }
-
- include_once('HTML/QuickForm/RuleRegistry.php');
- $registry =& HTML_QuickForm_RuleRegistry::singleton();
- $test = array();
- $js_escape = array(
- "\r" => '\r',
- "\n" => '\n',
- "\t" => '\t',
- "'" => "\\'",
- '"' => '\"',
- '\\' => '\\\\'
- );
-
- foreach ($this->_rules as $elementName => $rules) {
- foreach ($rules as $rule) {
- if ('client' == $rule['validation']) {
- $dependent = isset($rule['dependent']) && is_array($rule['dependent']);
- $rule['message'] = strtr($rule['message'], $js_escape);
-
- if (isset($rule['group'])) {
- $group =& $this->getElement($rule['group']);
- // No JavaScript validation for frozen elements
- if ($group->isFrozen()) {
- continue 2;
- }
- $elements =& $group->getElements();
- foreach (array_keys($elements) as $key) {
- if ($elementName == $group->getElementName($key)) {
- $element =& $elements[$key];
- break;
- }
- }
- } elseif ($dependent) {
- $element = array();
- $element[] =& $this->getElement($elementName);
- foreach ($rule['dependent'] as $idx => $elName) {
- $element[] =& $this->getElement($elName);
- }
- } else {
- $element =& $this->getElement($elementName);
- }
- // No JavaScript validation for frozen elements
- if (is_object($element) && $element->isFrozen()) {
- continue 2;
- } elseif (is_array($element)) {
- foreach (array_keys($element) as $key) {
- if ($element[$key]->isFrozen()) {
- continue 3;
- }
- }
- }
-
- $test[] = $registry->getValidationScript($element, $elementName, $rule);
- unset($element);
- }
- }
- }
- if (count($test) > 0) {
- return
- "\n<script type=\"text/javascript\">\n" .
- "//<![CDATA[\n" .
- "function validate_" . $this->_attributes['id'] . "(frm) {\n" .
- " var value = '';\n" .
- " var errFlag = new Array();\n" .
- " _qfMsg = '';\n\n" .
- join("\n", $test) .
- "\n if (_qfMsg != '') {\n" .
- " _qfMsg = '" . strtr($this->_jsPrefix, $js_escape) . "' + _qfMsg;\n" .
- " _qfMsg = _qfMsg + '\\n" . strtr($this->_jsPostfix, $js_escape) . "';\n" .
- " alert(_qfMsg);\n" .
- " return false;\n" .
- " }\n" .
- " return true;\n" .
- "}\n" .
- "//]]>\n" .
- "</script>";
- }
- return '';
- } // end func getValidationScript
-
- // }}}
- // {{{ getSubmitValues()
-
- /**
- * Returns the values submitted by the form
- *
- * @since 2.0
- * @access public
- * @param bool Whether uploaded files should be returned too
- * @return array
- */
- function getSubmitValues($mergeFiles = false)
- {
- return $mergeFiles? HTML_QuickForm::arrayMerge($this->_submitValues, $this->_submitFiles): $this->_submitValues;
- } // end func getSubmitValues
-
- // }}}
- // {{{ toArray()
-
- /**
- * Returns the form's contents in an array.
- *
- * The description of the array structure is in HTML_QuickForm_Renderer_Array docs
- *
- * @since 2.0
- * @access public
- * @param bool Whether to collect hidden elements (passed to the Renderer's constructor)
- * @return array of form contents
- */
- function toArray($collectHidden = false)
- {
- include_once 'HTML/QuickForm/Renderer/Array.php';
- $renderer = new HTML_QuickForm_Renderer_Array($collectHidden);
- $this->accept($renderer);
- return $renderer->toArray();
- } // end func toArray
-
- // }}}
- // {{{ exportValue()
-
- /**
- * Returns a 'safe' element's value
- *
- * This method first tries to find a cleaned-up submitted value,
- * it will return a value set by setValue()/setDefaults()/setConstants()
- * if submitted value does not exist for the given element.
- *
- * @param string Name of an element
- * @access public
- * @return mixed
- */
- function exportValue($element)
- {
- if (!isset($this->_elementIndex[$element])) {
- return PEAR::raiseError(null, QUICKFORM_NONEXIST_ELEMENT, null, E_USER_WARNING, "Element '$element' does not exist in HTML_QuickForm::getElementValue()", 'HTML_QuickForm_Error', true);
- }
- $value = $this->_elements[$this->_elementIndex[$element]]->exportValue($this->_submitValues, false);
- if (isset($this->_duplicateIndex[$element])) {
- foreach ($this->_duplicateIndex[$element] as $index) {
- if (null !== ($v = $this->_elements[$index]->exportValue($this->_submitValues, false))) {
- if (is_array($value)) {
- $value[] = $v;
- } else {
- $value = (null === $value)? $v: array($value, $v);
- }
- }
- }
- }
- return $value;
- }
-
- // }}}
- // {{{ exportValues()
-
- /**
- * Returns 'safe' elements' values
- *
- * Unlike getSubmitValues(), this will return only the values
- * corresponding to the elements present in the form.
- *
- * @param mixed Array/string of element names, whose values we want. If not set then return all elements.
- * @access public
- * @return array An assoc array of elements' values
- * @throws HTML_QuickForm_Error
- */
- function exportValues($elementList = null)
- {
- $values = array();
- if (null === $elementList) {
- // iterate over all elements, calling their exportValue() methods
- foreach (array_keys($this->_elements) as $key) {
- $value = $this->_elements[$key]->exportValue($this->_submitValues, true);
- if (is_array($value)) {
- // This shit throws a bogus warning in PHP 4.3.x
- $values = HTML_QuickForm::arrayMerge($values, $value);
- }
- }
- } else {
- if (!is_array($elementList)) {
- $elementList = array_map('trim', explode(',', $elementList));
- }
- foreach ($elementList as $elementName) {
- $value = $this->exportValue($elementName);
- if (PEAR::isError($value)) {
- return $value;
- }
- $values[$elementName] = $value;
- }
- }
- return $values;
- }
-
- // }}}
- // {{{ isSubmitted()
- /**
- * Tells whether the form was already submitted
- *
- * This is useful since the _submitFiles and _submitValues arrays
- * may be completely empty after the trackSubmit value is removed.
- *
- * @access public
- * @return bool
- */
- function isSubmitted()
- {
- return $this->_flagSubmitted;
- }
-
- // }}}
- // {{{ isError()
-
- /**
- * Tell whether a result from a QuickForm method is an error (an instance of HTML_QuickForm_Error)
- *
- * @access public
- * @param mixed result code
- * @return bool whether $value is an error
- */
- function isError($value)
- {
- return (is_object($value) && is_a($value, 'html_quickform_error'));
- } // end func isError
-
- // }}}
- // {{{ errorMessage()
-
- /**
- * Return a textual error message for an QuickForm error code
- *
- * @access public
- * @param int error code
- * @return string error message
- */
- function errorMessage($value)
- {
- // make the variable static so that it only has to do the defining on the first call
- static $errorMessages;
-
- // define the varies error messages
- if (!isset($errorMessages)) {
- $errorMessages = array(
- QUICKFORM_OK => 'no error',
- QUICKFORM_ERROR => 'unknown error',
- QUICKFORM_INVALID_RULE => 'the rule does not exist as a registered rule',
- QUICKFORM_NONEXIST_ELEMENT => 'nonexistent html element',
- QUICKFORM_INVALID_FILTER => 'invalid filter',
- QUICKFORM_UNREGISTERED_ELEMENT => 'unregistered element',
- QUICKFORM_INVALID_ELEMENT_NAME => 'element already exists',
- QUICKFORM_INVALID_PROCESS => 'process callback does not exist',
- QUICKFORM_DEPRECATED => 'method is deprecated',
- QUICKFORM_INVALID_DATASOURCE => 'datasource is not an object'
- );
- }
-
- // If this is an error object, then grab the corresponding error code
- if (HTML_QuickForm::isError($value)) {
- $value = $value->getCode();
- }
-
- // return the textual error message corresponding to the code
- return isset($errorMessages[$value]) ? $errorMessages[$value] : $errorMessages[QUICKFORM_ERROR];
- } // end func errorMessage
-
- // }}}
-} // end class HTML_QuickForm
-
-class HTML_QuickForm_Error extends PEAR_Error {
-
- // {{{ properties
-
- /**
- * Prefix for all error messages
- * @var string
- */
- var $error_message_prefix = 'QuickForm Error: ';
-
- // }}}
- // {{{ constructor
-
- /**
- * Creates a quickform error object, extending the PEAR_Error class
- *
- * @param int $code the error code
- * @param int $mode the reaction to the error, either return, die or trigger/callback
- * @param int $level intensity of the error (PHP error code)
- * @param mixed $debuginfo any information that can inform user as to nature of the error
- */
- function HTML_QuickForm_Error($code = QUICKFORM_ERROR, $mode = PEAR_ERROR_RETURN,
- $level = E_USER_NOTICE, $debuginfo = null)
- {
- if (is_int($code)) {
- $this->PEAR_Error(HTML_QuickForm::errorMessage($code), $code, $mode, $level, $debuginfo);
- } else {
- $this->PEAR_Error("Invalid error code: $code", QUICKFORM_ERROR, $mode, $level, $debuginfo);
- }
- }
-
- // }}}
-} // end class HTML_QuickForm_Error
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * Class representing an action to perform on HTTP request.
- *
- * PHP versions 4 and 5
- *
- * LICENSE: This source file is subject to version 3.01 of the PHP license
- * that is available through the world-wide-web at the following URI:
- * http://www.php.net/license/3_01.txt If you did not receive a copy of
- * the PHP License and are unable to obtain it through the web, please
- * send a note to license@php.net so we can mail you a copy immediately.
- *
- * @category HTML
- * @package HTML_QuickForm_Controller
- * @author Alexey Borzov <avb@php.net>
- * @copyright 2003-2007 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version CVS: $Id: Action.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_QuickForm_Controller
- */
-
-/**
- * Class representing an action to perform on HTTP request.
- *
- * The Controller will select the appropriate Action to call on the request and
- * call its perform() method. The subclasses of this class should implement all
- * the necessary business logic.
- *
- * @category HTML
- * @package HTML_QuickForm_Controller
- * @author Alexey Borzov <avb@php.net>
- * @version Release: 1.0.8
- * @abstract
- */
-class HTML_QuickForm_Action
-{
- /**
- * Processes the request. This method should be overriden by child classes to
- * provide the necessary logic.
- *
- * @access public
- * @param HTML_QuickForm_Page The current form-page
- * @param string Current action name, as one Action object
- * can serve multiple actions
- * @throws PEAR_Error
- * @abstract
- */
- function perform(&$page, $actionName)
- {
- }
-}
-
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * The action for a 'back' button of wizard-type multipage form.
- *
- * PHP versions 4 and 5
- *
- * LICENSE: This source file is subject to version 3.01 of the PHP license
- * that is available through the world-wide-web at the following URI:
- * http://www.php.net/license/3_01.txt If you did not receive a copy of
- * the PHP License and are unable to obtain it through the web, please
- * send a note to license@php.net so we can mail you a copy immediately.
- *
- * @category HTML
- * @package HTML_QuickForm_Controller
- * @author Alexey Borzov <avb@php.net>
- * @copyright 2003-2007 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version CVS: $Id: Back.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_QuickForm_Controller
- */
-
-/**
- * Class representing an action to perform on HTTP request.
- */
-require_once 'HTML/QuickForm/Action.php';
-
-/**
- * The action for a 'back' button of wizard-type multipage form.
- *
- * @category HTML
- * @package HTML_QuickForm_Controller
- * @author Alexey Borzov <avb@php.net>
- * @version Release: 1.0.8
- */
-class HTML_QuickForm_Action_Back extends HTML_QuickForm_Action
-{
- function perform(&$page, $actionName)
- {
- // save the form values and validation status to the session
- $page->isFormBuilt() or $page->buildForm();
- $pageName = $page->getAttribute('id');
- $data =& $page->controller->container();
- $data['values'][$pageName] = $page->exportValues();
- if (!$page->controller->isModal()) {
- if (PEAR::isError($valid = $page->validate())) {
- return $valid;
- }
- $data['valid'][$pageName] = $valid;
- }
-
- // get the previous page and go to it
- // we don't check validation status here, 'jump' handler should
- if (null === ($prevName = $page->controller->getPrevName($pageName))) {
- return $page->handle('jump');
- } else {
- $prev =& $page->controller->getPage($prevName);
- return $prev->handle('jump');
- }
- }
-}
-
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * This action allows to go to a specific page of a multipage form.
- *
- * PHP versions 4 and 5
- *
- * LICENSE: This source file is subject to version 3.01 of the PHP license
- * that is available through the world-wide-web at the following URI:
- * http://www.php.net/license/3_01.txt If you did not receive a copy of
- * the PHP License and are unable to obtain it through the web, please
- * send a note to license@php.net so we can mail you a copy immediately.
- *
- * @category HTML
- * @package HTML_QuickForm_Controller
- * @author Alexey Borzov <avb@php.net>
- * @copyright 2003-2007 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version CVS: $Id: Direct.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_QuickForm_Controller
- */
-
-/**
- * Class representing an action to perform on HTTP request.
- */
-require_once 'HTML/QuickForm/Action.php';
-
-/**
- * This action allows to go to a specific page of a multipage form.
- *
- * Please note that the name for this action in addAction() should NOT be
- * 'direct', but the name of the page you wish to go to.
- *
- * @category HTML
- * @package HTML_QuickForm_Controller
- * @author Alexey Borzov <avb@php.net>
- * @version Release: 1.0.8
- */
-class HTML_QuickForm_Action_Direct extends HTML_QuickForm_Action
-{
- function perform(&$page, $actionName)
- {
- // save the form values and validation status to the session
- $page->isFormBuilt() or $page->buildForm();
- $pageName = $page->getAttribute('id');
- $data =& $page->controller->container();
- $data['values'][$pageName] = $page->exportValues();
- if (PEAR::isError($valid = $page->validate())) {
- return $valid;
- }
- $data['valid'][$pageName] = $valid;
-
- $target =& $page->controller->getPage($actionName);
- if (PEAR::isError($target)) {
- return $target;
- } else {
- return $target->handle('jump');
- }
- }
-}
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * This action handles output of the form.
- *
- * PHP versions 4 and 5
- *
- * LICENSE: This source file is subject to version 3.01 of the PHP license
- * that is available through the world-wide-web at the following URI:
- * http://www.php.net/license/3_01.txt If you did not receive a copy of
- * the PHP License and are unable to obtain it through the web, please
- * send a note to license@php.net so we can mail you a copy immediately.
- *
- * @category HTML
- * @package HTML_QuickForm_Controller
- * @author Alexey Borzov <avb@php.net>
- * @copyright 2003-2007 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version CVS: $Id: Display.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_QuickForm_Controller
- */
-
-/**
- * Class representing an action to perform on HTTP request.
- */
-require_once 'HTML/QuickForm/Action.php';
-
-/**
- * This action handles output of the form.
- *
- * If you want to customize the form display, subclass this class and
- * override the _renderForm() method, you don't need to change the perform()
- * method itself.
- *
- * @category HTML
- * @package HTML_QuickForm_Controller
- * @author Alexey Borzov <avb@php.net>
- * @version Release: 1.0.8
- */
-class HTML_QuickForm_Action_Display extends HTML_QuickForm_Action
-{
- function perform(&$page, $actionName)
- {
- $pageName = $page->getAttribute('id');
- // If the original action was 'display' and we have values in container then we load them
- // BTW, if the page was invalid, we should later call validate() to get the errors
- list(, $oldName) = $page->controller->getActionName();
- if ('display' == $oldName) {
- // If the controller is "modal" we should not allow direct access to a page
- // unless all previous pages are valid (see also bug #2323)
- if ($page->controller->isModal() && !$page->controller->isValid($page->getAttribute('id'))) {
- $target =& $page->controller->getPage($page->controller->findInvalid());
- return $target->handle('jump');
- }
- $data =& $page->controller->container();
- if (!empty($data['values'][$pageName])) {
- $page->loadValues($data['values'][$pageName]);
- $validate = false === $data['valid'][$pageName];
- }
- }
- // set "common" defaults and constants
- $page->controller->applyDefaults($pageName);
- $page->isFormBuilt() or $page->buildForm();
- // if we had errors we should show them again
- if (isset($validate) && $validate) {
- if (PEAR::isError($err = $page->validate())) {
- return $err;
- }
- }
- return $this->_renderForm($page);
- }
-
-
- /**
- * Actually outputs the form.
- *
- * If you want to customize the form's appearance (you most certainly will),
- * then you should override this method. There is no need to override perform()
- *
- * @access private
- * @param HTML_QuickForm_Page the page being processed
- */
- function _renderForm(&$page)
- {
- $page->display();
- }
-}
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * This action performs HTTP redirect to a specific page.
- *
- * PHP versions 4 and 5
- *
- * LICENSE: This source file is subject to version 3.01 of the PHP license
- * that is available through the world-wide-web at the following URI:
- * http://www.php.net/license/3_01.txt If you did not receive a copy of
- * the PHP License and are unable to obtain it through the web, please
- * send a note to license@php.net so we can mail you a copy immediately.
- *
- * @category HTML
- * @package HTML_QuickForm_Controller
- * @author Alexey Borzov <avb@php.net>
- * @copyright 2003-2007 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version CVS: $Id: Jump.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_QuickForm_Controller
- */
-
-/**
- * Class representing an action to perform on HTTP request.
- */
-require_once 'HTML/QuickForm/Action.php';
-
-/**
- * This action performs HTTP redirect to a specific page.
- *
- * @category HTML
- * @package HTML_QuickForm_Controller
- * @author Alexey Borzov <avb@php.net>
- * @version Release: 1.0.8
- */
-class HTML_QuickForm_Action_Jump extends HTML_QuickForm_Action
-{
- function perform(&$page, $actionName)
- {
- // check whether the page is valid before trying to go to it
- if ($page->controller->isModal()) {
- // we check whether *all* pages up to current are valid
- // if there is an invalid page we go to it, instead of the
- // requested one
- $pageName = $page->getAttribute('id');
- if (!$page->controller->isValid($pageName)) {
- $pageName = $page->controller->findInvalid();
- }
- $current =& $page->controller->getPage($pageName);
-
- } else {
- $current =& $page;
- }
- // generate the URL for the page 'display' event and redirect to it
- $action = $current->getAttribute('action');
- $url = $action . (false === strpos($action, '?')? '?': '&') .
- $current->getButtonName('display') . '=true' .
- ((!defined('SID') || '' == SID || ini_get('session.use_only_cookies'))? '': '&' . SID);
- header('Location: ' . $url);
- exit;
- }
-}
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * The action for a 'next' button of wizard-type multipage form.
- *
- * PHP versions 4 and 5
- *
- * LICENSE: This source file is subject to version 3.01 of the PHP license
- * that is available through the world-wide-web at the following URI:
- * http://www.php.net/license/3_01.txt If you did not receive a copy of
- * the PHP License and are unable to obtain it through the web, please
- * send a note to license@php.net so we can mail you a copy immediately.
- *
- * @category HTML
- * @package HTML_QuickForm_Controller
- * @author Alexey Borzov <avb@php.net>
- * @copyright 2003-2007 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version CVS: $Id: Next.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_QuickForm_Controller
- */
-
-/**
- * Class representing an action to perform on HTTP request.
- */
-require_once 'HTML/QuickForm/Action.php';
-
-/**
- * The action for a 'next' button of wizard-type multipage form.
- *
- * @category HTML
- * @package HTML_QuickForm_Controller
- * @author Alexey Borzov <avb@php.net>
- * @version Release: 1.0.8
- */
-class HTML_QuickForm_Action_Next extends HTML_QuickForm_Action
-{
- function perform(&$page, $actionName)
- {
-// echo 'here';
- // save the form values and validation status to the session
- $page->isFormBuilt() or $page->buildForm();
- $pageName = $page->getAttribute('id');
- $data =& $page->controller->container();
- $data['values'][$pageName] = $page->exportValues();
- if (PEAR::isError($valid = $page->validate())) {
- return $valid;
- }
- $data['valid'][$pageName] = $valid;
-
- // Modal form and page is invalid: don't go further
- if ($page->controller->isModal() && !$data['valid'][$pageName]) {
- return $page->handle('display');
- }
- // More pages?
- if (null !== ($nextName = $page->controller->getNextName($pageName))) {
- $next =& $page->controller->getPage($nextName);
- return $next->handle('jump');
- // Consider this a 'finish' button, if there is no explicit one
- } elseif($page->controller->isModal()) {
- if ($page->controller->isValid()) {
- return $page->handle('process');
- } else {
- // this should redirect to the first invalid page
- return $page->handle('jump');
- }
- } else {
- return $page->handle('display');
- }
- }
-}
-
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * The action for a 'submit' button.
- *
- * PHP versions 4 and 5
- *
- * LICENSE: This source file is subject to version 3.01 of the PHP license
- * that is available through the world-wide-web at the following URI:
- * http://www.php.net/license/3_01.txt If you did not receive a copy of
- * the PHP License and are unable to obtain it through the web, please
- * send a note to license@php.net so we can mail you a copy immediately.
- *
- * @category HTML
- * @package HTML_QuickForm_Controller
- * @author Alexey Borzov <avb@php.net>
- * @copyright 2003-2007 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version CVS: $Id: Submit.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_QuickForm_Controller
- */
-
-/**
- * Class representing an action to perform on HTTP request.
- */
-require_once 'HTML/QuickForm/Action.php';
-
-/**
- * The action for a 'submit' button.
- *
- * @category HTML
- * @package HTML_QuickForm_Controller
- * @author Alexey Borzov <avb@php.net>
- * @version Release: 1.0.8
- */
-class HTML_QuickForm_Action_Submit extends HTML_QuickForm_Action
-{
- function perform(&$page, $actionName)
- {
- // save the form values and validation status to the session
- $page->isFormBuilt() or $page->buildForm();
- $pageName = $page->getAttribute('id');
- $data =& $page->controller->container();
- $data['values'][$pageName] = $page->exportValues();
- if (PEAR::isError($valid = $page->validate())) {
- return $valid;
- }
- $data['valid'][$pageName] = $valid;
-
- // All pages are valid, process
- if ($page->controller->isValid()) {
- return $page->handle('process');
-
- // Current page is invalid, display it
- } elseif (!$data['valid'][$pageName]) {
- return $page->handle('display');
-
- // Some other page is invalid, redirect to it
- } else {
- $target =& $page->controller->getPage($page->controller->findInvalid());
- return $target->handle('jump');
- }
- }
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-
-/**
- * Common class for HTML_QuickForm elements to display a CAPTCHA
- *
- * The HTML_QuickForm_CAPTCHA package adds an element to the
- * HTML_QuickForm package to display a CAPTCHA question (image, riddle, etc...)
- *
- * This package requires the use of a PHP session.
- *
- * PHP versions 4 and 5
- *
- * @category HTML
- * @package HTML_QuickForm_CAPTCHA
- * @author Philippe Jausions <Philippe.Jausions@11abacus.com>
- * @copyright 2006 by 11abacus
- * @license LGPL
- * @version CVS: $Id: CAPTCHA.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_QuickForm_CAPTCHA
- */
-
-/**
- * Required packages
- */
-require_once 'HTML/QuickForm/input.php';
-require_once 'Text/CAPTCHA.php';
-
-/**
- * Common class for HTML_QuickForm elements to display a CAPTCHA
- *
- * The HTML_QuickForm_CAPTCHA package adds an element to the
- * HTML_QuickForm package to display a CAPTCHA question (image, riddle, etc...)
- *
- * This package requires the use of a PHP session.
- *
- * Because the CAPTCHA element is serialized in the PHP session,
- * you need to include the class declaration BEFORE the session starts.
- * So BEWARE if you have php.ini session.auto_start enabled, you won't be
- * able to use this element (unless you're also using PHP 5's __autoload()
- *
- * PHP versions 4 and 5
- *
- * @category HTML
- * @package HTML_QuickForm_CAPTCHA
- * @author Philippe Jausions <Philippe.Jausions@11abacus.com>
- * @copyright 2006 by 11abacus
- * @license LGPL
- * @version Release: 0.2.1
- * @link http://pear.php.net/package/HTML_QuickForm_CAPTCHA
- */
-class HTML_QuickForm_CAPTCHA extends HTML_QuickForm_input
-{
- /**
- * Default options
- *
- * @var array
- * @access protected
- */
- var $_options = array(
- 'sessionVar' => '_HTML_QuickForm_CAPTCHA',
- 'phrase' => null,
- );
-
- /**
- * CAPTCHA driver
- *
- * @var string
- * @access protected
- */
- var $_CAPTCHA_driver;
-
- /**
- * Class constructor
- *
- * @param string Name
- * @param mixed Label for the CAPTCHA
- * @param array Options for the Text_CAPTCHA package
- * <ul>
- * <li>'sessionVar' (string) name of session variable containing
- * the Text_CAPTCHA instance (defaults to
- * _HTML_QuickForm_CAPTCHA.)</li>
- * <li>Other options depend on the driver used</li>
- * </ul>
- * @param mixed HTML Attributes for the <a> tag surrounding the
- * image. Can be a string or array.
- * @access public
- */
- function HTML_QuickForm_CAPTCHA($elementName = null, $elementLabel = null,
- $options = null, $attributes = null)
- {
- HTML_QuickForm_input::HTML_QuickForm_input($elementName, $elementLabel,
- $attributes);
- $this->setType('CAPTCHA_'.$this->_CAPTCHA_driver);
-
- if (is_array($options)) {
- $this->_options = array_merge($this->_options, $options);
- }
- }
-
- /**
- * Initializes the CAPTCHA instance (if needed)
- *
- * @access protected
- * @return boolean TRUE or PEAR_Error on error
- */
- function _initCAPTCHA()
- {
- $sessionVar = $this->_options['sessionVar'];
-
- if (empty($_SESSION[$sessionVar])) {
- $_SESSION[$sessionVar] =& Text_CAPTCHA::factory($this->_CAPTCHA_driver);
- if (PEAR::isError($_SESSION[$sessionVar])) {
- return $_SESSION[$sessionVar];
- }
- $result = $_SESSION[$sessionVar]->init($this->_options);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
-
- return true;
- }
-
- /**
- * Returns the answer/phrase of the CAPTCHA
- *
- * @return string
- * @access private
- */
- function _findValue(&$values)
- {
- return $this->getValue();
- }
-
- /**
- * Returns the answer/phrase of the CAPTCHA
- *
- * @return string
- * @access public
- */
- function getValue()
- {
- $sessionVar = $this->_options['sessionVar'];
-
- return (!empty($_SESSION[$sessionVar]))
- ? $_SESSION[$sessionVar]->getPhrase()
- : null;
- }
-
- /**
- * Returns the answer/phrase of the CAPTCHA
- *
- * @return string
- * @access public
- */
- function exportValue(&$submitValues, $assoc = false)
- {
- return ($assoc)
- ? array($this->getName() => $this->getValue())
- : $this->getValue();
- }
-
- /**
- * Sets the CAPTCHA question/phrase
- *
- * Pass NULL or no argument for a random question/phrase to be generated
- *
- * @param string $phrase
- * @access public
- */
- function setPhrase($phrase = null)
- {
- $this->_options['phrase'] = $phrase;
-
- if (!empty($_SESSION[$this->_options['sessionVar']])) {
- $_SESSION[$this->_options['sessionVar']]->setPhrase($phrase);
- }
- }
-
- /**
- * Destroys the CAPTCHA instance to prevent reuse
- *
- * @access public
- */
- function destroy()
- {
- unset($_SESSION[$this->_options['sessionVar']]);
- }
-
- /**
- * Returns the HTML for the CAPTCHA
- *
- * This can be overwritten by sub-classes for specific output behavior
- * (for instance the Image CAPTCHA displays an image)
- *
- * @access public
- * @return string
- */
- function toHtml()
- {
- $result = $this->_initCAPTCHA();
- if (PEAR::isError($result)) {
- return $result;
- }
-
- $captcha = $_SESSION[$this->_options['sessionVar']]->getCAPTCHA();
-
- $attr = $this->_attributes;
- unset($attr['type']);
- unset($attr['value']);
- unset($attr['name']);
-
- $html = $this->_getTabs()
- . '<span' . $this->_getAttrString($attr) . '>'
- . htmlspecialchars($captcha)
- . '</span>';
- return $html;
- }
-}
-
-/**
- * Register the rule with QuickForm
- */
-require_once 'HTML/QuickForm/Rule/CAPTCHA.php';
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-
-/**
- * Element for HTML_QuickForm to display a CAPTCHA equation
- *
- * The HTML_QuickForm_CAPTCHA package adds an element to the
- * HTML_QuickForm package to display a CAPTCHA equation.
- *
- * This package requires the use of a PHP session.
- *
- * PHP versions 4 and 5
- *
- * @category HTML
- * @package HTML_QuickForm_CAPTCHA
- * @author Philippe Jausions <Philippe.Jausions@11abacus.com>
- * @copyright 2006 by 11abacus
- * @license LGPL
- * @version CVS: $Id: Equation.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_QuickForm_CAPTCHA
- */
-
-/**
- * Required packages
- */
-require_once 'HTML/QuickForm/CAPTCHA.php';
-require_once 'Text/CAPTCHA/Driver/Equation.php';
-
-/**
- * Element for HTML_QuickForm to display a CAPTCHA equation question
- *
- * The HTML_QuickForm_CAPTCHA package adds an element to the
- * HTML_QuickForm package to display a CAPTCHA equation question.
- *
- * Options for the element
- * <ul>
- * <li>'min' (integer) Minimal number to use in an equation.</li>
- * <li>'max' (integer) Maximal number to use in an equation.</li>
- * <li>'severity' (integer) Complexity of the equation to resolve
- * (1 = easy, 2 = harder)</li>
- * <li>'numbersToText' (boolean) Whether to use the Numbers_Words
- * package to convert numbers to text,</li>
- * <li>'sessionVar' (string) name of session variable containing
- * the Text_CAPTCHA instance (defaults to
- * _HTML_QuickForm_CAPTCHA.)</li>
- * </ul>
- *
- * This package requires the use of a PHP session.
- *
- * PHP versions 4 and 5
- *
- * @category HTML
- * @package HTML_QuickForm_CAPTCHA
- * @author Philippe Jausions <Philippe.Jausions@11abacus.com>
- * @copyright 2006 by 11abacus
- * @license LGPL
- * @version Release: 0.2.1
- * @link http://pear.php.net/package/HTML_QuickForm_CAPTCHA
- * @see Text_CAPTCHA_Driver_Equation
- */
-class HTML_QuickForm_CAPTCHA_Equation extends HTML_QuickForm_CAPTCHA
-{
- /**
- * Default options
- *
- * @var array
- * @access protected
- */
- var $_options = array(
- 'sessionVar' => '_HTML_QuickForm_CAPTCHA',
- 'severity' => 1,
- 'numbersToText' => false,
- 'phrase' => null,
- );
-
- /**
- * CAPTCHA driver
- *
- * @var string
- * @access protected
- */
- var $_CAPTCHA_driver = 'Equation';
-}
-
-/**
- * Register the class with QuickForm
- */
-if (class_exists('HTML_QuickForm')) {
- HTML_QuickForm::registerElementType('CAPTCHA_Equation',
- 'HTML/QuickForm/CAPTCHA/Equation.php',
- 'HTML_QuickForm_CAPTCHA_Equation');
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-
-/**
- * Element for HTML_QuickForm to display a CAPTCHA figlet
- *
- * The HTML_QuickForm_CAPTCHA package adds an element to the
- * HTML_QuickForm package to display a CAPTCHA figlet.
- *
- * This package requires the use of a PHP session.
- *
- * PHP versions 4 and 5
- *
- * @category HTML
- * @package HTML_QuickForm_CAPTCHA
- * @author Philippe Jausions <Philippe.Jausions@11abacus.com>
- * @copyright 2006 by 11abacus
- * @license LGPL
- * @version CVS: $Id: Figlet.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_QuickForm_CAPTCHA
- */
-
-/**
- * Required packages
- */
-require_once 'HTML/QuickForm/CAPTCHA.php';
-require_once 'Text/CAPTCHA/Driver/Figlet.php';
-
-/**
- * Element for HTML_QuickForm to display a CAPTCHA figlet
- *
- * The HTML_QuickForm_CAPTCHA package adds an element to the
- * HTML_QuickForm package to display a CAPTCHA figlet
- *
- * Options for the element
- * <ul>
- * <li>'width' (integer) Width of figlet (default is 200px)</li>
- * <li>'output' (string) Output format: "html", "text" or
- * "javascript" (default is "html").</li>
- * <li>'length' (integer) number of letters in the figlet
- * (default is 6)</li>
- * <li>'options' (array) only index supported is "font_file", which
- * should either be one figlet font file path,
- * or an array of figlet font file paths
- * (one we be picked randomly)</li>
- * <li>'sessionVar' (string) name of session variable containing
- * the Text_CAPTCHA instance (defaults to
- * _HTML_QuickForm_CAPTCHA.)</li>
- * </ul>
- *
- * This package requires the use of a PHP session.
- *
- * PHP versions 4 and 5
- *
- * @category HTML
- * @package HTML_QuickForm_CAPTCHA
- * @author Philippe Jausions <Philippe.Jausions@11abacus.com>
- * @copyright 2006 by 11abacus
- * @license LGPL
- * @version Release: 0.2.1
- * @link http://pear.php.net/package/HTML_QuickForm_CAPTCHA
- * @see Text_CAPTCHA_Driver_Equation
- */
-class HTML_QuickForm_CAPTCHA_Figlet extends HTML_QuickForm_CAPTCHA
-{
- /**
- * Default options
- *
- * @var array
- * @access protected
- */
- var $_options = array(
- 'sessionVar' => '_HTML_QuickForm_CAPTCHA',
- 'output' => 'html',
- 'width' => 200,
- 'length' => 6,
- 'phrase' => null,
- );
-
- /**
- * CAPTCHA driver
- *
- * @var string
- * @access protected
- */
- var $_CAPTCHA_driver = 'Figlet';
-
-
- /**
- * Returns the HTML for the CAPTCHA
- *
- * This can be overwritten by sub-classes for specific output behavior
- * (for instance the Image CAPTCHA displays an image)
- *
- * @access public
- * @return string
- */
- function toHtml()
- {
- $result = $this->_initCAPTCHA();
- if (PEAR::isError($result)) {
- return $result;
- }
-
- $attr = $this->_attributes;
- unset($attr['type']);
- unset($attr['value']);
- unset($attr['name']);
-
- $html = $this->_getTabs()
- . '<div' . $this->_getAttrString($attr) . '>'
- . $_SESSION[$this->_options['sessionVar']]->getCAPTCHA()
- . '</div>';
- return $html;
- }
-}
-
-/**
- * Register the class with QuickForm
- */
-if (class_exists('HTML_QuickForm')) {
- HTML_QuickForm::registerElementType('CAPTCHA_Figlet',
- 'HTML/QuickForm/CAPTCHA/Figlet.php',
- 'HTML_QuickForm_CAPTCHA_Figlet');
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-
-/**
- * Element for HTML_QuickForm to display a CAPTCHA image
- *
- * The HTML_QuickForm_CAPTCHA package adds an element to the
- * HTML_QuickForm package to display a CAPTCHA image.
- *
- * This package requires the use of a PHP session.
- *
- * PHP versions 4 and 5
- *
- * @category HTML
- * @package HTML_QuickForm_CAPTCHA
- * @author Philippe Jausions <Philippe.Jausions@11abacus.com>
- * @copyright 2006 by 11abacus
- * @license LGPL
- * @version CVS: $Id: Image.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_QuickForm_CAPTCHA
- */
-
-/**
- * Required packages
- */
-require_once 'HTML/QuickForm/CAPTCHA.php';
-require_once 'Text/CAPTCHA/Driver/Image.php';
-
-/**
- * Element for HTML_QuickForm to display a CAPTCHA image
- *
- * The HTML_QuickForm_CAPTCHA package adds an element to the
- * HTML_QuickForm package to display a CAPTCHA image.
- *
- * Options for the element
- * <ul>
- * <li>'width' (integer) width of the image,</li>
- * <li>'height' (integer) height of the image,</li>
- * <li>'imageOptions' (array) options passed to the Image_Text
- * constructor,</li>
- * <li>'callback' (string) URL of callback script that will generate
- * and output the image itself,</li>
- * <li>'alt' (string) the alt text for the image,</li>
- * <li>'sessionVar' (string) name of session variable containing
- * the Text_CAPTCHA instance (defaults to
- * _HTML_QuickForm_CAPTCHA.)</li>
- * </ul>
- *
- * This package requires the use of a PHP session.
- *
- * PHP versions 4 and 5
- *
- * @category HTML
- * @package HTML_QuickForm_CAPTCHA
- * @author Philippe Jausions <Philippe.Jausions@11abacus.com>
- * @copyright 2006 by 11abacus
- * @license LGPL
- * @version Release: 0.2.1
- * @link http://pear.php.net/package/HTML_QuickForm_CAPTCHA
- * @see Text_CAPTCHA_Driver_Image
- */
-class HTML_QuickForm_CAPTCHA_Image extends HTML_QuickForm_CAPTCHA
-{
- /**
- * Default options
- *
- * @var array
- * @access protected
- */
- var $_options = array(
- 'sessionVar' => '_HTML_QuickForm_CAPTCHA',
- 'width' => '200',
- 'height' => '80',
- 'alt' => 'Click to view another image',
- 'callback' => '',
- 'imageOptions' => null,
- 'phrase' => null,
- 'output' => 'jpeg',
- );
-
- /**
- * CAPTCHA driver
- *
- * @var string
- * @access protected
- */
- var $_CAPTCHA_driver = 'Image';
-
- /**
- * Returns the HTML for the CAPTCHA image
- *
- * @access public
- * @return string
- */
- function toHtml()
- {
- if ($this->_flagFrozen) {
- return '';
- }
-
- $result = parent::_initCAPTCHA();
- if (PEAR::isError($result)) {
- return $result;
- }
-
- $html = '';
- $tabs = $this->_getTabs();
- $inputName = $this->getName();
- $imgName = 'QF_CAPTCHA_' . $inputName;
-
- if ($this->getComment() != '') {
- $html .= $tabs . '<!-- ' . $this->getComment() . ' // -->';
- }
-
- $html = $tabs . '<a href="' . $this->_options['callback']
- . '" target="_blank" '
- . $this->_getAttrString($this->_attributes)
- . ' onclick="var cancelClick = false; '
- . $this->getOnclickJs($imgName)
- . ' return !cancelClick;"><img src="'
- . $this->_options['callback'] . '" name="' . $imgName
- . '" id="' . $imgName . '" width="' . $this->_options['width']
- . '" height="' . $this->_options['height'] . '" title="'
- . htmlspecialchars($this->_options['alt']) . '" /></a>';
-
- return $html;
- }
-
- /**
- * Create the javascript for the onclick event which will
- * reload a new CAPTCHA image
- *
- * @param string $imageName The image name/id
- *
- * @access public
- * @return string
- */
- function getOnclickJs($imageName)
- {
- $onclickJs = 'if (document.images) {var img = new Image(); var d = new Date(); img.src = this.href + ((this.href.indexOf(\'?\') == -1) ? \'?\' : \'&\') + d.getTime(); document.images[\'' . addslashes($imageName) . '\'].src = img.src; cancelClick = true;}';
- return $onclickJs;
- }
-}
-
-/**
- * Register the class with QuickForm
- */
-if (class_exists('HTML_QuickForm')) {
- HTML_QuickForm::registerElementType('CAPTCHA_Image',
- 'HTML/QuickForm/CAPTCHA/Image.php', 'HTML_QuickForm_CAPTCHA_Image');
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-
-/**
- * Element for HTML_QuickForm to display a CAPTCHA "Word"
- *
- * The HTML_QuickForm_CAPTCHA package adds an element to the
- * HTML_QuickForm package to display a CAPTCHA "word".
- *
- * This package requires the use of a PHP session.
- *
- * PHP versions 4 and 5
- *
- * @category HTML
- * @package HTML_QuickForm_CAPTCHA
- * @author Philippe Jausions <Philippe.Jausions@11abacus.com>
- * @copyright 2006 by 11abacus
- * @license LGPL
- * @version CVS: $Id: Word.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_QuickForm_CAPTCHA
- */
-
-/**
- * Required packages
- */
-require_once 'HTML/QuickForm/CAPTCHA.php';
-require_once 'Text/CAPTCHA/Driver/Word.php';
-
-/**
- * Element for HTML_QuickForm to display a CAPTCHA "word" question
- *
- * The HTML_QuickForm_CAPTCHA package adds an element to the
- * HTML_QuickForm package to display a CAPTCHA "word" question.
- *
- * Options for the element
- * <ul>
- * <li>'length' (integer) the length of the Word.</li>
- * <li>'mode' (string) 'single' for separated words.</li>
- * <li>'locale' (string) locale for Numbers_Words package</li>
- * <li>'sessionVar' (string) name of session variable containing
- * the Text_CAPTCHA instance (defaults to
- * _HTML_QuickForm_CAPTCHA.)</li>
- * </ul>
- *
- * This package requires the use of a PHP session.
- *
- * PHP versions 4 and 5
- *
- * @category HTML
- * @package HTML_QuickForm_CAPTCHA
- * @author Philippe Jausions <Philippe.Jausions@11abacus.com>
- * @copyright 2006 by 11abacus
- * @license LGPL
- * @version Release: 0.2.1
- * @link http://pear.php.net/package/HTML_QuickForm_CAPTCHA
- * @see Text_CAPTCHA_Driver_Equation
- */
-class HTML_QuickForm_CAPTCHA_Word extends HTML_QuickForm_CAPTCHA
-{
- /**
- * Default options
- *
- * @var array
- * @access protected
- */
- var $_options = array(
- 'sessionVar' => '_HTML_QuickForm_CAPTCHA',
- 'length' => 4,
- 'mode' => 'single',
- 'locale' => 'en_US',
- 'phrase' => null,
- );
-
- /**
- * CAPTCHA driver
- *
- * @var string
- * @access protected
- */
- var $_CAPTCHA_driver = 'Word';
-}
-
-/**
- * Register the class with QuickForm
- */
-if (class_exists('HTML_QuickForm')) {
- HTML_QuickForm::registerElementType('CAPTCHA_Word',
- 'HTML/QuickForm/CAPTCHA/Word.php', 'HTML_QuickForm_CAPTCHA_Word');
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * The class representing a Controller of MVC design pattern.
- *
- * PHP versions 4 and 5
- *
- * LICENSE: This source file is subject to version 3.01 of the PHP license
- * that is available through the world-wide-web at the following URI:
- * http://www.php.net/license/3_01.txt If you did not receive a copy of
- * the PHP License and are unable to obtain it through the web, please
- * send a note to license@php.net so we can mail you a copy immediately.
- *
- * @category HTML
- * @package HTML_QuickForm_Controller
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <bmansion@mamasam.com>
- * @copyright 2003-2007 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version CVS: $Id: Controller.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_QuickForm_Controller
- */
-
-/**
- * The class representing a page of a multipage form.
- */
-require_once 'HTML/QuickForm/Page.php';
-
-/**
- * The class representing a Controller of MVC design pattern.
- *
- * This class keeps track of pages and (default) action handlers for the form,
- * it manages keeping the form values in session, setting defaults and
- * constants for the form as a whole and getting its submit values.
- *
- * Generally you don't need to subclass this.
- *
- * @category HTML
- * @package HTML_QuickForm_Controller
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <bmansion@mamasam.com>
- * @version Release: 1.0.8
- */
-class HTML_QuickForm_Controller
-{
- /**
- * Contains the pages (HTML_QuickForm_Page objects) of the miultipage form
- * @var array
- */
- var $_pages = array();
-
- /**
- * Contains the mapping of actions to corresponding HTML_QuickForm_Action objects
- * @var array
- */
- var $_actions = array();
-
- /**
- * Name of the form, used to store the values in session
- * @var string
- */
- var $_name;
-
- /**
- * Whether the form is modal
- * @var bool
- */
- var $_modal = true;
-
- /**
- * The action extracted from HTTP request: array('page', 'action')
- * @var array
- */
- var $_actionName = null;
-
- /**
- * Class constructor.
- *
- * Sets the form name and modal/non-modal behaviuor. Different multipage
- * forms should have different names, as they are used to store form
- * values in session. Modal forms allow passing to the next page only when
- * all of the previous pages are valid.
- *
- * @access public
- * @param string form name
- * @param bool whether the form is modal
- */
- function HTML_QuickForm_Controller($name, $modal = true)
- {
- $this->_name = $name;
- $this->_modal = $modal;
- }
-
-
- /**
- * Returns a reference to a session variable containing the form-page
- * values and pages' validation status.
- *
- * This is a "low-level" method, use exportValues() if you want just to
- * get the form's values.
- *
- * @access public
- * @param bool If true, then reset the container: clear all default, constant and submitted values
- * @return array
- */
- function &container($reset = false)
- {
- $name = '_' . $this->_name . '_container';
- if (!isset($_SESSION[$name]) || $reset) {
- $_SESSION[$name] = array(
- 'defaults' => array(),
- 'constants' => array(),
- 'values' => array(),
- 'valid' => array()
- );
- }
- foreach (array_keys($this->_pages) as $pageName) {
- if (!isset($_SESSION[$name]['values'][$pageName])) {
- $_SESSION[$name]['values'][$pageName] = array();
- $_SESSION[$name]['valid'][$pageName] = null;
- }
- }
- return $_SESSION[$name];
- }
-
-
- /**
- * Processes the request.
- *
- * This finds the current page, the current action and passes the action
- * to the page's handle() method.
- *
- * @access public
- * @throws PEAR_Error
- */
- function run()
- {
- // the names of the action and page should be saved
- list($page, $action) = $this->_actionName = $this->getActionName();
- return $this->_pages[$page]->handle($action);
- }
-
-
- /**
- * Registers a handler for a specific action.
- *
- * @access public
- * @param string name of the action
- * @param HTML_QuickForm_Action the handler for the action
- */
- function addAction($actionName, &$action)
- {
- $this->_actions[$actionName] =& $action;
- }
-
-
- /**
- * Adds a new page to the form
- *
- * @access public
- * @param HTML_QuickForm_Page
- */
- function addPage(&$page)
- {
- $page->controller =& $this;
- $this->_pages[$page->getAttribute('id')] =& $page;
- }
-
-
- /**
- * Returns a page
- *
- * @access public
- * @param string Name of a page
- * @return HTML_QuickForm_Page A reference to the page
- * @throws PEAR_Error
- */
- function &getPage($pageName)
- {
- if (!isset($this->_pages[$pageName])) {
- return PEAR::raiseError('HTML_QuickForm_Controller: Unknown page "' . $pageName . '"');
- }
- return $this->_pages[$pageName];
- }
-
-
- /**
- * Handles an action.
- *
- * This will be called if the page itself does not have a handler
- * to a specific action. The method also loads and uses default handlers
- * for common actions, if specific ones were not added.
- *
- * @access public
- * @param HTML_QuickForm_Page The page that failed to handle the action
- * @param string Name of the action
- * @throws PEAR_Error
- */
- function handle(&$page, $actionName)
- {
- if (isset($this->_actions[$actionName])) {
- return $this->_actions[$actionName]->perform($page, $actionName);
- }
- switch ($actionName) {
- case 'next':
- case 'back':
- case 'submit':
- case 'display':
- case 'jump':
- include_once 'HTML/QuickForm/Action/' . ucfirst($actionName) . '.php';
- $className = 'HTML_QuickForm_Action_' . $actionName;
- $this->_actions[$actionName] = new $className();
- return $this->_actions[$actionName]->perform($page, $actionName);
- break;
- default:
- return PEAR::raiseError('HTML_QuickForm_Controller: Unhandled action "' . $actionName . '" in page "' . $page->getAttribute('id') . '"');
- } // switch
- }
-
-
- /**
- * Checks whether the form is modal.
- *
- * @access public
- * @return bool
- */
- function isModal()
- {
- return $this->_modal;
- }
-
-
- /**
- * Checks whether the pages of the controller are valid
- *
- * @access public
- * @param string If set, check only the pages before (not including) that page
- * @return bool
- * @throws PEAR_Error
- */
- function isValid($pageName = null)
- {
- $data =& $this->container();
- foreach (array_keys($this->_pages) as $key) {
- if (isset($pageName) && $pageName == $key) {
- return true;
- } elseif (!$data['valid'][$key]) {
- // We should handle the possible situation when the user has never
- // seen a page of a non-modal multipage form
- if (!$this->isModal() && null === $data['valid'][$key]) {
- $page =& $this->_pages[$key];
- // Fix for bug #8687: the unseen page was considered
- // submitted, so defaults for checkboxes and multiselects
- // were not used. Shouldn't break anything since this flag
- // will be reset right below in loadValues().
- $page->_flagSubmitted = false;
- // Use controller's defaults and constants, if present
- $this->applyDefaults($key);
- $page->isFormBuilt() or $page->BuildForm();
- // We use defaults and constants as if they were submitted
- $data['values'][$key] = $page->exportValues();
- $page->loadValues($data['values'][$key]);
- // Is the page now valid?
- if (PEAR::isError($valid = $page->validate())) {
- return $valid;
- }
- $data['valid'][$key] = $valid;
- if (true === $valid) {
- continue;
- }
- }
- return false;
- }
- }
- return true;
- }
-
-
- /**
- * Returns the name of the page before the given.
- *
- * @access public
- * @param string
- * @return string
- */
- function getPrevName($pageName)
- {
- $prev = null;
- foreach (array_keys($this->_pages) as $key) {
- if ($key == $pageName) {
- return $prev;
- }
- $prev = $key;
- }
- }
-
-
- /**
- * Returns the name of the page after the given.
- *
- * @access public
- * @param string
- * @return string
- */
- function getNextName($pageName)
- {
- $prev = null;
- foreach (array_keys($this->_pages) as $key) {
- if ($prev == $pageName) {
- return $key;
- }
- $prev = $key;
- }
- return null;
- }
-
-
- /**
- * Finds the (first) invalid page
- *
- * @access public
- * @return string Name of an invalid page
- */
- function findInvalid()
- {
- $data =& $this->container();
- foreach (array_keys($this->_pages) as $key) {
- if (!$data['valid'][$key]) {
- return $key;
- }
- }
- return null;
- }
-
-
- /**
- * Extracts the names of the current page and the current action from
- * HTTP request data.
- *
- * @access public
- * @return array first element is page name, second is action name
- */
- function getActionName()
- {
- if (is_array($this->_actionName)) {
- return $this->_actionName;
- }
- $names = array_map('preg_quote', array_keys($this->_pages));
- $regex = '/^_qf_(' . implode('|', $names) . ')_(.+?)(_x)?$/';
- foreach (array_keys($_REQUEST) as $key) {
- if (preg_match($regex, $key, $matches)) {
- return array($matches[1], $matches[2]);
- }
- }
- if (isset($_REQUEST['_qf_default'])) {
- $matches = explode(':', $_REQUEST['_qf_default'], 2);
- if (isset($this->_pages[$matches[0]])) {
- return $matches;
- }
- }
- reset($this->_pages);
- return array(key($this->_pages), 'display');
- }
-
-
- /**
- * Initializes default form values.
- *
- * @access public
- * @param array default values
- * @param mixed filter(s) to apply to default values
- * @throws PEAR_Error
- */
- function setDefaults($defaultValues = null, $filter = null)
- {
- if (is_array($defaultValues)) {
- $data =& $this->container();
- return $this->_setDefaultsOrConstants($data['defaults'], $defaultValues, $filter);
- }
- }
-
-
- /**
- * Initializes constant form values.
- * These values won't get overridden by POST or GET vars
- *
- * @access public
- * @param array constant values
- * @param mixed filter(s) to apply to constant values
- * @throws PEAR_Error
- */
- function setConstants($constantValues = null, $filter = null)
- {
- if (is_array($constantValues)) {
- $data =& $this->container();
- return $this->_setDefaultsOrConstants($data['constants'], $constantValues, $filter);
- }
- }
-
-
- /**
- * Adds new values to defaults or constants array
- *
- * @access private
- * @param array array to add values to (either defaults or constants)
- * @param array values to add
- * @param mixed filters to apply to new values
- * @throws PEAR_Error
- */
- function _setDefaultsOrConstants(&$values, $newValues, $filter = null)
- {
- if (isset($filter)) {
- if (is_array($filter) && (2 != count($filter) || !is_callable($filter))) {
- foreach ($filter as $val) {
- if (!is_callable($val)) {
- return PEAR::raiseError(null, QUICKFORM_INVALID_FILTER, null, E_USER_WARNING, "Callback function does not exist in QuickForm_Controller::_setDefaultsOrConstants()", 'HTML_QuickForm_Error', true);
- } else {
- $newValues = $this->_arrayMapRecursive($val, $newValues);
- }
- }
- } elseif (!is_callable($filter)) {
- return PEAR::raiseError(null, QUICKFORM_INVALID_FILTER, null, E_USER_WARNING, "Callback function does not exist in QuickForm_Controller::_setDefaultsOrConstants()", 'HTML_QuickForm_Error', true);
- } else {
- $newValues = $this->_arrayMapRecursive($val, $newValues);
- }
- }
- $values = HTML_QuickForm::arrayMerge($values, $newValues);
- }
-
-
- /**
- * Recursively applies the callback function to the value
- *
- * @param mixed Callback function
- * @param mixed Value to process
- * @access private
- * @return mixed Processed values
- */
- function _arrayMapRecursive($callback, $value)
- {
- if (!is_array($value)) {
- return call_user_func($callback, $value);
- } else {
- $map = array();
- foreach ($value as $k => $v) {
- $map[$k] = $this->_arrayMapRecursive($callback, $v);
- }
- return $map;
- }
- }
-
-
- /**
- * Sets the default values for the given page
- *
- * @access public
- * @param string Name of a page
- */
- function applyDefaults($pageName)
- {
- $data =& $this->container();
- if (!empty($data['defaults'])) {
- $this->_pages[$pageName]->setDefaults($data['defaults']);
- }
- if (!empty($data['constants'])) {
- $this->_pages[$pageName]->setConstants($data['constants']);
- }
- }
-
-
- /**
- * Returns the form's values
- *
- * @access public
- * @param string name of the page, if not set then returns values for all pages
- * @return array
- */
- function exportValues($pageName = null)
- {
- $data =& $this->container();
- $values = array();
- if (isset($pageName)) {
- $pages = array($pageName);
- } else {
- $pages = array_keys($data['values']);
- }
- foreach ($pages as $page) {
- // skip elements representing actions
- foreach ($data['values'][$page] as $key => $value) {
- if (0 !== strpos($key, '_qf_')) {
- if (isset($values[$key]) && is_array($value)) {
- $values[$key] = HTML_QuickForm::arrayMerge($values[$key], $value);
- } else {
- $values[$key] = $value;
- }
- }
- }
- }
- return $values;
- }
-
-
- /**
- * Returns the element's value
- *
- * @access public
- * @param string name of the page
- * @param string name of the element in the page
- * @return mixed value for the element
- */
- function exportValue($pageName, $elementName)
- {
- $data =& $this->container();
- return isset($data['values'][$pageName][$elementName])? $data['values'][$pageName][$elementName]: null;
- }
-}
-?>
+++ /dev/null
-<?php
-/**
- * This is a new element type for HTML_QuickForm which defines a grid of QuickForm elements
- *
- * PHP Versions 4 and 5
- *
- * @category HTML
- * @package HTML_QuickForm_ElementGrid
- * @license http://www.gnu.org/copyleft/lesser.html LGPL
- * @author Justin Patrin <papercrane@reversefold.com>
- * @version $Id: ElementGrid.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- */
-
-require_once 'HTML/QuickForm/element.php';
-
-/**
- * An HTML_QuickForm element which holds any number of other elements in a grid.
- * Used in DB_DataObject_FormBuilder for tripleLinks and crossLinks when there are
- * crossLinkExtraFields. This element type makes these grids of elements behave the
- * same as normal elements in the form. i.e. they will freeze correctly and get
- * values (defaults) set correctly.
- */
-class HTML_QuickForm_ElementGrid extends HTML_QuickForm_element {
-
- /**
- * Array of arrays of HTML_QuickForm elements
- *
- * @var array
- */
- var $_rows = array();
-
- /**
- * Array of column names (strings)
- *
- * @var array
- */
- var $_columnNames = array();
-
- /**
- * Array of row names (strings)
- *
- * @var array
- */
- var $_rowNames = array();
-
- /**
- * Holds this element's name
- *
- * @var string
- */
- var $_name;
-
- /**
- * Holds a reference to the form for use when adding elements
- *
- * @var HTML_QuickForm
- */
- var $_form;
-
- /**
- * Holds options
- *
- * @var array
- */
- var $_options = array('actAsGroup' => false);
-
- /**
- * Constructor
- *
- * @param string name for the element
- * @param string label for the element
- */
- function HTML_QuickForm_ElementGrid($name = null, $label = null/*, $columnNames = null,
- $rowNames = null, $rows = null, $attributes = null*/,
- $options = null)
- {
- parent::HTML_QuickForm_element($name, $label);
- $this->updateAttributes(array('class' => 'elementGrid'));
- //$this->setRows($rows);
- //$this->setColumnNames($columnNames);
- //$this->setRowNames($rowNames);
- if (is_array($options)) {
- $this->_options = array_merge($this->_options, $options);
- }
- }
-
- /**
- * Sets this element's name
- *
- * @param string name
- */
- function setName($name)
- {
- $this->_name = $name;
- }
-
- /**
- * Gets this element's name
- *
- * @return string name
- */
- function getName()
- {
- return $this->_name;
- }
-
- /**
- * Sets the column names
- *
- * @param array array of column names (strings)
- */
- function setColumnNames($columnNames)
- {
- $this->_columnNames = $columnNames;
- }
-
- /**
- * Adds a column name
- *
- * @param string name of the column
- */
- function addColumnName($columnName)
- {
- $this->_columnNames[] = $columnName;
- }
-
- /**
- * Set the row names
- *
- * @param array array of row names (strings)
- */
- function setRowNames($rowNames)
- {
- $this->_rowNames = $rowNames;
- }
-
- /**
- * Sets the rows
- *
- * @param array array of HTML_QuickForm elements
- */
- function setRows(&$rows)
- {
- foreach (array_keys($rows) as $key) {
- $this->addRow($rows[$key]);
- }
- }
-
- /**
- * Adds a row to the grid
- *
- * @param array array of HTML_QuickForm elements
- * @param string name of the row
- */
- function addRow(&$row, $rowName = null)
- {
- $key = sizeof($this->_rows);
- $this->_rows[$key] =& $row;
-
- //if updateValue has been called make sure to update the values of each added element
- foreach (array_keys($this->_rows[$key]) as $key2) {
- if (isset($this->_form)) {
- $this->_rows[$key][$key2]->onQuickFormEvent('updateValue', null, $this->_form);
- }
- if ($this->isFrozen()) {
- $this->_rows[$key][$key2]->freeze();
- }
- }
- if ($rowName !== null) {
- $this->addRowName($rowName);
- }
- }
-
- /**
- * Adds a row name
- *
- * @param string name of the row
- */
- function addRowName($rowName)
- {
- $this->_rowNames[] = $rowName;
- }
-
- /**
- * Freezes all elements in the grid
- */
- function freeze()
- {
- parent::freeze();
- foreach (array_keys($this->_rows) as $key) {
- foreach (array_keys($this->_rows[$key]) as $key2) {
- $this->_rows[$key][$key2]->freeze();
- }
- }
- }
-
- /**
- * Returns Html for the element
- *
- * @access public
- * @return string
- */
- function toHtml()
- {
- require_once 'HTML/Table.php';
- $table = new HTML_Table(null, 0, true);
- $table->updateAttributes($this->getAttributes());
-
- $tbody =& $table->getBody();
- $tbody->setAutoGrow(true);
- $tbody->setAutoFill('');
-
- $thead =& $table->getHeader();
- $thead->setAutoGrow(true);
- $thead->setAutoFill('');
-
- $col = 0;
- if ($this->_columnNames) {
- foreach ($this->_columnNames as $key => $value) {
- ++$col;
- $thead->setHeaderContents(0, $col, $value);
- }
- $thead->updateRowAttributes(0, array('class' => 'elementGridColumnLabel'), true);
- }
-
- $row = 0;
- foreach (array_keys($this->_rows) as $key) {
- $col = 0;
- $tbody->setHeaderContents($row, $col, isset($this->_rowNames[$key]) ? $this->_rowNames[$key] : '');
- foreach (array_keys($this->_rows[$key]) as $key2) {
- ++$col;
- $tbody->setCellContents($row, $col, $this->_rows[$key][$key2]->toHTML());
- }
- ++$row;
- }
-
- $tbody->updateColAttributes(0, array('class' => 'elementGridRowLabel'));
- return $table->toHTML();
-
- /*include_once('HTML/QuickForm/Renderer/Default.php');
- $renderer =& new HTML_QuickForm_Renderer_Default();
- $renderer->setElementTemplate('{element}');
- $this->accept($renderer);
- return $renderer->toHtml();*/
- }
-
- /**
- * Called by HTML_QuickForm whenever form event is made on this element
- *
- * @param string Name of event
- * @param mixed event arguments
- * @param object calling object
- * @access public
- * @return bool true
- */
- function onQuickFormEvent($event, $arg, &$caller)
- {
- switch ($event) {
- case 'updateValue':
- //store form for use in addRow
- $this->_form =& $caller;
-
- foreach (array_keys($this->_rows) as $key) {
- foreach (array_keys($this->_rows[$key]) as $key2) {
- $this->_rows[$key][$key2]->onQuickFormEvent('updateValue', null, $caller);
- }
- }
- break;
-
- default:
- parent::onQuickFormEvent($event, $arg, $caller);
- break;
- }
- return true;
- }
-
- /**
- * Returns a 'safe' element's value
- *
- * @param array array of submitted values to search
- * @param bool whether to return the value as associative array
- * @access public
- * @return mixed
- */
- function exportValue(&$submitValues, $assoc)
- {
- if ($this->_options['actAsGroup']) {
- return parent::exportValue($submitValues, $assoc);
- }
-
- if ($assoc) {
- $values = array();
- foreach (array_keys($this->_rows) as $key) {
- foreach (array_keys($this->_rows[$key]) as $key2) {
- $value = $this->_rows[$key][$key2]->exportValue($submitValues, true);
- if (is_array($value)) {
- $values = HTML_QuickForm::arrayMerge($values, $value);
- } else {
- $values[$this->_rows[$key][$key2]->getName()] = $value;
- }
- }
- }
- return $values;
- } else {
- return null;
- }
- }
-
- /**
- * Returns the value of the form element
- *
- * @since 1.0
- * @access public
- * @return mixed
- */
- function getValue()
- {
- $values = array();
- foreach (array_keys($this->_rows) as $key) {
- foreach (array_keys($this->_rows[$key]) as $key2) {
- $values[$this->_rows[$key][$key2]->getName()] = $this->_rows[$key][$key2]->getValue();
- }
- }
- return $values;
- }
-}
-
-require_once 'HTML/QuickForm.php';
-HTML_QuickForm::registerElementType('elementGrid', __FILE__, 'HTML_QuickForm_ElementGrid');
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * Class representing a page of a multipage form.
- *
- * PHP versions 4 and 5
- *
- * LICENSE: This source file is subject to version 3.01 of the PHP license
- * that is available through the world-wide-web at the following URI:
- * http://www.php.net/license/3_01.txt If you did not receive a copy of
- * the PHP License and are unable to obtain it through the web, please
- * send a note to license@php.net so we can mail you a copy immediately.
- *
- * @category HTML
- * @package HTML_QuickForm_Controller
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <bmansion@mamasam.com>
- * @copyright 2003-2007 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version CVS: $Id: Page.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_QuickForm_Controller
- */
-
-/**
- * Create, validate and process HTML forms
- */
-require_once 'HTML/QuickForm.php';
-
-/**
- * Class representing a page of a multipage form.
- *
- * Generally you'll need to subclass this and define your buildForm()
- * method that will build the form. While it is also possible to instantiate
- * this class and build the form manually, this is not the recommended way.
- *
- * @category HTML
- * @package HTML_QuickForm_Controller
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <bmansion@mamasam.com>
- * @version Release: 1.0.8
- */
-class HTML_QuickForm_Page extends HTML_QuickForm
-{
- /**
- * Contains the mapping of actions to corresponding HTML_QuickForm_Action objects
- * @var array
- */
- var $_actions = array();
-
- /**
- * Contains a reference to a Controller object containing this page
- * @var HTML_QuickForm_Controller
- * @access public
- */
- var $controller = null;
-
- /**
- * Should be set to true on first call to buildForm()
- * @var bool
- */
- var $_formBuilt = false;
-
- /**
- * Class constructor
- *
- * @access public
- */
- function HTML_QuickForm_Page($formName, $method = 'post', $target = '', $attributes = null)
- {
- $this->HTML_QuickForm($formName, $method, $target, $attributes);
- }
-
-
- /**
- * Registers a handler for a specific action.
- *
- * @access public
- * @param string name of the action
- * @param HTML_QuickForm_Action the handler for the action
- */
- function addAction($actionName, &$action)
- {
- $this->_actions[$actionName] =& $action;
- }
-
-
- /**
- * Handles an action.
- *
- * If an Action object was not registered here, controller's handle()
- * method will be called.
- *
- * @access public
- * @param string Name of the action
- * @throws PEAR_Error
- */
- function handle($actionName)
- {
- if (isset($this->_actions[$actionName])) {
- return $this->_actions[$actionName]->perform($this, $actionName);
- } else {
- return $this->controller->handle($this, $actionName);
- }
- }
-
-
- /**
- * Returns a name for a submit button that will invoke a specific action.
- *
- * @access public
- * @param string Name of the action
- * @return string "name" attribute for a submit button
- */
- function getButtonName($actionName)
- {
- return '_qf_' . $this->getAttribute('id') . '_' . $actionName;
- }
-
-
- /**
- * Loads the submit values from the array.
- *
- * The method is NOT intended for general usage.
- *
- * @param array 'submit' values
- * @access public
- */
- function loadValues($values)
- {
- $this->_flagSubmitted = true;
- $this->_submitValues = $values;
- foreach (array_keys($this->_elements) as $key) {
- $this->_elements[$key]->onQuickFormEvent('updateValue', null, $this);
- }
- }
-
-
- /**
- * Builds a form.
- *
- * You should override this method when you subclass HTML_QuickForm_Page,
- * it should contain all the necessary addElement(), applyFilter(), addRule()
- * and possibly setDefaults() and setConstants() calls. The method will be
- * called on demand, so please be sure to set $_formBuilt property to true to
- * assure that the method works only once.
- *
- * @access public
- * @abstract
- */
- function buildForm()
- {
- $this->_formBuilt = true;
- }
-
-
- /**
- * Checks whether the form was already built.
- *
- * @access public
- * @return bool
- */
- function isFormBuilt()
- {
- return $this->_formBuilt;
- }
-
-
- /**
- * Sets the default action invoked on page-form submit
- *
- * This is necessary as the user may just press Enter instead of
- * clicking one of the named submit buttons and then no action name will
- * be passed to the script.
- *
- * @access public
- * @param string default action name
- */
- function setDefaultAction($actionName)
- {
- if ($this->elementExists('_qf_default')) {
- $element =& $this->getElement('_qf_default');
- $element->setValue($this->getAttribute('id') . ':' . $actionName);
- } else {
- $this->addElement('hidden', '_qf_default', $this->getAttribute('id') . ':' . $actionName);
- }
- }
-
-
- /**
- * Returns 'safe' elements' values
- *
- * @param mixed Array/string of element names, whose values we want. If not set then return all elements.
- * @param bool Whether to remove internal (_qf_...) values from the resultant array
- */
- function exportValues($elementList = null, $filterInternal = false)
- {
- $values = parent::exportValues($elementList);
- if ($filterInternal) {
- foreach (array_keys($values) as $key) {
- if (0 === strpos($key, '_qf_')) {
- unset($values[$key]);
- }
- }
- }
- return $values;
- }
-}
-
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP version 4.0 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Alexey Borzov <borz_off@cs.msu.su> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Renderer.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-/**
- * An abstract base class for QuickForm renderers
- *
- * The class implements a Visitor design pattern
- *
- * @abstract
- * @author Alexey Borzov <borz_off@cs.msu.su>
- */
-class HTML_QuickForm_Renderer
-{
- /**
- * Constructor
- *
- * @access public
- */
- function HTML_QuickForm_Renderer()
- {
- } // end constructor
-
- /**
- * Called when visiting a form, before processing any form elements
- *
- * @param object An HTML_QuickForm object being visited
- * @access public
- * @return void
- * @abstract
- */
- function startForm(&$form)
- {
- return;
- } // end func startForm
-
- /**
- * Called when visiting a form, after processing all form elements
- *
- * @param object An HTML_QuickForm object being visited
- * @access public
- * @return void
- * @abstract
- */
- function finishForm(&$form)
- {
- return;
- } // end func finishForm
-
- /**
- * Called when visiting a header element
- *
- * @param object An HTML_QuickForm_header element being visited
- * @access public
- * @return void
- * @abstract
- */
- function renderHeader(&$header)
- {
- return;
- } // end func renderHeader
-
- /**
- * Called when visiting an element
- *
- * @param object An HTML_QuickForm_element object being visited
- * @param bool Whether an element is required
- * @param string An error message associated with an element
- * @access public
- * @return void
- * @abstract
- */
- function renderElement(&$element, $required, $error)
- {
- return;
- } // end func renderElement
-
- /**
- * Called when visiting a hidden element
- *
- * @param object An HTML_QuickForm_hidden object being visited
- * @access public
- * @return void
- * @abstract
- */
- function renderHidden(&$element)
- {
- return;
- } // end func renderHidden
-
- /**
- * Called when visiting a raw HTML/text pseudo-element
- *
- * Seems that this should not be used when using a template-based renderer
- *
- * @param object An HTML_QuickForm_html element being visited
- * @access public
- * @return void
- * @abstract
- */
- function renderHtml(&$data)
- {
- return;
- } // end func renderHtml
-
- /**
- * Called when visiting a group, before processing any group elements
- *
- * @param object An HTML_QuickForm_group object being visited
- * @param bool Whether a group is required
- * @param string An error message associated with a group
- * @access public
- * @return void
- * @abstract
- */
- function startGroup(&$group, $required, $error)
- {
- return;
- } // end func startGroup
-
- /**
- * Called when visiting a group, after processing all group elements
- *
- * @param object An HTML_QuickForm_group object being visited
- * @access public
- * @return void
- * @abstract
- */
- function finishGroup(&$group)
- {
- return;
- } // end func finishGroup
-} // end class HTML_QuickForm_Renderer
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP version 4.0 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Alexey Borzov <borz_off@cs.msu.su> |
-// | Adam Daniel <adaniel1@eesus.jnj.com> |
-// | Bertrand Mansion <bmansion@mamasam.com> |
-// | Thomas Schulz <ths@4bconsult.de> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Array.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-require_once 'HTML/QuickForm/Renderer.php';
-
-/**
- * A concrete renderer for HTML_QuickForm, makes an array of form contents
- *
- * Based on old toArray() code.
- *
- * The form array structure is the following:
- * array(
- * 'frozen' => 'whether the form is frozen',
- * 'javascript' => 'javascript for client-side validation',
- * 'attributes' => 'attributes for <form> tag',
- * 'requirednote => 'note about the required elements',
- * // if we set the option to collect hidden elements
- * 'hidden' => 'collected html of all hidden elements',
- * // if there were some validation errors:
- * 'errors' => array(
- * '1st element name' => 'Error for the 1st element',
- * ...
- * 'nth element name' => 'Error for the nth element'
- * ),
- * // if there are no headers in the form:
- * 'elements' => array(
- * element_1,
- * ...
- * element_N
- * )
- * // if there are headers in the form:
- * 'sections' => array(
- * array(
- * 'header' => 'Header text for the first header',
- * 'name' => 'Header name for the first header',
- * 'elements' => array(
- * element_1,
- * ...
- * element_K1
- * )
- * ),
- * ...
- * array(
- * 'header' => 'Header text for the Mth header',
- * 'name' => 'Header name for the Mth header',
- * 'elements' => array(
- * element_1,
- * ...
- * element_KM
- * )
- * )
- * )
- * );
- *
- * where element_i is an array of the form:
- * array(
- * 'name' => 'element name',
- * 'value' => 'element value',
- * 'type' => 'type of the element',
- * 'frozen' => 'whether element is frozen',
- * 'label' => 'label for the element',
- * 'required' => 'whether element is required',
- * 'error' => 'error associated with the element',
- * 'style' => 'some information about element style (e.g. for Smarty)',
- * // if element is not a group
- * 'html' => 'HTML for the element'
- * // if element is a group
- * 'separator' => 'separator for group elements',
- * 'elements' => array(
- * element_1,
- * ...
- * element_N
- * )
- * );
- *
- * @access public
- */
-class HTML_QuickForm_Renderer_Array extends HTML_QuickForm_Renderer
-{
- /**
- * An array being generated
- * @var array
- */
- var $_ary;
-
- /**
- * Number of sections in the form (i.e. number of headers in it)
- * @var integer
- */
- var $_sectionCount;
-
- /**
- * Current section number
- * @var integer
- */
- var $_currentSection;
-
- /**
- * Array representing current group
- * @var array
- */
- var $_currentGroup = null;
-
- /**
- * Additional style information for different elements
- * @var array
- */
- var $_elementStyles = array();
-
- /**
- * true: collect all hidden elements into string; false: process them as usual form elements
- * @var bool
- */
- var $_collectHidden = false;
-
- /**
- * true: render an array of labels to many labels, $key 0 named 'label', the rest "label_$key"
- * false: leave labels as defined
- * @var bool
- */
- var $staticLabels = false;
-
- /**
- * Constructor
- *
- * @param bool true: collect all hidden elements into string; false: process them as usual form elements
- * @param bool true: render an array of labels to many labels, $key 0 to 'label' and the oterh to "label_$key"
- * @access public
- */
- function HTML_QuickForm_Renderer_Array($collectHidden = false, $staticLabels = false)
- {
- $this->HTML_QuickForm_Renderer();
- $this->_collectHidden = $collectHidden;
- $this->_staticLabels = $staticLabels;
- } // end constructor
-
-
- /**
- * Returns the resultant array
- *
- * @access public
- * @return array
- */
- function toArray()
- {
- return $this->_ary;
- }
-
-
- function startForm(&$form)
- {
- $this->_ary = array(
- 'frozen' => $form->isFrozen(),
- 'javascript' => $form->getValidationScript(),
- 'attributes' => $form->getAttributes(true),
- 'requirednote' => $form->getRequiredNote(),
- 'errors' => array()
- );
- if ($this->_collectHidden) {
- $this->_ary['hidden'] = '';
- }
- $this->_elementIdx = 1;
- $this->_currentSection = null;
- $this->_sectionCount = 0;
- } // end func startForm
-
-
- function renderHeader(&$header)
- {
- $this->_ary['sections'][$this->_sectionCount] = array(
- 'header' => $header->toHtml(),
- 'name' => $header->getName()
- );
- $this->_currentSection = $this->_sectionCount++;
- } // end func renderHeader
-
-
- function renderElement(&$element, $required, $error)
- {
- $elAry = $this->_elementToArray($element, $required, $error);
- if (!empty($error)) {
- $this->_ary['errors'][$elAry['name']] = $error;
- }
- $this->_storeArray($elAry);
- } // end func renderElement
-
-
- function renderHidden(&$element)
- {
- if ($this->_collectHidden) {
- $this->_ary['hidden'] .= $element->toHtml() . "\n";
- } else {
- $this->renderElement($element, false, null);
- }
- } // end func renderHidden
-
-
- function startGroup(&$group, $required, $error)
- {
- $this->_currentGroup = $this->_elementToArray($group, $required, $error);
- if (!empty($error)) {
- $this->_ary['errors'][$this->_currentGroup['name']] = $error;
- }
- } // end func startGroup
-
-
- function finishGroup(&$group)
- {
- $this->_storeArray($this->_currentGroup);
- $this->_currentGroup = null;
- } // end func finishGroup
-
-
- /**
- * Creates an array representing an element
- *
- * @access private
- * @param object An HTML_QuickForm_element object
- * @param bool Whether an element is required
- * @param string Error associated with the element
- * @return array
- */
- function _elementToArray(&$element, $required, $error)
- {
- $ret = array(
- 'name' => $element->getName(),
- 'value' => $element->getValue(),
- 'type' => $element->getType(),
- 'frozen' => $element->isFrozen(),
- 'required' => $required,
- 'error' => $error
- );
- // render label(s)
- $labels = $element->getLabel();
- if (is_array($labels) && $this->_staticLabels) {
- foreach($labels as $key => $label) {
- $key = is_int($key)? $key + 1: $key;
- if (1 === $key) {
- $ret['label'] = $label;
- } else {
- $ret['label_' . $key] = $label;
- }
- }
- } else {
- $ret['label'] = $labels;
- }
-
- // set the style for the element
- if (isset($this->_elementStyles[$ret['name']])) {
- $ret['style'] = $this->_elementStyles[$ret['name']];
- }
- if ('group' == $ret['type']) {
- $ret['separator'] = $element->_separator;
- $ret['elements'] = array();
- } else {
- $ret['html'] = $element->toHtml();
- }
- return $ret;
- }
-
-
- /**
- * Stores an array representation of an element in the form array
- *
- * @access private
- * @param array Array representation of an element
- * @return void
- */
- function _storeArray($elAry)
- {
- // where should we put this element...
- if (is_array($this->_currentGroup) && ('group' != $elAry['type'])) {
- $this->_currentGroup['elements'][] = $elAry;
- } elseif (isset($this->_currentSection)) {
- $this->_ary['sections'][$this->_currentSection]['elements'][] = $elAry;
- } else {
- $this->_ary['elements'][] = $elAry;
- }
- }
-
-
- /**
- * Sets a style to use for element rendering
- *
- * @param mixed element name or array ('element name' => 'style name')
- * @param string style name if $elementName is not an array
- * @access public
- * @return void
- */
- function setElementStyle($elementName, $styleName = null)
- {
- if (is_array($elementName)) {
- $this->_elementStyles = array_merge($this->_elementStyles, $elementName);
- } else {
- $this->_elementStyles[$elementName] = $styleName;
- }
- }
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP version 4.0 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Alexey Borzov <borz_off@cs.msu.su> |
-// | Bertrand Mansion <bmansion@mamasam.com> |
-// | Thomas Schulz <ths@4bconsult.de> |
-// +----------------------------------------------------------------------+
-//
-// $Id: ArraySmarty.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-require_once 'HTML/QuickForm/Renderer/Array.php';
-
-/**
- * A static renderer for HTML_QuickForm, makes an array of form content
- * useful for an Smarty template
- *
- * Based on old toArray() code and ITStatic renderer.
- *
- * The form array structure is the following:
- * Array (
- * [frozen] => whether the complete form is frozen'
- * [javascript] => javascript for client-side validation
- * [attributes] => attributes for <form> tag
- * [hidden] => html of all hidden elements
- * [requirednote] => note about the required elements
- * [errors] => Array
- * (
- * [1st_element_name] => Error for the 1st element
- * ...
- * [nth_element_name] => Error for the nth element
- * )
- *
- * [header] => Array
- * (
- * [1st_header_name] => Header text for the 1st header
- * ...
- * [nth_header_name] => Header text for the nth header
- * )
- *
- * [1st_element_name] => Array for the 1st element
- * ...
- * [nth_element_name] => Array for the nth element
- *
- * // where an element array has the form:
- * (
- * [name] => element name
- * [value] => element value,
- * [type] => type of the element
- * [frozen] => whether element is frozen
- * [label] => label for the element
- * [required] => whether element is required
- * // if element is not a group:
- * [html] => HTML for the element
- * // if element is a group:
- * [separator] => separator for group elements
- * [1st_gitem_name] => Array for the 1st element in group
- * ...
- * [nth_gitem_name] => Array for the nth element in group
- * )
- * )
- *
- * @access public
- */
-class HTML_QuickForm_Renderer_ArraySmarty extends HTML_QuickForm_Renderer_Array
-{
- /**
- * The Smarty template engine instance
- * @var object
- */
- var $_tpl = null;
-
- /**
- * Current element index
- * @var integer
- */
- var $_elementIdx = 0;
-
- /**
- * The current element index inside a group
- * @var integer
- */
- var $_groupElementIdx = 0;
-
- /**
- * How to handle the required tag for required fields
- * @var string
- * @see setRequiredTemplate()
- */
- var $_required = '';
-
- /**
- * How to handle error messages in form validation
- * @var string
- * @see setErrorTemplate()
- */
- var $_error = '';
-
- /**
- * Constructor
- *
- * @param object reference to the Smarty template engine instance
- * @param bool true: render an array of labels to many labels, $key 0 to 'label' and the oterh to "label_$key"
- * @access public
- */
- function HTML_QuickForm_Renderer_ArraySmarty(&$tpl, $staticLabels = false)
- {
- $this->HTML_QuickForm_Renderer_Array(true, $staticLabels);
- $this->_tpl =& $tpl;
- } // end constructor
-
- /**
- * Called when visiting a header element
- *
- * @param object An HTML_QuickForm_header element being visited
- * @access public
- * @return void
- */
- function renderHeader(&$header)
- {
- if ($name = $header->getName()) {
- $this->_ary['header'][$name] = $header->toHtml();
- } else {
- $this->_ary['header'][$this->_sectionCount] = $header->toHtml();
- }
- $this->_currentSection = $this->_sectionCount++;
- } // end func renderHeader
-
- /**
- * Called when visiting a group, before processing any group elements
- *
- * @param object An HTML_QuickForm_group object being visited
- * @param bool Whether a group is required
- * @param string An error message associated with a group
- * @access public
- * @return void
- */
- function startGroup(&$group, $required, $error)
- {
- parent::startGroup($group, $required, $error);
- $this->_groupElementIdx = 1;
- } // end func startGroup
-
- /**
- * Creates an array representing an element containing
- * the key for storing this
- *
- * @access private
- * @param object An HTML_QuickForm_element object
- * @param bool Whether an element is required
- * @param string Error associated with the element
- * @return array
- */
- function _elementToArray(&$element, $required, $error)
- {
- $ret = parent::_elementToArray($element, $required, $error);
-
- if ('group' == $ret['type']) {
- $ret['html'] = $element->toHtml();
- // we don't need the elements, see the array structure
- unset($ret['elements']);
- }
- if (!empty($this->_required)){
- $this->_renderRequired($ret['label'], $ret['html'], $required, $error);
- }
- if (!empty($this->_error)) {
- $this->_renderError($ret['label'], $ret['html'], $error);
- $ret['error'] = $error;
- }
- // create keys for elements grouped by native group or name
- if (strstr($ret['name'], '[') or $this->_currentGroup) {
- preg_match('/([^]]*)\\[([^]]*)\\]/', $ret['name'], $matches);
- if (isset($matches[1])) {
- $sKeysSub = substr_replace($ret['name'], '', 0, strlen($matches[1]));
- $sKeysSub = str_replace(
- array('[' , ']', '[\'\']'),
- array('[\'', '\']', '[]' ),
- $sKeysSub
- );
- $sKeys = '[\'' . $matches[1] . '\']' . $sKeysSub;
- } else {
- $sKeys = '[\'' . $ret['name'] . '\']';
- }
- // special handling for elements in native groups
- if ($this->_currentGroup) {
- // skip unnamed group items unless radios: no name -> no static access
- // identification: have the same key string as the parent group
- if ($this->_currentGroup['keys'] == $sKeys and 'radio' != $ret['type']) {
- return false;
- }
- // reduce string of keys by remove leading group keys
- if (0 === strpos($sKeys, $this->_currentGroup['keys'])) {
- $sKeys = substr_replace($sKeys, '', 0, strlen($this->_currentGroup['keys']));
- }
- }
- // element without a name
- } elseif ($ret['name'] == '') {
- $sKeys = '[\'element_' . $this->_elementIdx . '\']';
- // other elements
- } else {
- $sKeys = '[\'' . $ret['name'] . '\']';
- }
- // for radios: add extra key from value
- if ('radio' == $ret['type'] and substr($sKeys, -2) != '[]') {
- $sKeys .= '[\'' . $ret['value'] . '\']';
- }
- $this->_elementIdx++;
- $ret['keys'] = $sKeys;
- return $ret;
- } // end func _elementToArray
-
- /**
- * Stores an array representation of an element in the form array
- *
- * @access private
- * @param array Array representation of an element
- * @return void
- */
- function _storeArray($elAry)
- {
- if ($elAry) {
- $sKeys = $elAry['keys'];
- unset($elAry['keys']);
- // where should we put this element...
- if (is_array($this->_currentGroup) && ('group' != $elAry['type'])) {
- $toEval = '$this->_currentGroup' . $sKeys . ' = $elAry;';
- } else {
- $toEval = '$this->_ary' . $sKeys . ' = $elAry;';
- }
- eval($toEval);
- }
- return;
- }
-
- /**
- * Called when an element is required
- *
- * This method will add the required tag to the element label and/or the element html
- * such as defined with the method setRequiredTemplate.
- *
- * @param string The element label
- * @param string The element html rendering
- * @param boolean The element required
- * @param string The element error
- * @see setRequiredTemplate()
- * @access private
- * @return void
- */
- function _renderRequired(&$label, &$html, &$required, &$error)
- {
- $this->_tpl->assign(array(
- 'label' => $label,
- 'html' => $html,
- 'required' => $required,
- 'error' => $error
- ));
- if (!empty($label) && strpos($this->_required, $this->_tpl->left_delimiter . '$label') !== false) {
- $label = $this->_tplFetch($this->_required);
- }
- if (!empty($html) && strpos($this->_required, $this->_tpl->left_delimiter . '$html') !== false) {
- $html = $this->_tplFetch($this->_required);
- }
- $this->_tpl->clear_assign(array('label', 'html', 'required'));
- } // end func _renderRequired
-
- /**
- * Called when an element has a validation error
- *
- * This method will add the error message to the element label or the element html
- * such as defined with the method setErrorTemplate. If the error placeholder is not found
- * in the template, the error will be displayed in the form error block.
- *
- * @param string The element label
- * @param string The element html rendering
- * @param string The element error
- * @see setErrorTemplate()
- * @access private
- * @return void
- */
- function _renderError(&$label, &$html, &$error)
- {
- $this->_tpl->assign(array('label' => '', 'html' => '', 'error' => $error));
- $error = $this->_tplFetch($this->_error);
- $this->_tpl->assign(array('label' => $label, 'html' => $html));
-
- if (!empty($label) && strpos($this->_error, $this->_tpl->left_delimiter . '$label') !== false) {
- $label = $this->_tplFetch($this->_error);
- } elseif (!empty($html) && strpos($this->_error, $this->_tpl->left_delimiter . '$html') !== false) {
- $html = $this->_tplFetch($this->_error);
- }
- $this->_tpl->clear_assign(array('label', 'html', 'error'));
- } // end func _renderError
-
- /**
- * Process an template sourced in a string with Smarty
- *
- * Smarty has no core function to render a template given as a string.
- * So we use the smarty eval plugin function to do this.
- *
- * @param string The template source
- * @access private
- * @return void
- */
- function _tplFetch($tplSource)
- {
- if (!function_exists('smarty_function_eval')) {
- require SMARTY_DIR . '/plugins/function.eval.php';
- }
- return smarty_function_eval(array('var' => $tplSource), $this->_tpl);
- }// end func _tplFetch
-
- /**
- * Sets the way required elements are rendered
- *
- * You can use {$label} or {$html} placeholders to let the renderer know where
- * where the element label or the element html are positionned according to the
- * required tag. They will be replaced accordingly with the right value. You
- * can use the full smarty syntax here, especially a custom modifier for I18N.
- * For example:
- * {if $required}<span style="color: red;">*</span>{/if}{$label|translate}
- * will put a red star in front of the label if the element is required and
- * translate the label.
- *
- *
- * @param string The required element template
- * @access public
- * @return void
- */
- function setRequiredTemplate($template)
- {
- $this->_required = $template;
- } // end func setRequiredTemplate
-
- /**
- * Sets the way elements with validation errors are rendered
- *
- * You can use {$label} or {$html} placeholders to let the renderer know where
- * where the element label or the element html are positionned according to the
- * error message. They will be replaced accordingly with the right value.
- * The error message will replace the {$error} placeholder.
- * For example:
- * {if $error}<span style="color: red;">{$error}</span>{/if}<br />{$html}
- * will put the error message in red on top of the element html.
- *
- * If you want all error messages to be output in the main error block, use
- * the {$form.errors} part of the rendered array that collects all raw error
- * messages.
- *
- * If you want to place all error messages manually, do not specify {$html}
- * nor {$label}.
- *
- * Groups can have special layouts. With this kind of groups, you have to
- * place the formated error message manually. In this case, use {$form.group.error}
- * where you want the formated error message to appear in the form.
- *
- * @param string The element error template
- * @access public
- * @return void
- */
- function setErrorTemplate($template)
- {
- $this->_error = $template;
- } // end func setErrorTemplate
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP version 4.0 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Alexey Borzov <borz_off@cs.msu.su> |
-// | Adam Daniel <adaniel1@eesus.jnj.com> |
-// | Bertrand Mansion <bmansion@mamasam.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Default.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-require_once('HTML/QuickForm/Renderer.php');
-
-/**
- * A concrete renderer for HTML_QuickForm,
- * based on QuickForm 2.x built-in one
- *
- * @access public
- */
-class HTML_QuickForm_Renderer_Default extends HTML_QuickForm_Renderer
-{
- /**
- * The HTML of the form
- * @var string
- * @access private
- */
- var $_html;
-
- /**
- * Header Template string
- * @var string
- * @access private
- */
- var $_headerTemplate =
- "\n\t<tr>\n\t\t<td style=\"white-space: nowrap; background-color: #CCCCCC;\" align=\"left\" valign=\"top\" colspan=\"2\"><b>{header}</b></td>\n\t</tr>";
-
- /**
- * Element template string
- * @var string
- * @access private
- */
- var $_elementTemplate =
- "\n\t<tr>\n\t\t<td class=\"labelcell\" align=\"right\" valign=\"top\"><!-- BEGIN required --><span style=\"color: #ff0000\">*</span><!-- END required -->{label}</td>\n\t\t<td class=\"fieldcell\" valign=\"top\" align=\"left\"><!-- BEGIN error --><span style=\"color: #ff0000\">{error}</span><br /><!-- END error -->\t{element}</td>\n\t</tr>";
-
- /**
- * Form template string
- * @var string
- * @access private
- */
- var $_formTemplate =
- "\n<form{attributes}>\n{hidden}<table>\n{content}\n</table>\n</form>";
-
- /**
- * Required Note template string
- * @var string
- * @access private
- */
- var $_requiredNoteTemplate =
- "\n\t<tr>\n\t\t<td></td>\n\t<td align=\"left\" valign=\"top\">{requiredNote}</td>\n\t</tr>";
-
- /**
- * Array containing the templates for customised elements
- * @var array
- * @access private
- */
- var $_templates = array();
-
- /**
- * Array containing the templates for group wraps.
- *
- * These templates are wrapped around group elements and groups' own
- * templates wrap around them. This is set by setGroupTemplate().
- *
- * @var array
- * @access private
- */
- var $_groupWraps = array();
-
- /**
- * Array containing the templates for elements within groups
- * @var array
- * @access private
- */
- var $_groupTemplates = array();
-
- /**
- * True if we are inside a group
- * @var bool
- * @access private
- */
- var $_inGroup = false;
-
- /**
- * Array with HTML generated for group elements
- * @var array
- * @access private
- */
- var $_groupElements = array();
-
- /**
- * Template for an element inside a group
- * @var string
- * @access private
- */
- var $_groupElementTemplate = '';
-
- /**
- * HTML that wraps around the group elements
- * @var string
- * @access private
- */
- var $_groupWrap = '';
-
- /**
- * HTML for the current group
- * @var string
- * @access private
- */
- var $_groupTemplate = '';
-
- /**
- * Collected HTML of the hidden fields
- * @var string
- * @access private
- */
- var $_hiddenHtml = '';
-
- /**
- * Constructor
- *
- * @access public
- */
- function HTML_QuickForm_Renderer_Default()
- {
- $this->HTML_QuickForm_Renderer();
- } // end constructor
-
- /**
- * returns the HTML generated for the form
- *
- * @access public
- * @return string
- */
- function toHtml()
- {
- return $this->_html;
- } // end func toHtml
-
- /**
- * Called when visiting a form, before processing any form elements
- *
- * @param object An HTML_QuickForm object being visited
- * @access public
- * @return void
- */
- function startForm(&$form)
- {
- $this->_html = '';
- $this->_hiddenHtml = '';
- } // end func startForm
-
- /**
- * Called when visiting a form, after processing all form elements
- * Adds required note, form attributes, validation javascript and form content.
- *
- * @param object An HTML_QuickForm object being visited
- * @access public
- * @return void
- */
- function finishForm(&$form)
- {
- // add a required note, if one is needed
- if (!empty($form->_required) && !$form->_freezeAll) {
- $this->_html .= str_replace('{requiredNote}', $form->getRequiredNote(), $this->_requiredNoteTemplate);
- }
- // add form attributes and content
- $html = str_replace('{attributes}', $form->getAttributes(true), $this->_formTemplate);
- if (strpos($this->_formTemplate, '{hidden}')) {
- $html = str_replace('{hidden}', $this->_hiddenHtml, $html);
- } else {
- $this->_html .= $this->_hiddenHtml;
- }
- $this->_html = str_replace('{content}', $this->_html, $html);
- // add a validation script
- if ('' != ($script = $form->getValidationScript())) {
- $this->_html = $script . "\n" . $this->_html;
- }
- } // end func finishForm
-
- /**
- * Called when visiting a header element
- *
- * @param object An HTML_QuickForm_header element being visited
- * @access public
- * @return void
- */
- function renderHeader(&$header)
- {
- $name = $header->getName();
- if (!empty($name) && isset($this->_templates[$name])) {
- $this->_html .= str_replace('{header}', $header->toHtml(), $this->_templates[$name]);
- } else {
- $this->_html .= str_replace('{header}', $header->toHtml(), $this->_headerTemplate);
- }
- } // end func renderHeader
-
- /**
- * Helper method for renderElement
- *
- * @param string Element name
- * @param mixed Element label (if using an array of labels, you should set the appropriate template)
- * @param bool Whether an element is required
- * @param string Error message associated with the element
- * @access private
- * @see renderElement()
- * @return string Html for element
- */
- function _prepareTemplate($name, $label, $required, $error)
- {
- if (is_array($label)) {
- $nameLabel = array_shift($label);
- } else {
- $nameLabel = $label;
- }
- if (isset($this->_templates[$name])) {
- $html = str_replace('{label}', $nameLabel, $this->_templates[$name]);
- } else {
- $html = str_replace('{label}', $nameLabel, $this->_elementTemplate);
- }
- if ($required) {
- $html = str_replace('<!-- BEGIN required -->', '', $html);
- $html = str_replace('<!-- END required -->', '', $html);
- } else {
- $html = preg_replace("/([ \t\n\r]*)?<!-- BEGIN required -->(\s|\S)*<!-- END required -->([ \t\n\r]*)?/i", '', $html);
- }
- if (isset($error)) {
- $html = str_replace('{error}', $error, $html);
- $html = str_replace('<!-- BEGIN error -->', '', $html);
- $html = str_replace('<!-- END error -->', '', $html);
- } else {
- $html = preg_replace("/([ \t\n\r]*)?<!-- BEGIN error -->(\s|\S)*<!-- END error -->([ \t\n\r]*)?/i", '', $html);
- }
- if (is_array($label)) {
- foreach($label as $key => $text) {
- $key = is_int($key)? $key + 2: $key;
- $html = str_replace("{label_{$key}}", $text, $html);
- $html = str_replace("<!-- BEGIN label_{$key} -->", '', $html);
- $html = str_replace("<!-- END label_{$key} -->", '', $html);
- }
- }
- if (strpos($html, '{label_')) {
- $html = preg_replace('/\s*<!-- BEGIN label_(\S+) -->.*<!-- END label_\1 -->\s*/i', '', $html);
- }
- return $html;
- } // end func _prepareTemplate
-
- /**
- * Renders an element Html
- * Called when visiting an element
- *
- * @param object An HTML_QuickForm_element object being visited
- * @param bool Whether an element is required
- * @param string An error message associated with an element
- * @access public
- * @return void
- */
- function renderElement(&$element, $required, $error)
- {
- if (!$this->_inGroup) {
- $html = $this->_prepareTemplate($element->getName(), $element->getLabel(), $required, $error);
- $this->_html .= str_replace('{element}', $element->toHtml(), $html);
-
- } elseif (!empty($this->_groupElementTemplate)) {
- $html = str_replace('{label}', $element->getLabel(), $this->_groupElementTemplate);
- if ($required) {
- $html = str_replace('<!-- BEGIN required -->', '', $html);
- $html = str_replace('<!-- END required -->', '', $html);
- } else {
- $html = preg_replace("/([ \t\n\r]*)?<!-- BEGIN required -->(\s|\S)*<!-- END required -->([ \t\n\r]*)?/i", '', $html);
- }
- $this->_groupElements[] = str_replace('{element}', $element->toHtml(), $html);
-
- } else {
- $this->_groupElements[] = $element->toHtml();
- }
- } // end func renderElement
-
- /**
- * Renders an hidden element
- * Called when visiting a hidden element
- *
- * @param object An HTML_QuickForm_hidden object being visited
- * @access public
- * @return void
- */
- function renderHidden(&$element)
- {
- $this->_hiddenHtml .= $element->toHtml() . "\n";
- } // end func renderHidden
-
- /**
- * Called when visiting a raw HTML/text pseudo-element
- *
- * @param object An HTML_QuickForm_html element being visited
- * @access public
- * @return void
- */
- function renderHtml(&$data)
- {
- $this->_html .= $data->toHtml();
- } // end func renderHtml
-
- /**
- * Called when visiting a group, before processing any group elements
- *
- * @param object An HTML_QuickForm_group object being visited
- * @param bool Whether a group is required
- * @param string An error message associated with a group
- * @access public
- * @return void
- */
- function startGroup(&$group, $required, $error)
- {
- $name = $group->getName();
- $this->_groupTemplate = $this->_prepareTemplate($name, $group->getLabel(), $required, $error);
- $this->_groupElementTemplate = empty($this->_groupTemplates[$name])? '': $this->_groupTemplates[$name];
- $this->_groupWrap = empty($this->_groupWraps[$name])? '': $this->_groupWraps[$name];
- $this->_groupElements = array();
- $this->_inGroup = true;
- } // end func startGroup
-
- /**
- * Called when visiting a group, after processing all group elements
- *
- * @param object An HTML_QuickForm_group object being visited
- * @access public
- * @return void
- */
- function finishGroup(&$group)
- {
- $separator = $group->_separator;
- if (is_array($separator)) {
- $count = count($separator);
- $html = '';
- for ($i = 0; $i < count($this->_groupElements); $i++) {
- $html .= (0 == $i? '': $separator[($i - 1) % $count]) . $this->_groupElements[$i];
- }
- } else {
- if (is_null($separator)) {
- $separator = ' ';
- }
- $html = implode((string)$separator, $this->_groupElements);
- }
- if (!empty($this->_groupWrap)) {
- $html = str_replace('{content}', $html, $this->_groupWrap);
- }
- $this->_html .= str_replace('{element}', $html, $this->_groupTemplate);
- $this->_inGroup = false;
- } // end func finishGroup
-
- /**
- * Sets element template
- *
- * @param string The HTML surrounding an element
- * @param string (optional) Name of the element to apply template for
- * @access public
- * @return void
- */
- function setElementTemplate($html, $element = null)
- {
- if (is_null($element)) {
- $this->_elementTemplate = $html;
- } else {
- $this->_templates[$element] = $html;
- }
- } // end func setElementTemplate
-
-
- /**
- * Sets template for a group wrapper
- *
- * This template is contained within a group-as-element template
- * set via setTemplate() and contains group's element templates, set
- * via setGroupElementTemplate()
- *
- * @param string The HTML surrounding group elements
- * @param string Name of the group to apply template for
- * @access public
- * @return void
- */
- function setGroupTemplate($html, $group)
- {
- $this->_groupWraps[$group] = $html;
- } // end func setGroupTemplate
-
- /**
- * Sets element template for elements within a group
- *
- * @param string The HTML surrounding an element
- * @param string Name of the group to apply template for
- * @access public
- * @return void
- */
- function setGroupElementTemplate($html, $group)
- {
- $this->_groupTemplates[$group] = $html;
- } // end func setGroupElementTemplate
-
- /**
- * Sets header template
- *
- * @param string The HTML surrounding the header
- * @access public
- * @return void
- */
- function setHeaderTemplate($html)
- {
- $this->_headerTemplate = $html;
- } // end func setHeaderTemplate
-
- /**
- * Sets form template
- *
- * @param string The HTML surrounding the form tags
- * @access public
- * @return void
- */
- function setFormTemplate($html)
- {
- $this->_formTemplate = $html;
- } // end func setFormTemplate
-
- /**
- * Sets the note indicating required fields template
- *
- * @param string The HTML surrounding the required note
- * @access public
- * @return void
- */
- function setRequiredNoteTemplate($html)
- {
- $this->_requiredNoteTemplate = $html;
- } // end func setRequiredNoteTemplate
-
- /**
- * Clears all the HTML out of the templates that surround notes, elements, etc.
- * Useful when you want to use addData() to create a completely custom form look
- *
- * @access public
- * @return void
- */
- function clearAllTemplates()
- {
- $this->setElementTemplate('{element}');
- $this->setFormTemplate("\n\t<form{attributes}>{content}\n\t</form>\n");
- $this->setRequiredNoteTemplate('');
- $this->_templates = array();
- } // end func clearAllTemplates
-} // end class HTML_QuickForm_Renderer_Default
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP version 4.0 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Alexey Borzov <borz_off@cs.msu.su> |
-// +----------------------------------------------------------------------+
-//
-// $Id: ITDynamic.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-require_once 'HTML/QuickForm/Renderer.php';
-
-/**
- * A concrete renderer for HTML_QuickForm, using Integrated Templates.
- *
- * This is a "dynamic" renderer, which means that concrete form look
- * is defined at runtime. This also means that you can define
- * <b>one</b> template file for <b>all</b> your forms. That template
- * should contain a block for every element 'look' appearing in your
- * forms and also some special blocks (consult the examples). If a
- * special block is not set for an element, the renderer falls back to
- * a default one.
- *
- * @author Alexey Borzov <borz_off@cs.msu.su>
- * @access public
- */
-class HTML_QuickForm_Renderer_ITDynamic extends HTML_QuickForm_Renderer
-{
- /**
- * A template class (HTML_Template_ITX or HTML_Template_Sigma) instance
- * @var object
- */
- var $_tpl = null;
-
- /**
- * The errors that were not shown near concrete fields go here
- * @var array
- */
- var $_errors = array();
-
- /**
- * Show the block with required note?
- * @var bool
- */
- var $_showRequired = false;
-
- /**
- * A separator for group elements
- * @var mixed
- */
- var $_groupSeparator = null;
-
- /**
- * The current element index inside a group
- * @var integer
- */
- var $_groupElementIdx = 0;
-
- /**
- * Blocks to use for different elements
- * @var array
- */
- var $_elementBlocks = array();
-
- /**
- * Block to use for headers
- * @var string
- */
- var $_headerBlock = null;
-
-
- /**
- * Constructor
- *
- * @param object An HTML_Template_ITX/HTML_Template_Sigma object to use
- */
- function HTML_QuickForm_Renderer_ITDynamic(&$tpl)
- {
- $this->HTML_QuickForm_Renderer();
- $this->_tpl =& $tpl;
- $this->_tpl->setCurrentBlock('qf_main_loop');
- }
-
-
- function finishForm(&$form)
- {
- // display errors above form
- if (!empty($this->_errors) && $this->_tpl->blockExists('qf_error_loop')) {
- foreach ($this->_errors as $error) {
- $this->_tpl->setVariable('qf_error', $error);
- $this->_tpl->parse('qf_error_loop');
- }
- }
- // show required note
- if ($this->_showRequired) {
- $this->_tpl->setVariable('qf_required_note', $form->getRequiredNote());
- }
- // assign form attributes
- $this->_tpl->setVariable('qf_attributes', $form->getAttributes(true));
- // assign javascript validation rules
- $this->_tpl->setVariable('qf_javascript', $form->getValidationScript());
- }
-
-
- function renderHeader(&$header)
- {
- $blockName = $this->_matchBlock($header);
- if ('qf_header' == $blockName && isset($this->_headerBlock)) {
- $blockName = $this->_headerBlock;
- }
- $this->_tpl->setVariable('qf_header', $header->toHtml());
- $this->_tpl->parse($blockName);
- $this->_tpl->parse('qf_main_loop');
- }
-
-
- function renderElement(&$element, $required, $error)
- {
- $blockName = $this->_matchBlock($element);
- // are we inside a group?
- if ('qf_main_loop' != $this->_tpl->currentBlock) {
- if (0 != $this->_groupElementIdx && $this->_tpl->placeholderExists('qf_separator', $blockName)) {
- if (is_array($this->_groupSeparator)) {
- $this->_tpl->setVariable('qf_separator', $this->_groupSeparator[($this->_groupElementIdx - 1) % count($this->_groupSeparator)]);
- } else {
- $this->_tpl->setVariable('qf_separator', (string)$this->_groupSeparator);
- }
- }
- $this->_groupElementIdx++;
-
- } elseif(!empty($error)) {
- // show the error message or keep it for later use
- if ($this->_tpl->blockExists($blockName . '_error')) {
- $this->_tpl->setVariable('qf_error', $error);
- } else {
- $this->_errors[] = $error;
- }
- }
- // show an '*' near the required element
- if ($required) {
- $this->_showRequired = true;
- if ($this->_tpl->blockExists($blockName . '_required')) {
- $this->_tpl->touchBlock($blockName . '_required');
- }
- }
- // Prepare multiple labels
- $labels = $element->getLabel();
- if (is_array($labels)) {
- $mainLabel = array_shift($labels);
- } else {
- $mainLabel = $labels;
- }
- // render the element itself with its main label
- $this->_tpl->setVariable('qf_element', $element->toHtml());
- if ($this->_tpl->placeholderExists('qf_label', $blockName)) {
- $this->_tpl->setVariable('qf_label', $mainLabel);
- }
- // render extra labels, if any
- if (is_array($labels)) {
- foreach($labels as $key => $label) {
- $key = is_int($key)? $key + 2: $key;
- if ($this->_tpl->blockExists($blockName . '_label_' . $key)) {
- $this->_tpl->setVariable('qf_label_' . $key, $label);
- }
- }
- }
- $this->_tpl->parse($blockName);
- $this->_tpl->parseCurrentBlock();
- }
-
-
- function renderHidden(&$element)
- {
- $this->_tpl->setVariable('qf_hidden', $element->toHtml());
- $this->_tpl->parse('qf_hidden_loop');
- }
-
-
- function startGroup(&$group, $required, $error)
- {
- $blockName = $this->_matchBlock($group);
- $this->_tpl->setCurrentBlock($blockName . '_loop');
- $this->_groupElementIdx = 0;
- $this->_groupSeparator = is_null($group->_separator)? ' ': $group->_separator;
- // show an '*' near the required element
- if ($required) {
- $this->_showRequired = true;
- if ($this->_tpl->blockExists($blockName . '_required')) {
- $this->_tpl->touchBlock($blockName . '_required');
- }
- }
- // show the error message or keep it for later use
- if (!empty($error)) {
- if ($this->_tpl->blockExists($blockName . '_error')) {
- $this->_tpl->setVariable('qf_error', $error);
- } else {
- $this->_errors[] = $error;
- }
- }
- $this->_tpl->setVariable('qf_group_label', $group->getLabel());
- }
-
-
- function finishGroup(&$group)
- {
- $this->_tpl->parse($this->_matchBlock($group));
- $this->_tpl->setCurrentBlock('qf_main_loop');
- $this->_tpl->parseCurrentBlock();
- }
-
-
- /**
- * Returns the name of a block to use for element rendering
- *
- * If a name was not explicitly set via setElementBlock(), it tries
- * the names '{prefix}_{element type}' and '{prefix}_{element}', where
- * prefix is either 'qf' or the name of the current group's block
- *
- * @param object An HTML_QuickForm_element object
- * @access private
- * @return string block name
- */
- function _matchBlock(&$element)
- {
- $name = $element->getName();
- $type = $element->getType();
- if (isset($this->_elementBlocks[$name]) && $this->_tpl->blockExists($this->_elementBlocks[$name])) {
- if (('group' == $type) || ($this->_elementBlocks[$name] . '_loop' != $this->_tpl->currentBlock)) {
- return $this->_elementBlocks[$name];
- }
- }
- if ('group' != $type && 'qf_main_loop' != $this->_tpl->currentBlock) {
- $prefix = substr($this->_tpl->currentBlock, 0, -5); // omit '_loop' postfix
- } else {
- $prefix = 'qf';
- }
- if ($this->_tpl->blockExists($prefix . '_' . $type)) {
- return $prefix . '_' . $type;
- } elseif ($this->_tpl->blockExists($prefix . '_' . $name)) {
- return $prefix . '_' . $name;
- } else {
- return $prefix . '_element';
- }
- }
-
-
- /**
- * Sets the block to use for element rendering
- *
- * @param mixed element name or array ('element name' => 'block name')
- * @param string block name if $elementName is not an array
- * @access public
- * @return void
- */
- function setElementBlock($elementName, $blockName = null)
- {
- if (is_array($elementName)) {
- $this->_elementBlocks = array_merge($this->_elementBlocks, $elementName);
- } else {
- $this->_elementBlocks[$elementName] = $blockName;
- }
- }
-
-
- /**
- * Sets the name of a block to use for header rendering
- *
- * @param string block name
- * @access public
- * @return void
- */
- function setHeaderBlock($blockName)
- {
- $this->_headerBlock = $blockName;
- }
-}
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP version 4.0 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Bertrand Mansion <bmansion@mamasam.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: ITStatic.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-require_once('HTML/QuickForm/Renderer.php');
-
-/**
- * A static renderer for HTML_QuickForm compatible
- * with HTML_Template_IT and HTML_Template_Sigma.
- *
- * As opposed to the dynamic renderer, this renderer needs
- * every elements and labels in the form to be specified by
- * placeholders at the position you want them to be displayed.
- *
- * @author Bertrand Mansion <bmansion@mamasam.com>
- * @access public
- */
-class HTML_QuickForm_Renderer_ITStatic extends HTML_QuickForm_Renderer
-{
- /**
- * An HTML_Template_IT or some other API compatible Template instance
- * @var object
- */
- var $_tpl = null;
-
- /**
- * Rendered form name
- * @var string
- */
- var $_formName = 'form';
-
- /**
- * The errors that were not shown near concrete fields go here
- * @var array
- */
- var $_errors = array();
-
- /**
- * Show the block with required note?
- * @var bool
- */
- var $_showRequired = false;
-
- /**
- * Which group are we currently parsing ?
- * @var string
- */
- var $_inGroup;
-
- /**
- * Index of the element in its group
- * @var int
- */
- var $_elementIndex = 0;
-
- /**
- * If elements have been added with the same name
- * @var array
- */
- var $_duplicateElements = array();
-
- /**
- * How to handle the required tag for required fields
- * @var string
- */
- var $_required = '{label}<font size="1" color="red">*</font>';
-
- /**
- * How to handle error messages in form validation
- * @var string
- */
- var $_error = '<font color="red">{error}</font><br />{html}';
-
- /**
- * Collected HTML for hidden elements, if needed
- * @var string
- */
- var $_hidden = '';
-
- /**
- * Constructor
- *
- * @param object An HTML_Template_IT or other compatible Template object to use
- */
- function HTML_QuickForm_Renderer_ITStatic(&$tpl)
- {
- $this->HTML_QuickForm_Renderer();
- $this->_tpl =& $tpl;
- } // end constructor
-
- /**
- * Called when visiting a form, before processing any form elements
- *
- * @param object An HTML_QuickForm object being visited
- * @access public
- * @return void
- */
- function startForm(&$form)
- {
- $this->_formName = $form->getAttribute('id');
-
- if (count($form->_duplicateIndex) > 0) {
- // Take care of duplicate elements
- foreach ($form->_duplicateIndex as $elementName => $indexes) {
- $this->_duplicateElements[$elementName] = 0;
- }
- }
- } // end func startForm
-
- /**
- * Called when visiting a form, after processing all form elements
- *
- * @param object An HTML_QuickForm object being visited
- * @access public
- * @return void
- */
- function finishForm(&$form)
- {
- // display errors above form
- if (!empty($this->_errors) && $this->_tpl->blockExists($this->_formName.'_error_loop')) {
- foreach ($this->_errors as $error) {
- $this->_tpl->setVariable($this->_formName.'_error', $error);
- $this->_tpl->parse($this->_formName.'_error_loop');
- }
- }
- // show required note
- if ($this->_showRequired) {
- $this->_tpl->setVariable($this->_formName.'_required_note', $form->getRequiredNote());
- }
- // add hidden elements, if collected
- if (!empty($this->_hidden)) {
- $this->_tpl->setVariable($this->_formName . '_hidden', $this->_hidden);
- }
- // assign form attributes
- $this->_tpl->setVariable($this->_formName.'_attributes', $form->getAttributes(true));
- // assign javascript validation rules
- $this->_tpl->setVariable($this->_formName.'_javascript', $form->getValidationScript());
- } // end func finishForm
-
- /**
- * Called when visiting a header element
- *
- * @param object An HTML_QuickForm_header element being visited
- * @access public
- * @return void
- */
- function renderHeader(&$header)
- {
- $name = $header->getName();
- $varName = $this->_formName.'_header';
-
- // Find placeHolder
- if (!empty($name) && $this->_tpl->placeHolderExists($this->_formName.'_header_'.$name)) {
- $varName = $this->_formName.'_header_'.$name;
- }
- $this->_tpl->setVariable($varName, $header->toHtml());
- } // end func renderHeader
-
- /**
- * Called when visiting an element
- *
- * @param object An HTML_QuickForm_element object being visited
- * @param bool Whether an element is required
- * @param string An error message associated with an element
- * @access public
- * @return void
- */
- function renderElement(&$element, $required, $error)
- {
- $name = $element->getName();
-
- // are we inside a group?
- if (!empty($this->_inGroup)) {
- $varName = $this->_formName.'_'.str_replace(array('[', ']'), '_', $name);
- if (substr($varName, -2) == '__') {
- // element name is of type : group[]
- $varName = $this->_inGroup.'_'.$this->_elementIndex.'_';
- $this->_elementIndex++;
- }
- if ($varName != $this->_inGroup) {
- $varName .= '_' == substr($varName, -1)? '': '_';
- // element name is of type : group[name]
- $label = $element->getLabel();
- $html = $element->toHtml();
-
- if ($required && !$element->isFrozen()) {
- $this->_renderRequired($label, $html);
- $this->_showRequired = true;
- }
- if (!empty($label)) {
- if (is_array($label)) {
- foreach ($label as $key => $value) {
- $this->_tpl->setVariable($varName.'label_'.$key, $value);
- }
- } else {
- $this->_tpl->setVariable($varName.'label', $label);
- }
- }
- $this->_tpl->setVariable($varName.'html', $html);
- }
-
- } else {
-
- $name = str_replace(array('[', ']'), array('_', ''), $name);
-
- if (isset($this->_duplicateElements[$name])) {
- // Element is a duplicate
- $varName = $this->_formName.'_'.$name.'_'.$this->_duplicateElements[$name];
- $this->_duplicateElements[$name]++;
- } else {
- $varName = $this->_formName.'_'.$name;
- }
-
- $label = $element->getLabel();
- $html = $element->toHtml();
-
- if ($required) {
- $this->_showRequired = true;
- $this->_renderRequired($label, $html);
- }
- if (!empty($error)) {
- $this->_renderError($label, $html, $error);
- }
- if (is_array($label)) {
- foreach ($label as $key => $value) {
- $this->_tpl->setVariable($varName.'_label_'.$key, $value);
- }
- } else {
- $this->_tpl->setVariable($varName.'_label', $label);
- }
- $this->_tpl->setVariable($varName.'_html', $html);
- }
- } // end func renderElement
-
- /**
- * Called when visiting a hidden element
- *
- * @param object An HTML_QuickForm_hidden object being visited
- * @access public
- * @return void
- */
- function renderHidden(&$element)
- {
- if ($this->_tpl->placeholderExists($this->_formName . '_hidden')) {
- $this->_hidden .= $element->toHtml();
- } else {
- $name = $element->getName();
- $name = str_replace(array('[', ']'), array('_', ''), $name);
- $this->_tpl->setVariable($this->_formName.'_'.$name.'_html', $element->toHtml());
- }
- } // end func renderHidden
-
- /**
- * Called when visiting a group, before processing any group elements
- *
- * @param object An HTML_QuickForm_group object being visited
- * @param bool Whether a group is required
- * @param string An error message associated with a group
- * @access public
- * @return void
- */
- function startGroup(&$group, $required, $error)
- {
- $name = $group->getName();
- $varName = $this->_formName.'_'.$name;
-
- $this->_elementIndex = 0;
-
- $html = $this->_tpl->placeholderExists($varName.'_html') ? $group->toHtml() : '';
- $label = $group->getLabel();
-
- if ($required) {
- $this->_renderRequired($label, $html);
- }
- if (!empty($error)) {
- $this->_renderError($label, $html, $error);
- }
- if (!empty($html)) {
- $this->_tpl->setVariable($varName.'_html', $html);
- } else {
- // Uses error blocks to set the special groups layout error
- // <!-- BEGIN form_group_error -->{form_group_error}<!-- END form_group_error -->
- if (!empty($error)) {
- if ($this->_tpl->placeholderExists($varName.'_error')) {
- if ($this->_tpl->blockExists($this->_formName . '_error_block')) {
- $this->_tpl->setVariable($this->_formName . '_error', $error);
- $error = $this->_getTplBlock($this->_formName . '_error_block');
- } elseif (strpos($this->_error, '{html}') !== false || strpos($this->_error, '{label}') !== false) {
- $error = str_replace('{error}', $error, $this->_error);
- }
- }
- $this->_tpl->setVariable($varName . '_error', $error);
- array_pop($this->_errors);
- }
- }
- if (is_array($label)) {
- foreach ($label as $key => $value) {
- $this->_tpl->setVariable($varName.'_label_'.$key, $value);
- }
- } else {
- $this->_tpl->setVariable($varName.'_label', $label);
- }
- $this->_inGroup = $varName;
- } // end func startGroup
-
- /**
- * Called when visiting a group, after processing all group elements
- *
- * @param object An HTML_QuickForm_group object being visited
- * @access public
- * @return void
- */
- function finishGroup(&$group)
- {
- $this->_inGroup = '';
- } // end func finishGroup
-
- /**
- * Sets the way required elements are rendered
- *
- * You can use {label} or {html} placeholders to let the renderer know where
- * where the element label or the element html are positionned according to the
- * required tag. They will be replaced accordingly with the right value.
- * For example:
- * <font color="red">*</font>{label}
- * will put a red star in front of the label if the element is required.
- *
- * @param string The required element template
- * @access public
- * @return void
- */
- function setRequiredTemplate($template)
- {
- $this->_required = $template;
- } // end func setRequiredTemplate
-
- /**
- * Sets the way elements with validation errors are rendered
- *
- * You can use {label} or {html} placeholders to let the renderer know where
- * where the element label or the element html are positionned according to the
- * error message. They will be replaced accordingly with the right value.
- * The error message will replace the {error} place holder.
- * For example:
- * <font color="red">{error}</font><br />{html}
- * will put the error message in red on top of the element html.
- *
- * If you want all error messages to be output in the main error block, do not specify
- * {html} nor {label}.
- *
- * Groups can have special layouts. With this kind of groups, the renderer will need
- * to know where to place the error message. In this case, use error blocks like:
- * <!-- BEGIN form_group_error -->{form_group_error}<!-- END form_group_error -->
- * where you want the error message to appear in the form.
- *
- * @param string The element error template
- * @access public
- * @return void
- */
- function setErrorTemplate($template)
- {
- $this->_error = $template;
- } // end func setErrorTemplate
-
- /**
- * Called when an element is required
- *
- * This method will add the required tag to the element label and/or the element html
- * such as defined with the method setRequiredTemplate
- *
- * @param string The element label
- * @param string The element html rendering
- * @see setRequiredTemplate()
- * @access private
- * @return void
- */
- function _renderRequired(&$label, &$html)
- {
- if ($this->_tpl->blockExists($tplBlock = $this->_formName . '_required_block')) {
- if (!empty($label) && $this->_tpl->placeholderExists($this->_formName . '_label', $tplBlock)) {
- $this->_tpl->setVariable($this->_formName . '_label', is_array($label)? $label[0]: $label);
- if (is_array($label)) {
- $label[0] = $this->_getTplBlock($tplBlock);
- } else {
- $label = $this->_getTplBlock($tplBlock);
- }
- }
- if (!empty($html) && $this->_tpl->placeholderExists($this->_formName . '_html', $tplBlock)) {
- $this->_tpl->setVariable($this->_formName . '_html', $html);
- $html = $this->_getTplBlock($tplBlock);
- }
- } else {
- if (!empty($label) && strpos($this->_required, '{label}') !== false) {
- if (is_array($label)) {
- $label[0] = str_replace('{label}', $label[0], $this->_required);
- } else {
- $label = str_replace('{label}', $label, $this->_required);
- }
- }
- if (!empty($html) && strpos($this->_required, '{html}') !== false) {
- $html = str_replace('{html}', $html, $this->_required);
- }
- }
- } // end func _renderRequired
-
- /**
- * Called when an element has a validation error
- *
- * This method will add the error message to the element label or the element html
- * such as defined with the method setErrorTemplate. If the error placeholder is not found
- * in the template, the error will be displayed in the form error block.
- *
- * @param string The element label
- * @param string The element html rendering
- * @param string The element error
- * @see setErrorTemplate()
- * @access private
- * @return void
- */
- function _renderError(&$label, &$html, $error)
- {
- if ($this->_tpl->blockExists($tplBlock = $this->_formName . '_error_block')) {
- $this->_tpl->setVariable($this->_formName . '_error', $error);
- if (!empty($label) && $this->_tpl->placeholderExists($this->_formName . '_label', $tplBlock)) {
- $this->_tpl->setVariable($this->_formName . '_label', is_array($label)? $label[0]: $label);
- if (is_array($label)) {
- $label[0] = $this->_getTplBlock($tplBlock);
- } else {
- $label = $this->_getTplBlock($tplBlock);
- }
- } elseif (!empty($html) && $this->_tpl->placeholderExists($this->_formName . '_html', $tplBlock)) {
- $this->_tpl->setVariable($this->_formName . '_html', $html);
- $html = $this->_getTplBlock($tplBlock);
- }
- // clean up after ourselves
- $this->_tpl->setVariable($this->_formName . '_error', null);
- } elseif (!empty($label) && strpos($this->_error, '{label}') !== false) {
- if (is_array($label)) {
- $label[0] = str_replace(array('{label}', '{error}'), array($label[0], $error), $this->_error);
- } else {
- $label = str_replace(array('{label}', '{error}'), array($label, $error), $this->_error);
- }
- } elseif (!empty($html) && strpos($this->_error, '{html}') !== false) {
- $html = str_replace(array('{html}', '{error}'), array($html, $error), $this->_error);
- } else {
- $this->_errors[] = $error;
- }
- }// end func _renderError
-
-
- /**
- * Returns the block's contents
- *
- * The method is needed because ITX and Sigma implement clearing
- * the block contents on get() a bit differently
- *
- * @param string Block name
- * @return string Block contents
- */
- function _getTplBlock($block)
- {
- $this->_tpl->parse($block);
- if (is_a($this->_tpl, 'html_template_sigma')) {
- $ret = $this->_tpl->get($block, true);
- } else {
- $oldClear = $this->_tpl->clearCache;
- $this->_tpl->clearCache = true;
- $ret = $this->_tpl->get($block);
- $this->_tpl->clearCache = $oldClear;
- }
- return $ret;
- }
-} // end class HTML_QuickForm_Renderer_ITStatic
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP version 4.0 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Ron McClain <ron@humaniq.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Object.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-require_once('HTML/QuickForm/Renderer.php');
-
-/**
- * A concrete renderer for HTML_QuickForm, makes an object from form contents
- *
- * Based on HTML_Quickform_Renderer_Array code
- *
- * @public
- */
-class HTML_QuickForm_Renderer_Object extends HTML_QuickForm_Renderer {
- /**
- * The object being generated
- * @var object $_obj
- */
- var $_obj= null;
-
- /**
- * Number of sections in the form (i.e. number of headers in it)
- * @var integer $_sectionCount
- */
- var $_sectionCount;
-
- /**
- * Current section number
- * @var integer $_currentSection
- */
- var $_currentSection;
-
- /**
- * Object representing current group
- * @var object $_currentGroup
- */
- var $_currentGroup = null;
-
- /**
- * Class of Element Objects
- * @var object $_elementType
- */
- var $_elementType = 'QuickFormElement';
-
- /**
- * Additional style information for different elements
- * @var array $_elementStyles
- */
- var $_elementStyles = array();
-
- /**
- * true: collect all hidden elements into string; false: process them as usual form elements
- * @var bool $_collectHidden
- */
- var $_collectHidden = false;
-
-
- /**
- * Constructor
- *
- * @param collecthidden bool true: collect all hidden elements
- * @public
- */
- function HTML_QuickForm_Renderer_Object($collecthidden = false)
- {
- $this->HTML_QuickForm_Renderer();
- $this->_collectHidden = $collecthidden;
- $this->_obj = new QuickformForm;
- }
-
- /**
- * Return the rendered Object
- * @public
- */
- function toObject()
- {
- return $this->_obj;
- }
-
- /**
- * Set the class of the form elements. Defaults to StdClass.
- * @param type string Name of element class
- * @public
- */
- function setElementType($type) {
- $this->_elementType = $type;
- }
-
- function startForm(&$form)
- {
- $this->_obj->frozen = $form->isFrozen();
- $this->_obj->javascript = $form->getValidationScript();
- $this->_obj->attributes = $form->getAttributes(true);
- $this->_obj->requirednote = $form->getRequiredNote();
- $this->_obj->errors = new StdClass;
-
- if($this->_collectHidden) {
- $this->_obj->hidden = '';
- }
- $this->_elementIdx = 1;
- $this->_currentSection = null;
- $this->_sectionCount = 0;
- } // end func startForm
-
- function renderHeader(&$header)
- {
- $hobj = new StdClass;
- $hobj->header = $header->toHtml();
- $this->_obj->sections[$this->_sectionCount] = $hobj;
- $this->_currentSection = $this->_sectionCount++;
- }
- function renderElement(&$element, $required, $error)
- {
- $elObj = $this->_elementToObject($element, $required, $error);
- if(!empty($error)) {
- $name = $elObj->name;
- $this->_obj->errors->$name = $error;
- }
- $this->_storeObject($elObj);
- } // end func renderElement
-
- function renderHidden(&$element) {
- if($this->_collectHidden) {
- $this->_obj->hidden .= $element->toHtml() . "\n";
- } else {
- $this->renderElement($element, false, null);
- }
- } //end func renderHidden
-
- function startGroup(&$group, $required, $error)
- {
- $this->_currentGroup = $this->_elementToObject($group, $required, $error);
- if(!empty($error)) {
- $name = $this->_currentGroup->name;
- $this->_view->errors->$name = $error;
- }
- } // end func startGroup
-
- function finishGroup(&$group)
- {
- $this->_storeObject($this->_currentGroup);
- $this->_currentGroup = null;
- } // end func finishGroup
-
- /**
- * Creates an object representing an element
- *
- * @private
- * @param element object An HTML_QuickForm_element object
- * @param required bool Whether an element is required
- * @param error string Error associated with the element
- * @return object
- */
- function _elementToObject(&$element, $required, $error)
- {
- if($this->_elementType) {
- $ret = new $this->_elementType;
- }
- $ret->name = $element->getName();
- $ret->value = $element->getValue();
- $ret->type = $element->getType();
- $ret->frozen = $element->isFrozen();
- $labels = $element->getLabel();
- if (is_array($labels)) {
- $ret->label = array_shift($labels);
- foreach ($labels as $key => $label) {
- $key = is_int($key)? $key + 2: $key;
- $ret->{'label_' . $key} = $label;
- }
- } else {
- $ret->label = $labels;
- }
- $ret->required = $required;
- $ret->error = $error;
-
- if(isset($this->_elementStyles[$ret->name])) {
- $ret->style = $this->_elementStyles[$ret->name];
- $ret->styleTemplate = "styles/". $ret->style .".html";
- }
- if($ret->type == 'group') {
- $ret->separator = $element->_separator;
- $ret->elements = array();
- } else {
- $ret->html = $element->toHtml();
- }
- return $ret;
- }
-
- /**
- * Stores an object representation of an element in the form array
- *
- * @private
- * @param elObj object Object representation of an element
- * @return void
- */
- function _storeObject($elObj)
- {
- $name = $elObj->name;
- if(is_object($this->_currentGroup) && $elObj->type != 'group') {
- $this->_currentGroup->elements[] = $elObj;
- } elseif (isset($this->_currentSection)) {
- $this->_obj->sections[$this->_currentSection]->elements[] = $elObj;
- } else {
- $this->_obj->elements[] = $elObj;
- }
- }
-
- function setElementStyle($elementName, $styleName = null)
- {
- if(is_array($elementName)) {
- $this->_elementStyles = array_merge($this->_elementStyles, $elementName);
- } else {
- $this->_elementStyles[$elementName] = $styleName;
- }
- }
-
-} // end class HTML_QuickForm_Renderer_Object
-
-
-
-/**
- * @abstract Long Description
- * This class represents the object passed to outputObject()
- *
- * Eg.
- * {form.outputJavaScript():h}
- * {form.outputHeader():h}
- * <table>
- * <tr>
- * <td>{form.name.label:h}</td><td>{form.name.html:h}</td>
- * </tr>
- * </table>
- * </form>
- *
- * @public
- */
-class QuickformForm {
- /**
- * Whether the form has been frozen
- * @var boolean $frozen
- */
- var $frozen;
-
- /**
- * Javascript for client-side validation
- * @var string $javascript
- */
- var $javascript;
-
- /**
- * Attributes for form tag
- * @var string $attributes
- */
- var $attributes;
-
- /**
- * Note about required elements
- * @var string $requirednote
- */
- var $requirednote;
-
- /**
- * Collected html of all hidden variables
- * @var string $hidden
- */
- var $hidden;
-
- /**
- * Set if there were validation errors.
- * StdClass object with element names for keys and their
- * error messages as values
- * @var object $errors
- */
- var $errors;
-
- /**
- * Array of QuickformElementObject elements. If there are headers in the form
- * this will be empty and the elements will be in the
- * separate sections
- * @var array $elements
- */
- var $elements;
-
- /**
- * Array of sections contained in the document
- * @var array $sections
- */
- var $sections;
-
- /**
- * Output <form> header
- * {form.outputHeader():h}
- * @return string <form attributes>
- */
- function outputHeader() {
- $hdr = "<form " . $this->attributes . ">\n";
- return $hdr;
- }
- /**
- * Output form javascript
- * {form.outputJavaScript():h}
- * @return string Javascript
- */
- function outputJavaScript() {
- return $this->javascript;
- }
-} // end class QuickformForm
-
-
-/**
- * Convenience class describing a form element.
- * The properties defined here will be available from
- * your flexy templates by referencing
- * {form.zip.label:h}, {form.zip.html:h}, etc.
- */
-class QuickformElement {
-
- /**
- * Element name
- * @var string $name
- */
- var $name;
-
- /**
- * Element value
- * @var mixed $value
- */
- var $value;
-
- /**
- * Type of element
- * @var string $type
- */
- var $type;
-
- /**
- * Whether the element is frozen
- * @var boolean $frozen
- */
- var $frozen;
-
- /**
- * Label for the element
- * @var string $label
- */
- var $label;
-
- /**
- * Whether element is required
- * @var boolean $required
- */
- var $required;
-
- /**
- * Error associated with the element
- * @var string $error
- */
- var $error;
-
- /**
- * Some information about element style
- * @var string $style
- */
- var $style;
-
- /**
- * HTML for the element
- * @var string $html
- */
- var $html;
-
- /**
- * If element is a group, the group separator
- * @var mixed $separator
- */
- var $separator;
-
- /**
- * If element is a group, an array of subelements
- * @var array $elements
- */
- var $elements;
-
- function isType($type)
- {
- if($this->type == $type) {
- return true;
- } else {
- return false;
- }
- }
-
- function notFrozen()
- {
- if(!$this->frozen) {
- return true;
- } else {
- return false;
- }
- }
-
- function isButton()
- {
- if($this->type == "submit" || $this->type == "reset") {
- return true;
- } else {
- return false;
- }
- }
-
- function outputStyle()
- {
- $filename = "styles/".$this->style.".html";
- ob_start();
- HTML_Template_Flexy::staticQuickTemplate($filename, $this);
- $ret = ob_get_contents();
- ob_end_clean();
- return $ret;
- }
-
-} // end class QuickformElement
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP version 4.0 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Ron McClain <ron@humaniq.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: ObjectFlexy.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-require_once("HTML/QuickForm/Renderer/Object.php");
-
-/**
- * @abstract Long Description
- * A static renderer for HTML_Quickform. Makes a QuickFormFlexyObject
- * from the form content suitable for use with a Flexy template
- *
- * Usage:
- * $form =& new HTML_QuickForm('form', 'POST');
- * $template =& new HTML_Template_Flexy();
- * $renderer =& new HTML_QuickForm_Renderer_ObjectFlexy(&$template);
- * $renderer->setHtmlTemplate("html.html");
- * $renderer->setLabelTemplate("label.html");
- * $form->accept($renderer);
- * $view = new StdClass;
- * $view->form = $renderer->toObject();
- * $template->compile("mytemplate.html");
- *
- * @see QuickFormFlexyObject
- *
- * Based on the code for HTML_QuickForm_Renderer_ArraySmarty
- *
- * @public
- */
-class HTML_QuickForm_Renderer_ObjectFlexy extends HTML_QuickForm_Renderer_Object {
- /**
- * HTML_Template_Flexy instance
- * @var object $_flexy
- */
- var $_flexy;
-
- /**
- * Current element index
- * @var integer $_elementIdx
- */
- var $_elementIdx;
-
- /**
- * The current element index inside a group
- * @var integer $_groupElementIdx
- */
- var $_groupElementIdx = 0;
-
- /**
- * Name of template file for form html
- * @var string $_html
- * @see setRequiredTemplate()
- */
- var $_html = '';
-
- /**
- * Name of template file for form labels
- * @var string $label
- * @see setErrorTemplate()
- */
- var $label = '';
-
- /**
- * Class of the element objects, so you can add your own
- * element methods
- * @var string $_elementType
- */
- var $_elementType = 'QuickformFlexyElement';
-
- /**
- * Constructor
- *
- * @param $flexy object HTML_Template_Flexy instance
- * @public
- */
- function HTML_QuickForm_Renderer_ObjectFlexy(&$flexy)
- {
- $this->HTML_QuickForm_Renderer_Object(true);
- $this->_obj = new QuickformFlexyForm();
- $this->_flexy =& $flexy;
- } // end constructor
-
- function renderHeader(&$header)
- {
- if($name = $header->getName()) {
- $this->_obj->header->$name = $header->toHtml();
- } else {
- $this->_obj->header[$this->_sectionCount] = $header->toHtml();
- }
- $this->_currentSection = $this->_sectionCount++;
- } // end func renderHeader
-
- function startGroup(&$group, $required, $error)
- {
- parent::startGroup($group, $required, $error);
- $this->_groupElementIdx = 1;
- } //end func startGroup
-
- /**
- * Creates an object representing an element containing
- * the key for storing this
- *
- * @private
- * @param element object An HTML_QuickForm_element object
- * @param required bool Whether an element is required
- * @param error string Error associated with the element
- * @return object
- */
- function _elementToObject(&$element, $required, $error)
- {
- $ret = parent::_elementToObject($element, $required, $error);
- if($ret->type == 'group') {
- $ret->html = $element->toHtml();
- unset($ret->elements);
- }
- if(!empty($this->_label)) {
- $this->_renderLabel($ret);
- }
-
- if(!empty($this->_html)) {
- $this->_renderHtml($ret);
- $ret->error = $error;
- }
-
- // Create an element key from the name
- if (false !== ($pos = strpos($ret->name, '[')) || is_object($this->_currentGroup)) {
- if (!$pos) {
- $keys = '->{\'' . $ret->name . '\'}';
- } else {
- $keys = '->{\'' . str_replace(array('[', ']'), array('\'}->{\'', ''), $ret->name) . '\'}';
- }
- // special handling for elements in native groups
- if (is_object($this->_currentGroup)) {
- // skip unnamed group items unless radios: no name -> no static access
- // identification: have the same key string as the parent group
- if ($this->_currentGroup->keys == $keys && 'radio' != $ret->type) {
- return false;
- }
- // reduce string of keys by remove leading group keys
- if (0 === strpos($keys, $this->_currentGroup->keys)) {
- $keys = substr_replace($keys, '', 0, strlen($this->_currentGroup->keys));
- }
- }
- } elseif (0 == strlen($ret->name)) {
- $keys = '->{\'element_' . $this->_elementIdx . '\'}';
- } else {
- $keys = '->{\'' . $ret->name . '\'}';
- }
- // for radios: add extra key from value
- if ('radio' == $ret->type && '[]' != substr($keys, -2)) {
- $keys .= '->{\'' . $ret->value . '\'}';
- }
- $ret->keys = $keys;
- $this->_elementIdx++;
- return $ret;
- }
-
- /**
- * Stores an object representation of an element in the
- * QuickformFormObject instance
- *
- * @private
- * @param elObj object Object representation of an element
- * @return void
- */
- function _storeObject($elObj)
- {
- if ($elObj) {
- $keys = $elObj->keys;
- unset($elObj->keys);
- if(is_object($this->_currentGroup) && ('group' != $elObj->type)) {
- $code = '$this->_currentGroup' . $keys . ' = $elObj;';
- } else {
- $code = '$this->_obj' . $keys . ' = $elObj;';
- }
- eval($code);
- }
- }
-
- /**
- * Set the filename of the template to render html elements.
- * In your template, {html} is replaced by the unmodified html.
- * If the element is required, {required} will be true.
- * Eg.
- * {if:error}
- * <font color="red" size="1">{error:h}</font><br />
- * {end:}
- * {html:h}
- *
- * @public
- * @param template string Filename of template
- * @return void
- */
- function setHtmlTemplate($template)
- {
- $this->_html = $template;
- }
-
- /**
- * Set the filename of the template to render form labels
- * In your template, {label} is replaced by the unmodified label.
- * {error} will be set to the error, if any. {required} will
- * be true if this is a required field
- * Eg.
- * {if:required}
- * <font color="orange" size="1">*</font>
- * {end:}
- * {label:h}
- *
- * @public
- * @param template string Filename of template
- * @return void
- */
- function setLabelTemplate($template)
- {
- $this->_label = $template;
- }
-
- function _renderLabel(&$ret)
- {
- $this->_flexy->compile($this->_label);
- $ret->label = $this->_flexy->bufferedOutputObject($ret);
- }
-
- function _renderHtml(&$ret)
- {
- $this->_flexy->compile($this->_html);
- $ret->html = $this->_flexy->bufferedOutputObject($ret);
- }
-
-} // end class HTML_QuickForm_Renderer_ObjectFlexy
-
-/**
- * @abstract Long Description
- * This class represents the object passed to outputObject()
- *
- * Eg.
- * {form.outputJavaScript():h}
- * {form.outputHeader():h}
- * <table>
- * <tr>
- * <td>{form.name.label:h}</td><td>{form.name.html:h}</td>
- * </tr>
- * </table>
- * </form>
- *
- * @public
- */
-class QuickformFlexyForm {
- /**
- * Whether the form has been frozen
- * @var boolean $frozen
- */
- var $frozen;
-
- /**
- * Javascript for client-side validation
- * @var string $javascript
- */
- var $javascript;
-
- /**
- * Attributes for form tag
- * @var string $attributes
- */
- var $attributes;
-
- /**
- * Note about required elements
- * @var string $requirednote
- */
- var $requirednote;
-
- /**
- * Collected html of all hidden variables
- * @var string $hidden
- */
- var $hidden;
-
- /**
- * Set if there were validation errors.
- * StdClass object with element names for keys and their
- * error messages as values
- * @var object $errors
- */
- var $errors;
-
- /**
- * Array of QuickformElementObject elements. If there are headers in the form
- * this will be empty and the elements will be in the
- * separate sections
- * @var array $elements
- */
- var $elements;
-
- /**
- * Array of sections contained in the document
- * @var array $sections
- */
- var $sections;
-
- /**
- * Output <form> header
- * {form.outputHeader():h}
- * @return string <form attributes>
- */
- function outputHeader()
- {
- $hdr = "<form " . $this->attributes . ">\n";
- return $hdr;
- }
-
- /**
- * Output form javascript
- * {form.outputJavaScript():h}
- * @return string Javascript
- */
- function outputJavaScript()
- {
- return $this->javascript;
- }
-} // end class QuickformFlexyForm
-
-/**
- * Convenience class describing a form element.
- * The properties defined here will be available from
- * your flexy templates by referencing
- * {form.zip.label:h}, {form.zip.html:h}, etc.
- */
-class QuickformFlexyElement {
-
- /**
- * Element name
- * @var string $name
- */
- var $name;
-
- /**
- * Element value
- * @var mixed $value
- */
- var $value;
-
- /**
- * Type of element
- * @var string $type
- */
- var $type;
-
- /**
- * Whether the element is frozen
- * @var boolean $frozen
- */
- var $frozen;
-
- /**
- * Label for the element
- * @var string $label
- */
- var $label;
-
- /**
- * Whether element is required
- * @var boolean $required
- */
- var $required;
-
- /**
- * Error associated with the element
- * @var string $error
- */
- var $error;
-
- /**
- * Some information about element style
- * @var string $style
- */
- var $style;
-
- /**
- * HTML for the element
- * @var string $html
- */
- var $html;
-
- /**
- * If element is a group, the group separator
- * @var mixed $separator
- */
- var $separator;
-
- /**
- * If element is a group, an array of subelements
- * @var array $elements
- */
- var $elements;
-} // end class QuickformFlexyElement
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP version 4.0 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Jason Rust <jrust@rustyparts.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: QuickHtml.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-require_once('HTML/QuickForm/Renderer/Default.php');
-
-/**
- * A renderer that makes it quick and easy to create customized forms.
- *
- * This renderer has three main distinctives: an easy way to create
- * custom-looking forms, the ability to separate the creation of form
- * elements from their display, and being able to use QuickForm in
- * widget-based template systems. See the online docs for more info.
- * For a usage example see: docs/renderers/QuickHtml_example.php
- *
- * @access public
- * @package QuickForm
- */
-class HTML_QuickForm_Renderer_QuickHtml extends HTML_QuickForm_Renderer_Default {
- // {{{ properties
-
- /**
- * The array of rendered elements
- * @var array
- */
- var $renderedElements = array();
-
- // }}}
- // {{{ constructor
-
- /**
- * Constructor
- *
- * @access public
- * @return void
- */
- function HTML_QuickForm_Renderer_QuickHtml()
- {
- $this->HTML_QuickForm_Renderer_Default();
- // The default templates aren't used for this renderer
- $this->clearAllTemplates();
- } // end constructor
-
- // }}}
- // {{{ toHtml()
-
- /**
- * returns the HTML generated for the form
- *
- * @param string $data (optional) Any extra data to put before the end of the form
- *
- * @access public
- * @return string
- */
- function toHtml($data = '')
- {
- // Render any elements that haven't been rendered explicitly by elementToHtml()
- foreach (array_keys($this->renderedElements) as $key) {
- if (!$this->renderedElements[$key]['rendered']) {
- $this->renderedElements[$key]['rendered'] = true;
- $data .= $this->renderedElements[$key]['html'] . "\n";
- }
- }
-
- // Insert the extra data and form elements at the end of the form
- $this->_html = str_replace('</form>', $data . "\n</form>", $this->_html);
- return $this->_html;
- } // end func toHtml
-
- // }}}
- // {{{ elementToHtml()
-
- /**
- * Gets the html for an element and marks it as rendered.
- *
- * @param string $elementName The element name
- * @param string $elementValue (optional) The value of the element. This is only useful
- * for elements that have the same name (i.e. radio and checkbox), but
- * different values
- *
- * @access public
- * @return string The html for the QuickForm element
- */
- function elementToHtml($elementName, $elementValue = null)
- {
- $elementKey = null;
- // Find the key for the element
- foreach ($this->renderedElements as $key => $data) {
- if ($data['name'] == $elementName &&
- // See if the value must match as well
- (is_null($elementValue) ||
- $data['value'] == $elementValue)) {
- $elementKey = $key;
- break;
- }
- }
-
- if (is_null($elementKey)) {
- $msg = is_null($elementValue) ? "Element $elementName does not exist." :
- "Element $elementName with value of $elementValue does not exist.";
- return PEAR::raiseError(null, QUICKFORM_UNREGISTERED_ELEMENT, null, E_USER_WARNING, $msg, 'HTML_QuickForm_Error', true);
- } else {
- if ($this->renderedElements[$elementKey]['rendered']) {
- $msg = is_null($elementValue) ? "Element $elementName has already been rendered." :
- "Element $elementName with value of $elementValue has already been rendered.";
- return PEAR::raiseError(null, QUICKFORM_ERROR, null, E_USER_WARNING, $msg, 'HTML_QuickForm_Error', true);
- } else {
- $this->renderedElements[$elementKey]['rendered'] = true;
- return $this->renderedElements[$elementKey]['html'];
- }
- }
- } // end func elementToHtml
-
- // }}}
- // {{{ renderElement()
-
- /**
- * Gets the html for an element and adds it to the array by calling
- * parent::renderElement()
- *
- * @param object An HTML_QuickForm_element object
- * @param bool Whether an element is required
- * @param string An error message associated with an element
- *
- * @access public
- * @return mixed HTML string of element if $immediateRender is set, else we just add the
- * html to the global _html string
- */
- function renderElement(&$element, $required, $error)
- {
- $this->_html = '';
- parent::renderElement($element, $required, $error);
- if (!$this->_inGroup) {
- $this->renderedElements[] = array(
- 'name' => $element->getName(),
- 'value' => $element->getValue(),
- 'html' => $this->_html,
- 'rendered' => false);
- }
- $this->_html = '';
- } // end func renderElement
-
- // }}}
- // {{{ renderHidden()
-
- /**
- * Gets the html for a hidden element and adds it to the array.
- *
- * @param object An HTML_QuickForm_hidden object being visited
- * @access public
- * @return void
- */
- function renderHidden(&$element)
- {
- $this->renderedElements[] = array(
- 'name' => $element->getName(),
- 'value' => $element->getValue(),
- 'html' => $element->toHtml(),
- 'rendered' => false);
- } // end func renderHidden
-
- // }}}
- // {{{ finishGroup()
-
- /**
- * Gets the html for the group element and adds it to the array by calling
- * parent::finishGroup()
- *
- * @param object An HTML_QuickForm_group object being visited
- * @access public
- * @return void
- */
- function finishGroup(&$group)
- {
- $this->_html = '';
- parent::finishGroup($group);
- $this->renderedElements[] = array(
- 'name' => $group->getName(),
- 'value' => $group->getValue(),
- 'html' => $this->_html,
- 'rendered' => false);
- $this->_html = '';
- } // end func finishGroup
-
- // }}}
-} // end class HTML_QuickForm_Renderer_QuickHtml
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP version 4.0 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Bertrand Mansion <bmansion@mamasam.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Rule.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-class HTML_QuickForm_Rule
-{
- /**
- * Name of the rule to use in validate method
- *
- * This property is used in more global rules like Callback and Regex
- * to determine which callback and which regex is to be used for validation
- *
- * @var string
- * @access public
- */
- var $name;
-
- /**
- * Validates a value
- *
- * @access public
- * @abstract
- */
- function validate($value)
- {
- return true;
- }
-
- /**
- * Sets the rule name
- *
- * @access public
- */
- function setName($ruleName)
- {
- $this->name = $ruleName;
- }
-
- /**
- * Returns the javascript test (the test should return true if the value is INVALID)
- *
- * @param mixed Options for the rule
- * @access public
- * @return array first element is code to setup validation, second is the check itself
- */
- function getValidationScript($options = null)
- {
- return array('', '');
- }
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-require_once 'HTML/QuickForm/Rule.php';
-
-class HTML_QuickForm_Rule_Admin_Logo extends HTML_QuickForm_Rule
-{
- function validate($value, $options = null)
- {
- // Ewwwwww GLOBALS....I know they suck, but unavoidable in this case.
- global $form;
-
- // An image was uploaded from the file element.
- // extract and process the image
- // insert it into the form so it can get carried through if there
- // are other errors in the form.
- if (!empty($value['size']))
- {
- $imageName = process_image($value['tmp_name'], $value['name'], false);
-
- $element = array_keys($this->multiDimArrayLocate($_FILES, $value['name']));
- $origName = $element[0];
- $elementName = "uploaded_{$element[0]}";
-
- $img = '<img src="'.THUMB.$imageName.'" />';
-
- if ($form->elementExists($elementName))
- {
- $uploadedImage =& $form->getElement($elementName);
- $uploadedImage->setValue($imageName);
-
- $source =& $form->insertElementBefore($form->removeElement('image_rmv', false), $origName);
- $source->setValue($img);
- }
- else
- {
- $source =& $form->addElement('hidden', $elementName);
- $source->setValue($imageName);
-
- $source =& $form->createElement('static', 'image_rmv', 'Current Image:');
- $source->setValue($img);
- $form->insertElementBefore($source, $origName);
- }
- $form->_submitValues[$elementName] = $imageName;
- }
- // No image was uploaded
- // look and see if we are "carrying" and image
- // through the processing that was already uploaded.
- // IF we are, re-insert that image back into the form.
- // since it won't be there.
- else
- {
- $values = $form->getSubmitValues();
- foreach ($values as $k => $v)
- {
- if (is_string($v))
- {
- if (file_exists(THUMB_PATH . $v) && !is_dir(THUMB_PATH . $v))
- $key = $k;
- }
- }
-
- $origName = substr($key, 9);
-
- $img = '<img src="' . THUMB . $values[$key] . '" />';
-
- if ($form->elementExists($key))
- {
- $source =& $form->getElement($key);
- $source->setValue($values[$key]);
-
- $source =& $form->insertElementBefore($form->removeElement('image_rmv', false), $origName);
- $source->setValue($img);
- }
- else
- {
- $source =& $form->addElement('hidden', $key);
- $source->setValue($values[$key]);
-
- $source =& $form->createElement('static', 'image_rmv', 'Current Image:');
- $source->setValue($img);
- $form->insertElementBefore($source, $origName);
- }
- }
- return true;
- }
-
- function multiDimArrayLocate($array, $text)
- {
- foreach ($array as $k => $v)
- {
- if (is_array($v))
- {
- $temp[$k] = $this->multiDimArrayLocate($v, $text);
- if ($temp[$k])
- {
- $arrayResult[$k] = $temp[$k];
- }
- }
- else
- {
- if ($v == $text)
- {
- $arrayResult[$k] = $v;
- }
- }
- }
- return $arrayResult;
- }
-
-
- function getValidationScript($options = null)
- {
- }
-}
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-
-/**
- * Rule for HTML_QuickForm to display a CAPTCHA image
- *
- * This package requires the use of a PHP session.
- *
- * PHP versions 4 and 5
- *
- * @category HTML
- * @package HTML_QuickForm_CAPTCHA
- * @author Philippe Jausions <Philippe.Jausions@11abacus.com>
- * @copyright 2006 by 11abacus
- * @license LGPL
- * @version CVS: $Id: CAPTCHA.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_QuickForm_CAPTCHA
- */
-
-require_once 'HTML/QuickForm/Rule.php';
-
-/**
- * Rule to compare a field with a CAPTCHA image
- *
- * @access public
- * @package HTML_QuickForm_CAPTCHA
- * @version $Revision: 1.1.1.1 $
- */
-class HTML_QuickForm_Rule_CAPTCHA extends HTML_QuickForm_Rule
-{
- /**
- * Validates the data enter matches the CAPTCHA image that was
- * displayed
- *
- * @param string $value data to validate
- * @param HTML_QuickForm_CAPTCHA_Common $captcha_element to check against
- */
- function validate($value, $captcha)
- {
- return ($value == $captcha->getValue());
- }
-
-}
-
-HTML_QuickForm::registerRule('CAPTCHA', 'rule', 'HTML_QuickForm_Rule_CAPTCHA', 'HTML/QuickForm/Rule/CAPTCHA.php');
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP version 4.0 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Bertrand Mansion <bmansion@mamasam.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Callback.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-require_once('HTML/QuickForm/Rule.php');
-
-/**
-* Validates values using callback functions or methods
-* @version 1.0
-*/
-class HTML_QuickForm_Rule_Callback extends HTML_QuickForm_Rule
-{
- /**
- * Array of callbacks
- *
- * Array is in the format:
- * $_data['rulename'] = array('functionname', 'classname');
- * If the callback is not a method, then the class name is not set.
- *
- * @var array
- * @access private
- */
- var $_data = array();
-
- /**
- * Whether to use BC mode for specific rules
- *
- * Previous versions of QF passed element's name as a first parameter
- * to validation functions, but not to validation methods. This behaviour
- * is emulated if you are using 'function' as rule type when registering.
- *
- * @var array
- * @access private
- */
- var $_BCMode = array();
-
- /**
- * Validates a value using a callback
- *
- * @param string $value Value to be checked
- * @param mixed $options Options for callback
- * @access public
- * @return boolean true if value is valid
- */
- function validate($value, $options = null)
- {
- if (isset($this->_data[$this->name])) {
- $callback = $this->_data[$this->name];
- if (isset($callback[1])) {
- return call_user_func(array($callback[1], $callback[0]), $value, $options);
- } elseif ($this->_BCMode[$this->name]) {
- return $callback[0]('', $value, $options);
- } else {
- return $callback[0]($value, $options);
- }
- } elseif (is_callable($options)) {
- return call_user_func($options, $value);
- } else {
- return true;
- }
- } // end func validate
-
- /**
- * Adds new callbacks to the callbacks list
- *
- * @param string $name Name of rule
- * @param string $callback Name of function or method
- * @param string $class Name of class containing the method
- * @param bool $BCMode Backwards compatibility mode
- * @access public
- */
- function addData($name, $callback, $class = null, $BCMode = false)
- {
- if (!empty($class)) {
- $this->_data[$name] = array($callback, $class);
- } else {
- $this->_data[$name] = array($callback);
- }
- $this->_BCMode[$name] = $BCMode;
- } // end func addData
-
-
- function getValidationScript($options = null)
- {
- if (isset($this->_data[$this->name])) {
- $callback = $this->_data[$this->name][0];
- $params = ($this->_BCMode[$this->name]? "'', {jsVar}": '{jsVar}') .
- (isset($options)? ", '{$options}'": '');
- } else {
- $callback = is_array($options)? $options[1]: $options;
- $params = '{jsVar}';
- }
- return array('', "{jsVar} != '' && !{$callback}({$params})");
- } // end func getValidationScript
-
-} // end class HTML_QuickForm_Rule_Callback
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP version 4.0 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Alexey Borzov <avb@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Compare.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-require_once 'HTML/QuickForm/Rule.php';
-
-/**
- * Rule to compare two form fields
- *
- * The most common usage for this is to ensure that the password
- * confirmation field matches the password field
- *
- * @access public
- * @package HTML_QuickForm
- * @version $Revision: 1.1.1.1 $
- */
-class HTML_QuickForm_Rule_Compare extends HTML_QuickForm_Rule
-{
- /**
- * Possible operators to use
- * @var array
- * @access private
- */
- var $_operators = array(
- 'eq' => '==',
- 'neq' => '!=',
- 'gt' => '>',
- 'gte' => '>=',
- 'lt' => '<',
- 'lte' => '<='
- );
-
-
- /**
- * Returns the operator to use for comparing the values
- *
- * @access private
- * @param string operator name
- * @return string operator to use for validation
- */
- function _findOperator($name)
- {
- if (empty($name)) {
- return '==';
- } elseif (isset($this->_operators[$name])) {
- return $this->_operators[$name];
- } elseif (in_array($name, $this->_operators)) {
- return $name;
- } else {
- return '==';
- }
- }
-
-
- function validate($values, $operator = null)
- {
- $operator = $this->_findOperator($operator);
- if ('==' != $operator && '!=' != $operator) {
- $compareFn = create_function('$a, $b', 'return floatval($a) ' . $operator . ' floatval($b);');
- } else {
- $compareFn = create_function('$a, $b', 'return $a ' . $operator . ' $b;');
- }
-
- return $compareFn($values[0], $values[1]);
- }
-
-
- function getValidationScript($operator = null)
- {
- $operator = $this->_findOperator($operator);
- if ('==' != $operator && '!=' != $operator) {
- $check = "!(Number({jsVar}[0]) {$operator} Number({jsVar}[1]))";
- } else {
- $check = "!({jsVar}[0] {$operator} {jsVar}[1])";
- }
- return array('', "'' != {jsVar}[0] && {$check}");
- }
-}
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP version 4.0 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Bertrand Mansion <bmansion@mamasam.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Email.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-require_once('HTML/QuickForm/Rule.php');
-
-/**
-* Email validation rule
-* @version 1.0
-*/
-class HTML_QuickForm_Rule_Email extends HTML_QuickForm_Rule
-{
- var $regex = '/^((\"[^\"\f\n\r\t\v\b]+\")|([\w\!\#\$\%\&\'\*\+\-\~\/\^\`\|\{\}]+(\.[\w\!\#\$\%\&\'\*\+\-\~\/\^\`\|\{\}]+)*))@((\[(((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9])))\])|(((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9])))|((([A-Za-z0-9\-])+\.)+[A-Za-z\-]+))$/';
-
- /**
- * Validates an email address
- *
- * @param string $email Email address
- * @param boolean $checkDomain True if dns check should be performed
- * @access public
- * @return boolean true if email is valid
- */
- function validate($email, $checkDomain = false)
- {
- if (preg_match($this->regex, $email)) {
- if ($checkDomain && function_exists('checkdnsrr')) {
- $tokens = explode('@', $email);
- if (checkdnsrr($tokens[1], 'MX') || checkdnsrr($tokens[1], 'A')) {
- return true;
- }
- return false;
- }
- return true;
- }
- return false;
- } // end func validate
-
-
- function getValidationScript($options = null)
- {
- return array(" var regex = " . $this->regex . ";\n", "{jsVar} != '' && !regex.test({jsVar})");
- } // end func getValidationScript
-
-} // end class HTML_QuickForm_Rule_Email
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-require_once 'HTML/QuickForm/Rule.php';
-
-class HTML_QuickForm_Rule_Image extends HTML_QuickForm_Rule
-{
- function validate($value, $options = null)
- {
- // Ewwwwww GLOBALS....I know they suck, but unavoidable in this case.
- global $form;
-
- // An image was uploaded from the file element.
- // extract and process the image
- // insert it into the form so it can get carried through if there
- // are other errors in the form.
- if (!empty($value['size']))
- {
- $imageName = $this->process_image($value['tmp_name'], $value['name']);
-
- $element = array_keys($this->multiDimArrayLocate($_FILES, $value['name']));
- $origName = $element[0];
- $elementName = "uploaded_{$element[0]}";
-
- $img = '<img src="'.BANNER_THUMB.$imageName.'" />';
-
- if ($form->elementExists($elementName))
- {
- $uploadedImage =& $form->getElement($elementName);
- $uploadedImage->setValue($imageName);
-
- $source =& $form->insertElementBefore($form->removeElement('image_rmv', false), $origName);
- $source->setValue($img);
- }
- else
- {
- $source =& $form->addElement('hidden', $elementName);
- $source->setValue($imageName);
-
- $source =& $form->createElement('static', 'image_rmv', 'Current Banner:');
- $source->setValue($img);
- $form->insertElementBefore($source, $origName);
- }
- $form->_submitValues[$elementName] = $imageName;
- }
- // No image was uploaded
- // look and see if we are "carrying" and image
- // through the processing that was already uploaded.
- // IF we are, re-insert that image back into the form.
- // since it won't be there.
- else
- {
- $values = $form->getSubmitValues();
- foreach ($values as $k => $v)
- {
- if (is_string($v))
- {
- if (file_exists(BANNER_THUMB_PATH . $v) && !is_dir(BANNER_THUMB_PATH . $v))
- $key = $k;
- }
- }
-
- $origName = substr($key, 9);
-
- $img = '<img src="' . BANNER_THUMB . $values[$key] . '" />';
-
- if ($form->elementExists($key))
- {
- $source =& $form->getElement($key);
- $source->setValue($values[$key]);
-
- $source =& $form->insertElementBefore($form->removeElement('image_rmv', false), $origName);
- $source->setValue($img);
- }
- else
- {
- $source =& $form->addElement('hidden', $key);
- $source->setValue($values[$key]);
-
- $source =& $form->createElement('static', 'image_rmv', 'Current Banner:');
- $source->setValue($img);
- $form->insertElementBefore($source, $origName);
- }
- }
- return true;
- }
-
- function process_image( $image, $image_name )
- {
- if (!defined("BANNER_ORIGINAL_PATH"))
- {
- html_error("this not defined banner_original_path", 1);
- }
- if (!defined("BANNER_RESIZED_PATH"))
- {
- html_error("this not defined banner_resized_path", 1);
- }
- if (!defined("BANNER_MIDSIZED_PATH"))
- {
- html_error("this not defined banner_midsized_path", 1);
- }
- if (!defined("BANNER_THUMB_PATH"))
- {
- html_error("this not defined banner_thumb_path", 1);
- }
- $image_upload_array = img_upload($image,$image_name,BANNER_ORIGINAL_PATH);
- //img_resize($image_upload_array[1],BANNER_ORIGINAL_PATH.$image_upload_array[0],BANNER_ORIGINAL);
- img_resize(BANNER_ORIGINAL_PATH.$image_upload_array[0], BANNER_RESIZED_PATH.$image_upload_array[0], BANNER_ITEM_RESIZED);
- img_resize(BANNER_RESIZED_PATH.$image_upload_array[0], BANNER_MIDSIZED_PATH.$image_upload_array[0], BANNER_ITEM_MIDSIZED);
- img_resize(BANNER_MIDSIZED_PATH.$image_upload_array[0], BANNER_THUMB_PATH.$image_upload_array[0], BANNER_ITEM_THUMB);
- $image_name = $image_upload_array[0];
- return($image_name);
- }
-
- function multiDimArrayLocate($array, $text)
- {
- foreach ($array as $k => $v)
- {
- if (is_array($v))
- {
- $temp[$k] = $this->multiDimArrayLocate($v, $text);
- if ($temp[$k])
- {
- $arrayResult[$k] = $temp[$k];
- }
- }
- else
- {
- if ($v == $text)
- {
- $arrayResult[$k] = $v;
- }
- }
- }
- return $arrayResult;
- }
-
-
- function getValidationScript($options = null)
- {
- }
-}
-?>
+++ /dev/null
-<?php
-require_once 'HTML/QuickForm/Rule.php';
-
-class HTML_QuickForm_Rule_Logo extends HTML_QuickForm_Rule
-{
- function validate($value, $options = null)
- {
- // Ewwwwww GLOBALS....I know they suck, but unavoidable in this case.
- global $acform;
-
- // An image was uploaded from the file element.
- // extract and process the image
- // insert it into the form so it can get carried through if there
- // are other errors in the form.
- if (!empty($value['size']))
- {
- $imageName = process_image($value['tmp_name'], $value['name'], false);
-
- if ($imageName === 'ERROR')
- return false;
-
- $element = array_keys($this->multiDimArrayLocate($_FILES, $value['name']));
- $origName = $element[0];
- $elementName = "uploaded_{$element[0]}";
-
- $img = '<img src="' . THUMB . $imageName . '" />';
-
- if ($acform->elementExists($elementName))
- {
- $uploadedImage =& $acform->getElement($elementName);
- $uploadedImage->setValue($imageName);
-
- $source =& $acform->insertElementBefore($acform->removeElement('image_rmv', false), $origName);
- $source->setValue($img);
- }
- else
- {
- $source =& $acform->addElement('hidden', $elementName);
- $source->setValue($imageName);
-
- $source =& $acform->createElement('static', 'image_rmv', 'Uploaded Logo:');
- $source->setValue($img);
- $acform->insertElementBefore($source, $origName);
- }
- $acform->_submitValues[$elementName] = $imageName;
- }
- // No image was uploaded
- // look and see if we are "carrying" and image
- // through the processing that was already uploaded.
- // IF we are, re-insert that image back into the form.
- // since it won't be there.
- else
- {
- $values = $acform->getSubmitValues();
- foreach ($values as $k => $v)
- {
- if (is_string($v))
- {
- if (file_exists(THUMB_PATH . $v) && !is_dir(THUMB_PATH . $v))
- $key = $k;
- }
- }
-
- $origName = substr($key, 9);
-
- $img = '<img src="' . THUMB . $values[$key] . '" />';
-
- if ($acform->elementExists($key))
- {
- $source =& $acform->getElement($key);
- $source->setValue($values[$key]);
-
- $source =& $acform->insertElementBefore($acform->removeElement('image_rmv', false), $origName);
- $source->setValue($img);
- }
- else
- {
- $source =& $acform->addElement('hidden', $key);
- $source->setValue($values[$key]);
-
- $source =& $acform->createElement('static', 'image_rmv', 'Uploaded Logo:');
- $source->setValue($img);
- $acform->insertElementBefore($source, $origName);
- }
- }
- return true;
- }
-
- function multiDimArrayLocate($array, $text)
- {
- foreach ($array as $k => $v)
- {
- if (is_array($v))
- {
- $temp[$k] = $this->multiDimArrayLocate($v, $text);
- if ($temp[$k])
- {
- $arrayResult[$k] = $temp[$k];
- }
- }
- else
- {
- if ($v == $text)
- {
- $arrayResult[$k] = $v;
- }
- }
- }
- return $arrayResult;
- }
-
-
- function getValidationScript($options = null)
- {
- }
-}
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP version 4.0 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Bertrand Mansion <bmansion@mamasam.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Range.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-require_once('HTML/QuickForm/Rule.php');
-
-/**
-* Validates values using range comparison
-* @version 1.0
-*/
-class HTML_QuickForm_Rule_Range extends HTML_QuickForm_Rule
-{
- /**
- * Validates a value using a range comparison
- *
- * @param string $value Value to be checked
- * @param mixed $options Int for length, array for range
- * @access public
- * @return boolean true if value is valid
- */
- function validate($value, $options)
- {
- $length = strlen($value);
- switch ($this->name) {
- case 'minlength': return ($length >= $options);
- case 'maxlength': return ($length <= $options);
- default: return ($length >= $options[0] && $length <= $options[1]);
- }
- } // end func validate
-
-
- function getValidationScript($options = null)
- {
- switch ($this->name) {
- case 'minlength':
- $test = '{jsVar}.length < '.$options;
- break;
- case 'maxlength':
- $test = '{jsVar}.length > '.$options;
- break;
- default:
- $test = '({jsVar}.length < '.$options[0].' || {jsVar}.length > '.$options[1].')';
- }
- return array('', "{jsVar} != '' && {$test}");
- } // end func getValidationScript
-
-} // end class HTML_QuickForm_Rule_Range
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP version 4.0 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Bertrand Mansion <bmansion@mamasam.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Regex.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-require_once('HTML/QuickForm/Rule.php');
-
-/**
-* Validates values using regular expressions
-* @version 1.0
-*/
-class HTML_QuickForm_Rule_Regex extends HTML_QuickForm_Rule
-{
- /**
- * Array of regular expressions
- *
- * Array is in the format:
- * $_data['rulename'] = 'pattern';
- *
- * @var array
- * @access private
- */
- var $_data = array(
- 'lettersonly' => '/^[a-zA-Z]+$/',
- 'alphanumeric' => '/^[a-zA-Z0-9]+$/',
- 'numeric' => '/(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/',
- 'nopunctuation' => '/^[^().\/\*\^\?#!@$%+=,\"\'><~\[\]{}]+$/',
- 'nonzero' => '/^-?[1-9][0-9]*/'
- );
-
- /**
- * Validates a value using a regular expression
- *
- * @param string $value Value to be checked
- * @param string $regex Regular expression
- * @access public
- * @return boolean true if value is valid
- */
- function validate($value, $regex = null)
- {
- if (isset($this->_data[$this->name])) {
- if (!preg_match($this->_data[$this->name], $value)) {
- return false;
- }
- } else {
- if (!preg_match($regex, $value)) {
- return false;
- }
- }
- return true;
- } // end func validate
-
- /**
- * Adds new regular expressions to the list
- *
- * @param string $name Name of rule
- * @param string $pattern Regular expression pattern
- * @access public
- */
- function addData($name, $pattern)
- {
- $this->_data[$name] = $pattern;
- } // end func addData
-
-
- function getValidationScript($options = null)
- {
- $regex = isset($this->_data[$this->name]) ? $this->_data[$this->name] : $options;
-
- return array(" var regex = " . $regex . ";\n", "{jsVar} != '' && !regex.test({jsVar})");
- } // end func getValidationScript
-
-} // end class HTML_QuickForm_Rule_Regex
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP version 4.0 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Bertrand Mansion <bmansion@mamasam.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Required.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-require_once('HTML/QuickForm/Rule.php');
-
-/**
-* Required elements validation
-* @version 1.0
-*/
-class HTML_QuickForm_Rule_Required extends HTML_QuickForm_Rule
-{
- /**
- * Checks if an element is empty
- *
- * @param string $value Value to check
- * @param mixed $options Not used yet
- * @access public
- * @return boolean true if value is not empty
- */
- function validate($value, $options = null)
- {
- if ($value == '') {
- return false;
- }
- return true;
- } // end func validate
-
-
- function getValidationScript($options = null)
- {
- return array('', "{jsVar} == ''");
- } // end func getValidationScript
-
-} // end class HTML_QuickForm_Rule_Required
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP version 4.0 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Adam Daniel <adaniel1@eesus.jnj.com> |
-// | Alexey Borzov <borz_off@cs.msu.su> |
-// | Bertrand Mansion <bmansion@mamasam.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: RuleRegistry.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-/**
-* Registers rule objects and uses them for validation
-*
-*/
-class HTML_QuickForm_RuleRegistry
-{
- /**
- * Array containing references to used rules
- * @var array
- * @access private
- */
- var $_rules = array();
-
-
- /**
- * Returns a singleton of HTML_QuickForm_RuleRegistry
- *
- * Usually, only one RuleRegistry object is needed, this is the reason
- * why it is recommended to use this method to get the validation object.
- *
- * @access public
- * @static
- * @return object Reference to the HTML_QuickForm_RuleRegistry singleton
- */
- function &singleton()
- {
- static $obj;
- if (!isset($obj)) {
- $obj = new HTML_QuickForm_RuleRegistry();
- }
- return $obj;
- } // end func singleton
-
- /**
- * Registers a new validation rule
- *
- * In order to use a custom rule in your form, you need to register it
- * first. For regular expressions, one can directly use the 'regex' type
- * rule in addRule(), this is faster than registering the rule.
- *
- * Functions and methods can be registered. Use the 'function' type.
- * When registering a method, specify the class name as second parameter.
- *
- * You can also register an HTML_QuickForm_Rule subclass with its own
- * validate() method.
- *
- * @param string $ruleName Name of validation rule
- * @param string $type Either: 'regex', 'function' or null
- * @param string $data1 Name of function, regular expression or
- * HTML_QuickForm_Rule object class name
- * @param string $data2 Object parent of above function or HTML_QuickForm_Rule file path
- * @access public
- * @return void
- */
- function registerRule($ruleName, $type, $data1, $data2 = null)
- {
- $type = strtolower($type);
- if ($type == 'regex') {
- // Regular expression
- $rule =& $this->getRule('regex');
- $rule->addData($ruleName, $data1);
- $GLOBALS['_HTML_QuickForm_registered_rules'][$ruleName] = $GLOBALS['_HTML_QuickForm_registered_rules']['regex'];
-
- } elseif ($type == 'function' || $type == 'callback') {
- // Callback function
- $rule =& $this->getRule('callback');
- $rule->addData($ruleName, $data1, $data2, 'function' == $type);
- $GLOBALS['_HTML_QuickForm_registered_rules'][$ruleName] = $GLOBALS['_HTML_QuickForm_registered_rules']['callback'];
-
- } elseif (is_object($data1)) {
- // An instance of HTML_QuickForm_Rule
- $this->_rules[strtolower(get_class($data1))] = $data1;
- $GLOBALS['_HTML_QuickForm_registered_rules'][$ruleName] = array(strtolower(get_class($data1)), null);
-
- } else {
- // Rule class name
- $GLOBALS['_HTML_QuickForm_registered_rules'][$ruleName] = array(strtolower($data1), $data2);
- }
- } // end func registerRule
-
- /**
- * Returns a reference to the requested rule object
- *
- * @param string $ruleName Name of the requested rule
- * @access public
- * @return object
- */
- function &getRule($ruleName)
- {
- list($class, $path) = $GLOBALS['_HTML_QuickForm_registered_rules'][$ruleName];
-
- if (!isset($this->_rules[$class])) {
- if (!empty($path)) {
- include_once($path);
- }
- $this->_rules[$class] =& new $class();
- }
- $this->_rules[$class]->setName($ruleName);
- return $this->_rules[$class];
- } // end func getRule
-
- /**
- * Performs validation on the given values
- *
- * @param string $ruleName Name of the rule to be used
- * @param mixed $values Can be a scalar or an array of values
- * to be validated
- * @param mixed $options Options used by the rule
- * @param mixed $multiple Whether to validate an array of values altogether
- * @access public
- * @return mixed true if no error found, int of valid values (when an array of values is given) or false if error
- */
- function validate($ruleName, $values, $options = null, $multiple = false)
- {
- $rule =& $this->getRule($ruleName);
-
- if (is_array($values) && !$multiple) {
- $result = 0;
- foreach ($values as $value) {
- if ($rule->validate($value, $options) === true) {
- $result++;
- }
- }
- return ($result == 0) ? false : $result;
- } else {
- return $rule->validate($values, $options);
- }
- } // end func validate
-
- /**
- * Returns the validation test in javascript code
- *
- * @param mixed Element(s) the rule applies to
- * @param string Element name, in case $element is not array
- * @param array Rule data
- * @access public
- * @return string JavaScript for the rule
- */
- function getValidationScript(&$element, $elementName, $ruleData)
- {
- $reset = (isset($ruleData['reset'])) ? $ruleData['reset'] : false;
- $rule =& $this->getRule($ruleData['type']);
- if (!is_array($element)) {
- list($jsValue, $jsReset) = $this->_getJsValue($element, $elementName, $reset, null);
- } else {
- $jsValue = " value = new Array();\n";
- $jsReset = '';
- for ($i = 0; $i < count($element); $i++) {
- list($tmp_value, $tmp_reset) = $this->_getJsValue($element[$i], $element[$i]->getName(), $reset, $i);
- $jsValue .= "\n" . $tmp_value;
- $jsReset .= $tmp_reset;
- }
- }
- $jsField = isset($ruleData['group'])? $ruleData['group']: $elementName;
- list ($jsPrefix, $jsCheck) = $rule->getValidationScript($ruleData['format']);
- if (!isset($ruleData['howmany'])) {
- $js = $jsValue . "\n" . $jsPrefix .
- " if (" . str_replace('{jsVar}', 'value', $jsCheck) . " && !errFlag['{$jsField}']) {\n" .
- " errFlag['{$jsField}'] = true;\n" .
- " _qfMsg = _qfMsg + '\\n - {$ruleData['message']}';\n" .
- $jsReset .
- " }\n";
- } else {
- $js = $jsValue . "\n" . $jsPrefix .
- " var res = 0;\n" .
- " for (var i = 0; i < value.length; i++) {\n" .
- " if (!(" . str_replace('{jsVar}', 'value[i]', $jsCheck) . ")) {\n" .
- " res++;\n" .
- " }\n" .
- " }\n" .
- " if (res < {$ruleData['howmany']} && !errFlag['{$jsField}']) {\n" .
- " errFlag['{$jsField}'] = true;\n" .
- " _qfMsg = _qfMsg + '\\n - {$ruleData['message']}';\n" .
- $jsReset .
- " }\n";
- }
- return $js;
- } // end func getValidationScript
-
-
- /**
- * Returns JavaScript to get and to reset the element's value
- *
- * @access private
- * @param object HTML_QuickForm_element element being processed
- * @param string element's name
- * @param bool whether to generate JavaScript to reset the value
- * @param integer value's index in the array (only used for multielement rules)
- * @return array first item is value javascript, second is reset
- */
- function _getJsValue(&$element, $elementName, $reset = false, $index = null)
- {
- $jsIndex = isset($index)? '[' . $index . ']': '';
- $tmp_reset = $reset? " var field = frm.elements['$elementName'];\n": '';
- if (is_a($element, 'html_quickform_group')) {
- $value = " var {$elementName}Elements = '::";
- for ($i = 0, $count = count($element->_elements); $i < $count; $i++) {
- $value .= $element->getElementName($i) . '::';
- }
- $value .=
- "';\n" .
- " value{$jsIndex} = new Array();\n" .
- " var valueIdx = 0;\n" .
- " for (var i = 0; i < frm.elements.length; i++) {\n" .
- " var _element = frm.elements[i];\n" .
- " if ({$elementName}Elements.indexOf('::' + _element.name + '::') >= 0) {\n" .
- " switch (_element.type) {\n" .
- " case 'checkbox':\n" .
- " case 'radio':\n" .
- " if (_element.checked) {\n" .
- " value{$jsIndex}[valueIdx++] = _element.value;\n" .
- " }\n" .
- " break;\n" .
- " case 'select':\n" .
- " if (-1 != _element.selectedIndex) {\n" .
- " value{$jsIndex}[valueIdx++] = _element.options[_element.selectedIndex].value;\n" .
- " }\n" .
- " break;\n" .
- " default:\n" .
- " value{$jsIndex}[valueIdx++] = _element.value;\n" .
- " }\n" .
- " }\n" .
- " }\n";
- if ($reset) {
- $tmp_reset =
- " for (var i = 0; i < frm.elements.length; i++) {\n" .
- " var _element = frm.elements[i];\n" .
- " if ({$elementName}Elements.indexOf('::' + _element.name + '::') >= 0) {\n" .
- " switch (_element.type) {\n" .
- " case 'checkbox':\n" .
- " case 'radio':\n" .
- " _element.checked = _element.defaultChecked;\n" .
- " break;\n" .
- " case 'select':\n" .
- " for (var j = 0; j < _element.options.length; j++) {\n" .
- " _element.options[j].selected = _element.options[j].defaultSelected;\n" .
- " }\n" .
- " break;\n" .
- " default:\n" .
- " _element.value = _element.defaultValue;\n" .
- " }\n" .
- " }\n" .
- " }\n";
- }
-
- } elseif ($element->getType() == 'select') {
- if ($element->getMultiple()) {
- $elementName .= '[]';
- $value =
- " value{$jsIndex} = new Array();\n" .
- " var valueIdx = 0;\n" .
- " for (var i = 0; i < frm.elements['{$elementName}'].options.length; i++) {\n" .
- " if (frm.elements['{$elementName}'].options[i].selected) {\n" .
- " value{$jsIndex}[valueIdx++] = frm.elements['{$elementName}'].options[i].value;\n" .
- " }\n" .
- " }\n";
- } else {
- $value = " value{$jsIndex} = frm.elements['{$elementName}'].options[frm.elements['{$elementName}'].selectedIndex].value;\n";
- }
- if ($reset) {
- $tmp_reset .=
- " for (var i = 0; i < field.options.length; i++) {\n" .
- " field.options[i].selected = field.options[i].defaultSelected;\n" .
- " }\n";
- }
-
- } elseif ($element->getType() == 'checkbox') {
- $value = " if (frm.elements['$elementName'].checked) {\n" .
- " value{$jsIndex} = '1';\n" .
- " } else {\n" .
- " value{$jsIndex} = '';\n" .
- " }";
- $tmp_reset .= ($reset) ? " field.checked = field.defaultChecked;\n" : '';
-
- } elseif ($element->getType() == 'radio') {
- $value = " value{$jsIndex} = '';\n" .
- " for (var i = 0; i < frm.elements['$elementName'].length; i++) {\n" .
- " if (frm.elements['$elementName'][i].checked) {\n" .
- " value{$jsIndex} = frm.elements['$elementName'][i].value;\n" .
- " }\n" .
- " }";
- if ($reset) {
- $tmp_reset .= " for (var i = 0; i < field.length; i++) {\n" .
- " field[i].checked = field[i].defaultChecked;\n" .
- " }";
- }
-
- } else {
- $value = " value{$jsIndex} = frm.elements['$elementName'].value;";
- $tmp_reset .= ($reset) ? " field.value = field.defaultValue;\n" : '';
- }
- return array($value, $tmp_reset);
- }
-} // end class HTML_QuickForm_RuleRegistry
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP version 4.0 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997, 1998, 1999, 2000, 2001 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Adam Daniel <adaniel1@eesus.jnj.com> |
-// | Bertrand Mansion <bmansion@mamasam.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: advcheckbox.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-require_once('HTML/QuickForm/checkbox.php');
-
-/**
- * HTML class for an advanced checkbox type field
- *
- * Basically this fixes a problem that HTML has had
- * where checkboxes can only pass a single value (the
- * value of the checkbox when checked). A value for when
- * the checkbox is not checked cannot be passed, and
- * furthermore the checkbox variable doesn't even exist if
- * the checkbox was submitted unchecked.
- *
- * It works by creating a hidden field with the passed-in name
- * and creating the checkbox with no name, but with a javascript
- * onclick which sets the value of the hidden field.
- *
- * @author Jason Rust <jrust@php.net>
- * @since 2.0
- * @access public
- */
-class HTML_QuickForm_advcheckbox extends HTML_QuickForm_checkbox
-{
- // {{{ properties
-
- /**
- * The values passed by the hidden elment
- *
- * @var array
- * @access private
- */
- var $_values = null;
-
- /**
- * The default value
- *
- * @var boolean
- * @access private
- */
- var $_currentValue = null;
-
- // }}}
- // {{{ constructor
-
- /**
- * Class constructor
- *
- * @param string $elementName (optional)Input field name attribute
- * @param string $elementLabel (optional)Input field label
- * @param string $text (optional)Text to put after the checkbox
- * @param mixed $attributes (optional)Either a typical HTML attribute string
- * or an associative array
- * @param mixed $values (optional)Values to pass if checked or not checked
- *
- * @since 1.0
- * @access public
- * @return void
- */
- function HTML_QuickForm_advcheckbox($elementName=null, $elementLabel=null, $text=null, $attributes=null, $values=null)
- {
- $this->HTML_QuickForm_checkbox($elementName, $elementLabel, $text, $attributes);
- $this->setValues($values);
- } //end constructor
-
- // }}}
- // {{{ getPrivateName()
-
- /**
- * Gets the pribate name for the element
- *
- * @param string $elementName The element name to make private
- *
- * @access public
- * @return string
- */
- function getPrivateName($elementName)
- {
- return '__'.$elementName;
- }
-
- // }}}
- // {{{ getOnclickJs()
-
- /**
- * Create the javascript for the onclick event which will
- * set the value of the hidden field
- *
- * @param string $elementName The element name
- *
- * @access public
- * @return string
- */
- function getOnclickJs($elementName)
- {
- $onclickJs = 'if (this.checked) { this.form[\''.$elementName.'\'].value=\''.addcslashes($this->_values[1], '\'').'\'; }';
- $onclickJs .= 'else { this.form[\''.$elementName.'\'].value=\''.addcslashes($this->_values[0], '\'').'\'; }';
- return $onclickJs;
- }
-
- // }}}
- // {{{ setValues()
-
- /**
- * Sets the values used by the hidden element
- *
- * @param mixed $values The values, either a string or an array
- *
- * @access public
- * @return void
- */
- function setValues($values)
- {
- if (empty($values)) {
- // give it default checkbox behavior
- $this->_values = array('', 1);
- } elseif (is_scalar($values)) {
- // if it's string, then assume the value to
- // be passed is for when the element is checked
- $this->_values = array('', $values);
- } else {
- $this->_values = $values;
- }
- $this->setChecked($this->_currentValue == $this->_values[1]);
- }
-
- // }}}
- // {{{ setValue()
-
- /**
- * Sets the element's value
- *
- * @param mixed Element's value
- * @access public
- */
- function setValue($value)
- {
- $this->setChecked(isset($this->_values[1]) && $value == $this->_values[1]);
- $this->_currentValue = $value;
- }
-
- // }}}
- // {{{ getValue()
-
- /**
- * Returns the element's value
- *
- * @access public
- * @return mixed
- */
- function getValue()
- {
- if (is_array($this->_values)) {
- return $this->_values[$this->getChecked()? 1: 0];
- } else {
- return null;
- }
- }
-
- // }}}
- // {{{ toHtml()
-
- /**
- * Returns the checkbox element in HTML
- * and the additional hidden element in HTML
- *
- * @access public
- * @return string
- */
- function toHtml()
- {
- if ($this->_flagFrozen) {
- return parent::toHtml();
- } else {
- $oldName = $this->getName();
- $oldJs = $this->getAttribute('onclick');
- $this->updateAttributes(array(
- 'name' => $this->getPrivateName($oldName),
- 'onclick' => $this->getOnclickJs($oldName) . ' ' . $oldJs
- ));
- $html = parent::toHtml() . '<input type="hidden" name="' . $oldName .
- '" value="' . $this->getValue() . '" />';
- // revert the name and JS, in case this method will be called once more
- $this->updateAttributes(array(
- 'name' => $oldName,
- 'onclick' => $oldJs
- ));
- return $html;
- }
- } //end func toHtml
-
- // }}}
- // {{{ getFrozenHtml()
-
- /**
- * Unlike checkbox, this has to append a hidden input in both
- * checked and non-checked states
- */
- function getFrozenHtml()
- {
- return ($this->getChecked()? '<tt>[x]</tt>': '<tt>[ ]</tt>') .
- $this->_getPersistantData();
- }
-
- // }}}
- // {{{ onQuickFormEvent()
-
- /**
- * Called by HTML_QuickForm whenever form event is made on this element
- *
- * @param string $event Name of event
- * @param mixed $arg event arguments
- * @param object $caller calling object
- * @since 1.0
- * @access public
- * @return void
- */
- function onQuickFormEvent($event, $arg, &$caller)
- {
- switch ($event) {
- case 'updateValue':
- // constant values override both default and submitted ones
- // default values are overriden by submitted
- $value = $this->_findValue($caller->_constantValues);
- if (null === $value) {
- $value = $this->_findValue($caller->_submitValues);
- if (null === $value) {
- $value = $this->_findValue($caller->_defaultValues);
- }
- }
- if (null !== $value) {
- $this->setValue($value);
- }
- break;
- default:
- parent::onQuickFormEvent($event, $arg, $caller);
- }
- return true;
- } // end func onQuickFormLoad
-
- // }}}
- // {{{ exportValue()
-
- /**
- * This element has a value even if it is not checked, thus we override
- * checkbox's behaviour here
- */
- function exportValue(&$submitValues, $assoc)
- {
- $value = $this->_findValue($submitValues);
- if (null === $value) {
- $value = $this->getValue();
- } elseif (is_array($this->_values) && ($value != $this->_values[0]) && ($value != $this->_values[1])) {
- $value = null;
- }
- return $this->_prepareValue($value, $assoc);
- }
- // }}}
-} //end class HTML_QuickForm_advcheckbox
-?>
+++ /dev/null
-<?php
-/**
- * Copyright (c) 2005-2007, Laurent Laville <pear@laurent-laville.org>
- *
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * Neither the name of the authors nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- *
- * @category HTML
- * @package HTML_QuickForm_advmultiselect
- * @author Laurent Laville <pear@laurent-laville.org>
- * @copyright 2005-2007 Laurent Laville
- * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: advmultiselect.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_QuickForm_advmultiselect
- * @since File available since Release 0.4.0
- */
-
-require_once 'HTML/QuickForm/select.php';
-
-/**
- * Replace PHP_EOL constant
- *
- * category PHP
- * package PHP_Compat
- * @link http://php.net/reserved.constants.core
- * @author Aidan Lister <aidan@php.net>
- * @since PHP 5.0.2
- */
-if (!defined('PHP_EOL')) {
- switch (strtoupper(substr(PHP_OS, 0, 3))) {
- // Windows
- case 'WIN':
- define('PHP_EOL', "\r\n");
- break;
-
- // Mac
- case 'DAR':
- define('PHP_EOL', "\r");
- break;
-
- // Unix
- default:
- define('PHP_EOL', "\n");
- }
-}
-
-/**
- * Element for HTML_QuickForm that emulate a multi-select.
- *
- * The HTML_QuickForm_advmultiselect package adds an element to the
- * HTML_QuickForm package that is two select boxes next to each other
- * emulating a multi-select.
- *
- * @category HTML
- * @package HTML_QuickForm_advmultiselect
- * @author Laurent Laville <pear@laurent-laville.org>
- * @copyright 2005-2007 Laurent Laville
- * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
- * @version Release: @package_version@
- * @link http://pear.php.net/package/HTML_QuickForm_advmultiselect
- * @since Class available since Release 0.4.0
- */
-class HTML_QuickForm_advmultiselect extends HTML_QuickForm_select
-{
- /**
- * Prefix function name in javascript move selections
- *
- * @var string
- * @access private
- * @since 0.4.0
- */
- var $_jsPrefix;
-
- /**
- * Postfix function name in javascript move selections
- *
- * @var string
- * @access private
- * @since 0.4.0
- */
- var $_jsPostfix;
-
- /**
- * Associative array of the multi select container attributes
- *
- * @var array
- * @access private
- * @since 0.4.0
- */
- var $_tableAttributes;
-
- /**
- * Associative array of the add button attributes
- *
- * @var array
- * @access private
- * @since 0.4.0
- */
- var $_addButtonAttributes;
-
- /**
- * Associative array of the remove button attributes
- *
- * @var array
- * @access private
- * @since 0.4.0
- */
- var $_removeButtonAttributes;
-
- /**
- * Associative array of the select all button attributes
- *
- * @var array
- * @access private
- * @since 1.1.0
- */
- var $_allButtonAttributes;
-
- /**
- * Associative array of the select none button attributes
- *
- * @var array
- * @access private
- * @since 1.1.0
- */
- var $_noneButtonAttributes;
-
- /**
- * Associative array of the toggle selection button attributes
- *
- * @var array
- * @access private
- * @since 1.1.0
- */
- var $_toggleButtonAttributes;
-
- /**
- * Associative array of the move up button attributes
- *
- * @var array
- * @access private
- * @since 0.5.0
- */
- var $_upButtonAttributes;
-
- /**
- * Associative array of the move up button attributes
- *
- * @var array
- * @access private
- * @since 0.5.0
- */
- var $_downButtonAttributes;
-
- /**
- * Defines if both list (unselected, selected) will have their elements be
- * arranged from lowest to highest (or reverse) depending on comparaison function.
- *
- * SORT_ASC is used to sort in ascending order
- * SORT_DESC is used to sort in descending order
- *
- * @var string ('none' == false, 'asc' == SORT_ASC, 'desc' == SORT_DESC)
- * @access private
- * @since 0.5.0
- */
- var $_sort;
-
- /**
- * Associative array of the unselected item box attributes
- *
- * @var array
- * @access private
- * @since 0.4.0
- */
- var $_attributesUnselected;
-
- /**
- * Associative array of the selected item box attributes
- *
- * @var array
- * @access private
- * @since 0.4.0
- */
- var $_attributesSelected;
-
- /**
- * Associative array of the internal hidden box attributes
- *
- * @var array
- * @access private
- * @since 0.4.0
- */
- var $_attributesHidden;
-
- /**
- * Default Element template string
- *
- * @var string
- * @access private
- * @since 0.4.0
- */
- var $_elementTemplate = '
-{javascript}
-<table{class}>
-<!-- BEGIN label_2 --><tr><th>{label_2}</th><!-- END label_2 -->
-<!-- BEGIN label_3 --><th> </th><th>{label_3}</th></tr><!-- END label_3 -->
-<tr>
- <td valign="top">{unselected}</td>
- <td align="center">{add}{remove}</td>
- <td valign="top">{selected}</td>
-</tr>
-</table>
-';
-
- /**
- * Default Element stylesheet string
- *
- * @var string
- * @access private
- * @since 0.4.0
- */
- var $_elementCSS = '
-#qfams_{id} {
- font: 13.3px sans-serif;
- background-color: #fff;
- overflow: auto;
- height: 14.3em;
- width: 12em;
- border-left: 1px solid #404040;
- border-top: 1px solid #404040;
- border-bottom: 1px solid #d4d0c8;
- border-right: 1px solid #d4d0c8;
-}
-#qfams_{id} label {
- padding-right: 3px;
- display: block;
-}
-';
-
- /**
- * Class constructor
- *
- * @param string $elementName Dual Select name attribute
- * @param mixed $elementLabel Label(s) for the select boxes
- * @param mixed $options Data to be used to populate options
- * @param mixed $attributes Either a typical HTML attribute string or an associative array
- * @param integer $sort Either SORT_ASC for auto ascending arrange,
- * SORT_DESC for auto descending arrange, or
- * NULL for no sort (append at end: default)
- *
- * @access public
- * @return void
- * @since 0.4.0
- */
- function HTML_QuickForm_advmultiselect($elementName = null, $elementLabel = null,
- $options = null, $attributes = null,
- $sort = null)
- {
- $this->HTML_QuickForm_select($elementName, $elementLabel, $options, $attributes);
-
- // add multiple selection attribute by default if missing
- $this->updateAttributes(array('multiple' => 'multiple'));
-
- if (is_null($this->getAttribute('size'))) {
- // default size is ten item on each select box (left and right)
- $this->updateAttributes(array('size' => 10));
- }
- if (is_null($this->getAttribute('style'))) {
- // default width of each select box
- $this->updateAttributes(array('style' => 'width:100px;'));
- }
- $this->_tableAttributes = $this->getAttribute('class');
- if (is_null($this->_tableAttributes)) {
- // default table layout
- $attr = array('border' => '0', 'cellpadding' => '10', 'cellspacing' => '0');
- } else {
- $attr = array('class' => $this->_tableAttributes);
- $this->_removeAttr('class', $this->_attributes);
- }
- $this->_tableAttributes = $this->_getAttrString($attr);
-
- // set default add button attributes
- $this->setButtonAttributes('add');
- // set default remove button attributes
- $this->setButtonAttributes('remove');
- // set default selectall button attributes
- $this->setButtonAttributes('all');
- // set default selectnone button attributes
- $this->setButtonAttributes('none');
- // set default toggle selection button attributes
- $this->setButtonAttributes('toggle');
- // set default move up button attributes
- $this->setButtonAttributes('moveup');
- // set default move up button attributes
- $this->setButtonAttributes('movedown');
- // defines javascript functions names
- $this->setJsElement();
-
- // set select boxes sort order (none by default)
- if (!isset($sort)) {
- $sort = false;
- }
- if ($sort === SORT_ASC) {
- $this->_sort = 'asc';
- } elseif ($sort === SORT_DESC) {
- $this->_sort = 'desc';
- } else {
- $this->_sort = 'none';
- }
- }
-
- /**
- * Sets the button attributes
- *
- * In <b>custom example 1</b>, the <i>add</i> and <i>remove</i> buttons have look set
- * by the css class <i>inputCommand</i>. See especially lines 43-48 and 98-103.
- *
- * In <b>custom example 2</b>, the basic text <i>add</i> and <i>remove</i> buttons
- * are now replaced by images. See lines 43-44.
- *
- * In <b>custom example 5</b>, we have ability to sort the selection list (on right side)
- * by :
- * <pre>
- * - <b>user-end</b>: with <i>Up</i> and <i>Down</i> buttons
- * (see lines 65,65,76 and 128-130)
- * - <b>programming</b>: with the QF element constructor $sort option
- * (see lines 34,36,38 and 59)
- * </pre>
- *
- * @example examples/qfams_custom_5.php Custom example 5: source code
- * @link http://www.laurent-laville.org/img/qfams/screenshot/custom5.png Custom example 5: screenshot
- *
- * @example examples/qfams_custom_2.php Custom example 2: source code
- * @link http://www.laurent-laville.org/img/qfams/screenshot/custom2.png Custom example 2: screenshot
- *
- * @example examples/qfams_custom_1.php Custom example 1: source code
- * @link http://www.laurent-laville.org/img/qfams/screenshot/custom1.png Custom example 1: screenshot
- *
- * @param string $button Button identifier, either 'add', 'remove',
- * 'all', 'none', 'toggle',
- * 'moveup' or 'movedown'
- * @param mixed $attributes (optional) Either a typical HTML attribute string
- * or an associative array
- * @throws PEAR_Error $button argument
- * is not a string
- * or not in range (add, remove, all, none, toggle, moveup, movedown)
- * @access public
- * @since 0.4.0
- */
- function setButtonAttributes($button, $attributes = null)
- {
- if (!is_string($button)) {
- return PEAR::raiseError('Argument 1 of advmultiselect::setButtonAttributes'
- .' is not a string');
- }
-
- switch ($button) {
- case 'add':
- if (is_null($attributes)) {
- $this->_addButtonAttributes = array('name' => 'add',
- 'value' => ' >> ',
- 'type' => 'button'
- );
- } else {
- $this->_updateAttrArray($this->_addButtonAttributes,
- $this->_parseAttributes($attributes)
- );
- }
- break;
- case 'remove':
- if (is_null($attributes)) {
- $this->_removeButtonAttributes = array('name' => 'remove',
- 'value' => ' << ',
- 'type' => 'button'
- );
- } else {
- $this->_updateAttrArray($this->_removeButtonAttributes,
- $this->_parseAttributes($attributes)
- );
- }
- break;
- case 'all':
- if (is_null($attributes)) {
- $this->_allButtonAttributes = array('name' => 'all',
- 'value' => ' Select All ',
- 'type' => 'button'
- );
- } else {
- $this->_updateAttrArray($this->_allButtonAttributes,
- $this->_parseAttributes($attributes)
- );
- }
- break;
- case 'none':
- if (is_null($attributes)) {
- $this->_noneButtonAttributes = array('name' => 'none',
- 'value' => ' Select None ',
- 'type' => 'button'
- );
- } else {
- $this->_updateAttrArray($this->_noneButtonAttributes,
- $this->_parseAttributes($attributes)
- );
- }
- break;
- case 'toggle':
- if (is_null($attributes)) {
- $this->_toggleButtonAttributes = array('name' => 'toggle',
- 'value' => ' Toggle Selection ',
- 'type' => 'button'
- );
- } else {
- $this->_updateAttrArray($this->_toggleButtonAttributes,
- $this->_parseAttributes($attributes)
- );
- }
- break;
- case 'moveup':
- if (is_null($attributes)) {
- $this->_upButtonAttributes = array('name' => 'up',
- 'value' => ' Up ',
- 'type' => 'button'
- );
- } else {
- $this->_updateAttrArray($this->_upButtonAttributes,
- $this->_parseAttributes($attributes)
- );
- }
- break;
- case 'movedown':
- if (is_null($attributes)) {
- $this->_downButtonAttributes = array('name' => 'down',
- 'value' => ' Down ',
- 'type' => 'button'
- );
- } else {
- $this->_updateAttrArray($this->_downButtonAttributes,
- $this->_parseAttributes($attributes)
- );
- }
- break;
- default;
- return PEAR::raiseError('Argument 1 of advmultiselect::setButtonAttributes'
- .' has unexpected value');
- }
- }
-
- /**
- * Sets element template
- *
- * @param string $html The HTML surrounding select boxes and buttons
- *
- * @access public
- * @return void
- * @since 0.4.0
- */
- function setElementTemplate($html)
- {
- $this->_elementTemplate = $html;
- }
-
- /**
- * Sets JavaScript function name parts. Maybe usefull to avoid conflict names
- *
- * In <b>multiple example 1</b>, the javascript function prefix is set to not null
- * (see line 60).
- *
- * @example examples/qfams_multiple_1.php Multiple example 1: source code
- * @link http://www.laurent-laville.org/img/qfams/screenshot/multiple1.png Multiple example 1: screenshot
- *
- * @param string $pref (optional) Prefix name
- * @param string $post (optional) Postfix name
- *
- * @access public
- * @return void
- * @see getElementJs()
- * @since 0.4.0
- * @deprecated since version 1.3.0
- */
- function setJsElement($pref = null, $post = 'moveSelections')
- {
- $this->_jsPrefix = 'qfams';
- $this->_jsPostfix = 'MoveSelection';
- }
-
- /**
- * Gets default element stylesheet for a single multi-select shape render
- *
- * In <b>custom example 4</b>, the template defined lines 80-87 allows
- * a single multi-select checkboxes shape. Useful when javascript is disabled
- * (or when browser is not js compliant). In our example, no need to add javascript code
- * (see lines 170-172), but css is mandatory (see line 142).
- *
- * @example qfams_custom_4.php Custom example 4: source code
- * @link http://www.laurent-laville.org/img/qfams/screenshot/custom4.png Custom example 4: screenshot
- *
- * @param boolean $raw (optional) html output with style tags or just raw data
- *
- * @access public
- * @return string
- * @since 0.4.0
- */
- function getElementCss($raw = true)
- {
- $id = $this->getAttribute('name');
- $css = str_replace('{id}', $id, $this->_elementCSS);
-
- if ($raw !== true) {
- $css = '<style type="text/css">' . PHP_EOL
- . '<!--' . $css . '// -->' . PHP_EOL
- . '</style>';
- }
- return $css;
- }
-
- /**
- * Returns the HTML generated for the advanced mutliple select component
- *
- * @access public
- * @return string
- * @since 0.4.0
- */
- function toHtml()
- {
- if ($this->_flagFrozen) {
- return $this->getFrozenHtml();
- }
-
- $tabs = $this->_getTabs();
- $tab = $this->_getTab();
- $strHtml = '';
-
- if ($this->getComment() != '') {
- $strHtml .= $tabs . '<!-- ' . $this->getComment() . " //-->" . PHP_EOL;
- }
-
- $selectId = $this->getName();
- $selectName = $this->getName() . '[]';
- $selected_count = 0;
-
- // placeholder {unselected} existence determines if we will render
- if (strpos($this->_elementTemplate, '{unselected}') === false) {
- // ... a single multi-select with checkboxes
- $this->_jsPostfix = 'EditSelection';
-
- $id = $this->getAttribute('name');
-
- $strHtmlSelected = $tab . '<div id="qfams_'.$id.'">' . PHP_EOL;
- $unselected_count = count($this->_options);
-
- foreach ($this->_options as $option) {
-
- $_labelAttributes = array('style', 'class', 'onmouseover', 'onmouseout');
- $labelAttributes = array();
- foreach ($_labelAttributes as $attr) {
- if (isset($option['attr'][$attr])) {
- $labelAttributes[$attr] = $option['attr'][$attr];
- unset($option['attr'][$attr]);
- }
- }
-
- if (is_array($this->_values) && in_array((string)$option['attr']['value'], $this->_values)) {
- // The items is *selected*
- $checked = ' checked="checked"';
- $selected_count++;
- } else {
- // The item is *unselected* so we want to put it
- $checked = '';
- }
- $strHtmlSelected .= $tab
- . '<label'
- . $this->_getAttrString($labelAttributes) .'>'
- . '<input type="checkbox"'
- . ' id="'.$this->getName().'"'
- . ' name="'.$selectName.'"'
- . $checked
- . $this->_getAttrString($option['attr'])
- . ' />' . $option['text'] . '</label>'
- . PHP_EOL;
- }
- $strHtmlSelected .= $tab . '</div>'. PHP_EOL;
-
- $strHtmlHidden = '';
- $strHtmlUnselected = '';
- $strHtmlAdd = '';
- $strHtmlRemove = '';
-
- // build the select all button with all its attributes
- $attributes = array('onclick' => "{$this->_jsPrefix}{$this->_jsPostfix}('". $this->getName() ."', 1);");
- $this->_allButtonAttributes = array_merge($this->_allButtonAttributes, $attributes);
- $attrStrAll = $this->_getAttrString($this->_allButtonAttributes);
- $strHtmlAll = "<input$attrStrAll />". PHP_EOL;
-
- // build the select none button with all its attributes
- $attributes = array('onclick' => "{$this->_jsPrefix}{$this->_jsPostfix}('". $this->getName() ."', 0);");
- $this->_noneButtonAttributes = array_merge($this->_noneButtonAttributes, $attributes);
- $attrStrNone = $this->_getAttrString($this->_noneButtonAttributes);
- $strHtmlNone = "<input$attrStrNone />". PHP_EOL;
-
- // build the toggle selection button with all its attributes
- $attributes = array('onclick' => "{$this->_jsPrefix}{$this->_jsPostfix}('". $this->getName() ."', 2);");
- $this->_toggleButtonAttributes = array_merge($this->_toggleButtonAttributes, $attributes);
- $attrStrToggle = $this->_getAttrString($this->_toggleButtonAttributes);
- $strHtmlToggle = "<input$attrStrToggle />". PHP_EOL;
-
- $strHtmlMoveUp = '';
- $strHtmlMoveDown = '';
-
- // default selection counters
- $strHtmlSelectedCount = $selected_count . '/' . $unselected_count;
- } else {
- // ... or a dual multi-select
- $this->_jsPostfix = 'MoveSelection';
-
- // set name of Select From Box
- $this->_attributesUnselected = array('id' => '__'.$selectId, 'name' => '__'.$selectName, 'ondblclick' => "{$this->_jsPrefix}{$this->_jsPostfix}('{$selectId}', this.form.elements['__" . $selectName . "'], this.form.elements['_" . $selectName . "'], this.form.elements['" . $selectName . "'], 'add', '{$this->_sort}')");
- $this->_attributesUnselected = array_merge($this->_attributes, $this->_attributesUnselected);
- $attrUnselected = $this->_getAttrString($this->_attributesUnselected);
-
- // set name of Select To Box
- $this->_attributesSelected = array('id' => '_'.$selectId, 'name' => '_'.$selectName, 'ondblclick' => "{$this->_jsPrefix}{$this->_jsPostfix}('{$selectId}', this.form.elements['__" . $selectName . "'], this.form.elements['_" . $selectName . "'], this.form.elements['" . $selectName . "'], 'remove', '{$this->_sort}')");
- $this->_attributesSelected = array_merge($this->_attributes, $this->_attributesSelected);
- $attrSelected = $this->_getAttrString($this->_attributesSelected);
-
- // set name of Select hidden Box
- $this->_attributesHidden = array('name' => $selectName, 'style' => 'overflow: hidden; visibility: hidden; width: 1px; height: 0;');
- $this->_attributesHidden = array_merge($this->_attributes, $this->_attributesHidden);
- $attrHidden = $this->_getAttrString($this->_attributesHidden);
-
- // prepare option tables to be displayed as in POST order
- $append = count($this->_values);
- if ($append > 0) {
- $arrHtmlSelected = array_fill(0, $append, ' ');
- } else {
- $arrHtmlSelected = array();
- }
-
- $options = count($this->_options);
- $arrHtmlUnselected = array();
- if ($options > 0) {
- $arrHtmlHidden = array_fill(0, $options, ' ');
-
- foreach ($this->_options as $option) {
- if (is_array($this->_values) &&
- in_array((string)$option['attr']['value'], $this->_values)) {
- // Get the post order
- $key = array_search($option['attr']['value'], $this->_values);
-
- // The items is *selected* so we want to put it in the 'selected' multi-select
- $arrHtmlSelected[$key] = $option;
- // Add it to the 'hidden' multi-select and set it as 'selected'
- $option['attr']['selected'] = 'selected';
- $arrHtmlHidden[$key] = $option;
- } else {
- // The item is *unselected* so we want to put it in the 'unselected' multi-select
- $arrHtmlUnselected[] = $option;
- // Add it to the hidden multi-select as 'unselected'
- $arrHtmlHidden[$append] = $option;
- $append++;
- }
- }
- } else {
- $arrHtmlHidden = array();
- }
-
- // The 'unselected' multi-select which appears on the left
- $strHtmlUnselected = "<select$attrUnselected>". PHP_EOL;
- $unselected_count = count($arrHtmlUnselected);
- if ($unselected_count > 0) {
- foreach ($arrHtmlUnselected as $data) {
- $strHtmlUnselected .= $tabs . $tab
- . '<option' . $this->_getAttrString($data['attr']) . '>'
- . $data['text'] . '</option>' . PHP_EOL;
- }
- }
- $strHtmlUnselected .= '</select>';
-
- // The 'selected' multi-select which appears on the right
- $strHtmlSelected = "<select$attrSelected>". PHP_EOL;
- $selected_count = count($arrHtmlSelected);
- if ($selected_count > 0) {
- foreach ($arrHtmlSelected as $data) {
- $strHtmlSelected .= $tabs . $tab
- . '<option' . $this->_getAttrString($data['attr']) . '>'
- . $data['text'] . '</option>' . PHP_EOL;
- }
- }
- $strHtmlSelected .= '</select>';
-
- // The 'hidden' multi-select
- $strHtmlHidden = "<select$attrHidden>". PHP_EOL;
- if (count($arrHtmlHidden) > 0) {
- foreach ($arrHtmlHidden as $data) {
- $strHtmlHidden .= $tabs . $tab
- . '<option' . $this->_getAttrString($data['attr']) . '>'
- . $data['text'] . '</option>' . PHP_EOL;
- }
- }
- $strHtmlHidden .= '</select>';
-
- // build the remove button with all its attributes
- $attributes = array('onclick' => "{$this->_jsPrefix}{$this->_jsPostfix}('{$selectId}', this.form.elements['__" . $selectName . "'], this.form.elements['_" . $selectName . "'], this.form.elements['" . $selectName . "'], 'remove', '{$this->_sort}'); return false;");
- $this->_removeButtonAttributes = array_merge($this->_removeButtonAttributes, $attributes);
- $attrStrRemove = $this->_getAttrString($this->_removeButtonAttributes);
- $strHtmlRemove = "<input$attrStrRemove />". PHP_EOL;
-
- // build the add button with all its attributes
- $attributes = array('onclick' => "{$this->_jsPrefix}{$this->_jsPostfix}('{$selectId}', this.form.elements['__" . $selectName . "'], this.form.elements['_" . $selectName . "'], this.form.elements['" . $selectName . "'], 'add', '{$this->_sort}'); return false;");
- $this->_addButtonAttributes = array_merge($this->_addButtonAttributes, $attributes);
- $attrStrAdd = $this->_getAttrString($this->_addButtonAttributes);
- $strHtmlAdd = "<input$attrStrAdd />". PHP_EOL;
-
- // build the select all button with all its attributes
- $attributes = array('onclick' => "{$this->_jsPrefix}{$this->_jsPostfix}('{$selectId}', this.form.elements['__" . $selectName . "'], this.form.elements['_" . $selectName . "'], this.form.elements['" . $selectName . "'], 'all', '{$this->_sort}'); return false;");
- $this->_allButtonAttributes = array_merge($this->_allButtonAttributes, $attributes);
- $attrStrAll = $this->_getAttrString($this->_allButtonAttributes);
- $strHtmlAll = "<input$attrStrAll />". PHP_EOL;
-
- // build the select none button with all its attributes
- $attributes = array('onclick' => "{$this->_jsPrefix}{$this->_jsPostfix}('{$selectId}', this.form.elements['__" . $selectName . "'], this.form.elements['_" . $selectName . "'], this.form.elements['" . $selectName . "'], 'none', '{$this->_sort}'); return false;");
- $this->_noneButtonAttributes = array_merge($this->_noneButtonAttributes, $attributes);
- $attrStrNone = $this->_getAttrString($this->_noneButtonAttributes);
- $strHtmlNone = "<input$attrStrNone />". PHP_EOL;
-
- // build the toggle button with all its attributes
- $attributes = array('onclick' => "{$this->_jsPrefix}{$this->_jsPostfix}('{$selectId}', this.form.elements['__" . $selectName . "'], this.form.elements['_" . $selectName . "'], this.form.elements['" . $selectName . "'], 'toggle', '{$this->_sort}'); return false;");
- $this->_toggleButtonAttributes = array_merge($this->_toggleButtonAttributes, $attributes);
- $attrStrToggle = $this->_getAttrString($this->_toggleButtonAttributes);
- $strHtmlToggle = "<input$attrStrToggle />". PHP_EOL;
-
- // build the move up button with all its attributes
- $attributes = array('onclick' => "{$this->_jsPrefix}MoveUp(this.form.elements['_" . $selectName . "'], this.form.elements['" . $selectName . "']); return false;");
- $this->_upButtonAttributes = array_merge($this->_upButtonAttributes, $attributes);
- $attrStrUp = $this->_getAttrString($this->_upButtonAttributes);
- $strHtmlMoveUp = "<input$attrStrUp />". PHP_EOL;
-
- // build the move down button with all its attributes
- $attributes = array('onclick' => "{$this->_jsPrefix}MoveDown(this.form.elements['_" . $selectName . "'], this.form.elements['" . $selectName . "']); return false;");
- $this->_downButtonAttributes = array_merge($this->_downButtonAttributes, $attributes);
- $attrStrDown = $this->_getAttrString($this->_downButtonAttributes);
- $strHtmlMoveDown = "<input$attrStrDown />". PHP_EOL;
-
- // default selection counters
- $strHtmlSelectedCount = $selected_count;
- }
- $strHtmlUnselectedCount = $unselected_count;
-
- $strHtmlSelectedCountId = $this->getName() .'_selected';
- $strHtmlUnselectedCountId = $this->getName() .'_unselected';
-
- // render all part of the multi select component with the template
- $strHtml = $this->_elementTemplate;
-
- // Prepare multiple labels
- $labels = $this->getLabel();
- if (is_array($labels)) {
- array_shift($labels);
- }
- // render extra labels, if any
- if (is_array($labels)) {
- foreach($labels as $key => $text) {
- $key = is_int($key)? $key + 2: $key;
- $strHtml = str_replace("{label_{$key}}", $text, $strHtml);
- $strHtml = str_replace("<!-- BEGIN label_{$key} -->", '', $strHtml);
- $strHtml = str_replace("<!-- END label_{$key} -->", '', $strHtml);
- }
- }
- // clean up useless label tags
- if (strpos($strHtml, '{label_')) {
- $strHtml = preg_replace('/\s*<!-- BEGIN label_(\S+) -->.*<!-- END label_\1 -->\s*/i', '', $strHtml);
- }
-
- $placeHolders = array(
- '{stylesheet}', '{javascript}', '{class}',
- '{unselected_count_id}', '{selected_count_id}',
- '{unselected_count}', '{selected_count}',
- '{unselected}', '{selected}',
- '{add}', '{remove}',
- '{all}', '{none}', '{toggle}',
- '{moveup}', '{movedown}'
- );
- $htmlElements = array(
- $this->getElementCss(false), $this->getElementJs(false), $this->_tableAttributes,
- $strHtmlUnselectedCountId, $strHtmlSelectedCountId,
- $strHtmlUnselectedCount, $strHtmlSelectedCount,
- $strHtmlUnselected, $strHtmlSelected . $strHtmlHidden,
- $strHtmlAdd, $strHtmlRemove,
- $strHtmlAll, $strHtmlNone, $strHtmlToggle,
- $strHtmlMoveUp, $strHtmlMoveDown
- );
-
- $strHtml = str_replace($placeHolders, $htmlElements, $strHtml);
-
- return $strHtml;
- }
-
- /**
- * Returns the javascript code generated to handle this element
- *
- * @param boolean $raw (optional) html output with script tags or just raw data
- *
- * @access public
- * @return string
- * @see setJsElement()
- * @since 0.4.0
- */
- function getElementJs($raw = true)
- {
- $js = '@data_dir@' . DIRECTORY_SEPARATOR
- . '@package_name@' . DIRECTORY_SEPARATOR
- . 'qfamsHandler.js';
-
- if (file_exists($js)) {
- $js = file_get_contents($js);
- } else {
- $js = '';
- }
-
- if ($raw !== true) {
- $js = '<script type="text/javascript">'
- . PHP_EOL . '//<![CDATA['
- . PHP_EOL . $js
- . PHP_EOL . '//]]>'
- . PHP_EOL . '</script>'
- . PHP_EOL;
- }
- return $js;
- }
-}
-
-if (class_exists('HTML_QuickForm')) {
- HTML_QuickForm::registerElementType('advmultiselect', 'HTML/QuickForm/advmultiselect.php', 'HTML_QuickForm_advmultiselect');
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Matteo Di Giovinazzo <matteodg@infinito.it> |
-// | |
-// | For the JavaScript code thanks to Martin Honnen and |
-// | Nicholas C. Zakas |
-// | See: |
-// | http://www.faqts.com/knowledge_base/view.phtml/aid/13562 |
-// | and |
-// | http://www.sitepoint.com/article/1220 |
-// +----------------------------------------------------------------------+
-//
-// $Id: autocomplete.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-
-require_once("HTML/QuickForm/text.php");
-
-
-/**
- * Class to dynamically create an HTML input text element that
- * at every keypressed javascript event, check in an array of options
- * if there's a match and autocomplete the text in case of match.
- *
- * Ex:
- * $autocomplete =& $form->addElement('autocomplete', 'fruit', 'Favourite fruit:');
- * $options = array("Apple", "Orange", "Pear", "Strawberry");
- * $autocomplete->setOptions($options);
- *
- * @author Matteo Di Giovinazzo <matteodg@infinito.it>
- */
-class HTML_QuickForm_autocomplete extends HTML_QuickForm_text
-{
- // {{{ properties
-
- /**
- * Options for the autocomplete input text element
- *
- * @var array
- * @access private
- */
- var $_options = array();
-
- // }}}
- // {{{ constructor
-
- /**
- * Class constructor
- *
- * @param string $elementName (optional)Input field name attribute
- * @param string $elementLabel (optional)Input field label in form
- * @param array $options (optional)Autocomplete options
- * @param mixed $attributes (optional)Either a typical HTML attribute string
- * or an associative array. Date format is passed along the attributes.
- * @access public
- * @return void
- */
- function HTML_QuickForm_autocomplete($elementName = null, $elementLabel = null, $options = null, $attributes = null)
- {
- $this->HTML_QuickForm_text($elementName, $elementLabel, $attributes);
- $this->_persistantFreeze = true;
- $this->_type = 'autocomplete';
- if (isset($options)) {
- $this->setOptions($options);
- }
- } //end constructor
-
- // }}}
- // {{{ setOptions()
-
- /**
- * Sets the options for the autocomplete input text element
- *
- * @param array $options Array of options for the autocomplete input text element
- * @access public
- * @return void
- */
- function setOptions($options)
- {
- $this->_options = array_values($options);
- } // end func setOptions
-
- // }}}
- // {{{ toHtml()
-
- /**
- * Returns Html for the autocomplete input text element
- *
- * @access public
- * @return string
- */
- function toHtml()
- {
- // prevent problems with grouped elements
- $arrayName = str_replace(array('[', ']'), array('__', ''), $this->getName()) . '_values';
-
- $this->updateAttributes(array(
- 'onkeypress' => 'return autocomplete(this, event, ' . $arrayName . ');'
- ));
- if ($this->_flagFrozen) {
- $js = '';
- } else {
- $js = "<script type=\"text/javascript\">\n//<![CDATA[\n";
- if (!defined('HTML_QUICKFORM_AUTOCOMPLETE_EXISTS')) {
- $js .= <<<EOS
-
-/* begin javascript for autocomplete */
-function setSelectionRange(input, selectionStart, selectionEnd) {
- if (input.setSelectionRange) {
- input.setSelectionRange(selectionStart, selectionEnd);
- }
- else if (input.createTextRange) {
- var range = input.createTextRange();
- range.collapse(true);
- range.moveEnd("character", selectionEnd);
- range.moveStart("character", selectionStart);
- range.select();
- }
- input.focus();
-}
-
-function setCaretToPosition(input, position) {
- setSelectionRange(input, position, position);
-}
-
-function replaceSelection (input, replaceString) {
- var len = replaceString.length;
- if (input.setSelectionRange) {
- var selectionStart = input.selectionStart;
- var selectionEnd = input.selectionEnd;
-
- input.value = input.value.substring(0, selectionStart) + replaceString + input.value.substring(selectionEnd);
- input.selectionStart = selectionStart + len;
- input.selectionEnd = selectionStart + len;
- }
- else if (document.selection) {
- var range = document.selection.createRange();
- var saved_range = range.duplicate();
-
- if (range.parentElement() == input) {
- range.text = replaceString;
- range.moveEnd("character", saved_range.selectionStart + len);
- range.moveStart("character", saved_range.selectionStart + len);
- range.select();
- }
- }
- input.focus();
-}
-
-
-function autocompleteMatch (text, values) {
- for (var i = 0; i < values.length; i++) {
- if (values[i].toUpperCase().indexOf(text.toUpperCase()) == 0) {
- return values[i];
- }
- }
-
- return null;
-}
-
-function autocomplete(textbox, event, values) {
- if (textbox.setSelectionRange || textbox.createTextRange) {
- switch (event.keyCode) {
- case 38: // up arrow
- case 40: // down arrow
- case 37: // left arrow
- case 39: // right arrow
- case 33: // page up
- case 34: // page down
- case 36: // home
- case 35: // end
- case 13: // enter
- case 9: // tab
- case 27: // esc
- case 16: // shift
- case 17: // ctrl
- case 18: // alt
- case 20: // caps lock
- case 8: // backspace
- case 46: // delete
- return true;
- break;
-
- default:
- var c = String.fromCharCode(
- (event.charCode == undefined) ? event.keyCode : event.charCode
- );
- replaceSelection(textbox, c);
- sMatch = autocompleteMatch(textbox.value, values);
- var len = textbox.value.length;
-
- if (sMatch != null) {
- textbox.value = sMatch;
- setSelectionRange(textbox, len, textbox.value.length);
- }
- return false;
- }
- }
- else {
- return true;
- }
-}
-/* end javascript for autocomplete */
-
-EOS;
- define('HTML_QUICKFORM_AUTOCOMPLETE_EXISTS', true);
- }
- $jsEscape = array(
- "\r" => '\r',
- "\n" => '\n',
- "\t" => '\t',
- "'" => "\\'",
- '"' => '\"',
- '\\' => '\\\\'
- );
-
- $js .= 'var ' . $arrayName . " = new Array();\n";
- for ($i = 0; $i < count($this->_options); $i++) {
- $js .= $arrayName . '[' . $i . "] = '" . strtr($this->_options[$i], $jsEscape) . "';\n";
- }
- $js .= "//]]>\n</script>";
- }
- return $js . parent::toHtml();
- }// end func toHtml
-
- // }}}
-} // end class HTML_QuickForm_autocomplete
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP version 4.0 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997, 1998, 1999, 2000, 2001 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Adam Daniel <adaniel1@eesus.jnj.com> |
-// | Bertrand Mansion <bmansion@mamasam.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: button.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-require_once("HTML/QuickForm/input.php");
-
-/**
- * HTML class for a button type element
- *
- * @author Adam Daniel <adaniel1@eesus.jnj.com>
- * @author Bertrand Mansion <bmansion@mamasam.com>
- * @version 1.1
- * @since PHP4.04pl1
- * @access public
- */
-class HTML_QuickForm_button extends HTML_QuickForm_input
-{
- // {{{ constructor
-
- /**
- * Class constructor
- *
- * @param string $elementName (optional)Input field name attribute
- * @param string $value (optional)Input field value
- * @param mixed $attributes (optional)Either a typical HTML attribute string
- * or an associative array
- * @since 1.0
- * @access public
- * @return void
- */
- function HTML_QuickForm_button($elementName=null, $value=null, $attributes=null)
- {
- HTML_QuickForm_input::HTML_QuickForm_input($elementName, null, $attributes);
- $this->_persistantFreeze = false;
- $this->setValue($value);
- $this->setType('button');
- } //end constructor
-
- // }}}
- // {{{ freeze()
-
- /**
- * Freeze the element so that only its value is returned
- *
- * @access public
- * @return void
- */
- function freeze()
- {
- return false;
- } //end func freeze
-
- // }}}
-
-} //end class HTML_QuickForm_button
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP version 4.0 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997, 1998, 1999, 2000, 2001 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Adam Daniel <adaniel1@eesus.jnj.com> |
-// | Bertrand Mansion <bmansion@mamasam.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: checkbox.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-require_once("HTML/QuickForm/input.php");
-
-/**
- * HTML class for a checkbox type field
- *
- * @author Adam Daniel <adaniel1@eesus.jnj.com>
- * @author Bertrand Mansion <bmansion@mamasam.com>
- * @version 1.1
- * @since PHP4.04pl1
- * @access public
- */
-class HTML_QuickForm_checkbox extends HTML_QuickForm_input
-{
- // {{{ properties
-
- /**
- * Checkbox display text
- * @var string
- * @since 1.1
- * @access private
- */
- var $_text = '';
-
- // }}}
- // {{{ constructor
-
- /**
- * Class constructor
- *
- * @param string $elementName (optional)Input field name attribute
- * @param string $elementLabel (optional)Input field value
- * @param string $text (optional)Checkbox display text
- * @param mixed $attributes (optional)Either a typical HTML attribute string
- * or an associative array
- * @since 1.0
- * @access public
- * @return void
- */
- function HTML_QuickForm_checkbox($elementName=null, $elementLabel=null, $text='', $attributes=null)
- {
- HTML_QuickForm_input::HTML_QuickForm_input($elementName, $elementLabel, $attributes);
- $this->_persistantFreeze = true;
- $this->_text = $text;
- $this->setType('checkbox');
- $this->updateAttributes(array('value'=>1));
- $this->_generateId();
- } //end constructor
-
- // }}}
- // {{{ setChecked()
-
- /**
- * Sets whether a checkbox is checked
- *
- * @param bool $checked Whether the field is checked or not
- * @since 1.0
- * @access public
- * @return void
- */
- function setChecked($checked)
- {
- if (!$checked) {
- $this->removeAttribute('checked');
- } else {
- $this->updateAttributes(array('checked'=>'checked'));
- }
- } //end func setChecked
-
- // }}}
- // {{{ getChecked()
-
- /**
- * Returns whether a checkbox is checked
- *
- * @since 1.0
- * @access public
- * @return bool
- */
- function getChecked()
- {
- return (bool)$this->getAttribute('checked');
- } //end func getChecked
-
- // }}}
- // {{{ toHtml()
-
- /**
- * Returns the checkbox element in HTML
- *
- * @since 1.0
- * @access public
- * @return string
- */
- function toHtml()
- {
- if (0 == strlen($this->_text)) {
- $label = '';
- } elseif ($this->_flagFrozen) {
- $label = $this->_text;
- } else {
- $label = '<label for="' . $this->getAttribute('id') . '">' . $this->_text . '</label>';
- }
- return HTML_QuickForm_input::toHtml() . $label;
- } //end func toHtml
-
- // }}}
- // {{{ getFrozenHtml()
-
- /**
- * Returns the value of field without HTML tags
- *
- * @since 1.0
- * @access public
- * @return string
- */
- function getFrozenHtml()
- {
- if ($this->getChecked()) {
- return '<tt>[x]</tt>' .
- $this->_getPersistantData();
- } else {
- return '<tt>[ ]</tt>';
- }
- } //end func getFrozenHtml
-
- // }}}
- // {{{ setText()
-
- /**
- * Sets the checkbox text
- *
- * @param string $text
- * @since 1.1
- * @access public
- * @return void
- */
- function setText($text)
- {
- $this->_text = $text;
- } //end func setText
-
- // }}}
- // {{{ getText()
-
- /**
- * Returns the checkbox text
- *
- * @since 1.1
- * @access public
- * @return string
- */
- function getText()
- {
- return $this->_text;
- } //end func getText
-
- // }}}
- // {{{ setValue()
-
- /**
- * Sets the value of the form element
- *
- * @param string $value Default value of the form element
- * @since 1.0
- * @access public
- * @return void
- */
- function setValue($value)
- {
- return $this->setChecked($value);
- } // end func setValue
-
- // }}}
- // {{{ getValue()
-
- /**
- * Returns the value of the form element
- *
- * @since 1.0
- * @access public
- * @return bool
- */
- function getValue()
- {
- return $this->getChecked();
- } // end func getValue
-
- // }}}
- // {{{ onQuickFormEvent()
-
- /**
- * Called by HTML_QuickForm whenever form event is made on this element
- *
- * @param string $event Name of event
- * @param mixed $arg event arguments
- * @param object $caller calling object
- * @since 1.0
- * @access public
- * @return void
- */
- function onQuickFormEvent($event, $arg, &$caller)
- {
- switch ($event) {
- case 'updateValue':
- // constant values override both default and submitted ones
- // default values are overriden by submitted
- $value = $this->_findValue($caller->_constantValues);
- if (null === $value) {
- // if no boxes were checked, then there is no value in the array
- // yet we don't want to display default value in this case
- if (isset($caller->_submitValues) && 0 < count($caller->_submitValues)) {
- $value = $this->_findValue($caller->_submitValues);
- } else {
- $value = $this->_findValue($caller->_defaultValues);
- }
- }
- if (null !== $value) {
- $this->setChecked($value);
- }
- break;
- case 'setGroupValue':
- $this->setChecked($arg);
- break;
- default:
- parent::onQuickFormEvent($event, $arg, $caller);
- }
- return true;
- } // end func onQuickFormEvent
-
- // }}}
- // {{{ exportValue()
-
- /**
- * Return true if the checkbox is checked, null if it is not checked (getValue() returns false)
- */
- function exportValue(&$submitValues, $assoc = false)
- {
- $value = $this->_findValue($submitValues);
- if (null === $value) {
- $value = $this->getChecked()? true: null;
- }
- return $this->_prepareValue($value, $assoc);
- }
-
- // }}}
-} //end class HTML_QuickForm_checkbox
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Alexey Borzov <avb@php.net> |
-// | Adam Daniel <adaniel1@eesus.jnj.com> |
-// | Bertrand Mansion <bmansion@mamasam.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: date.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-require_once 'HTML/QuickForm/group.php';
-require_once 'HTML/QuickForm/select.php';
-
-/**
- * Class for a group of elements used to input dates (and times).
- *
- * Inspired by original 'date' element but reimplemented as a subclass
- * of HTML_QuickForm_group
- *
- * @author Alexey Borzov <avb@php.net>
- * @access public
- */
-class HTML_QuickForm_date extends HTML_QuickForm_group
-{
- // {{{ properties
-
- /**
- * Various options to control the element's display.
- *
- * Currently known options are
- * 'language': date language
- * 'format': Format of the date, based on PHP's date() function.
- * The following characters are recognised in format string:
- * D => Short names of days
- * l => Long names of days
- * d => Day numbers
- * M => Short names of months
- * F => Long names of months
- * m => Month numbers
- * Y => Four digit year
- * y => Two digit year
- * h => 12 hour format
- * H => 23 hour format
- * i => Minutes
- * s => Seconds
- * a => am/pm
- * A => AM/PM
- * 'minYear': Minimum year in year select
- * 'maxYear': Maximum year in year select
- * 'addEmptyOption': Should an empty option be added to the top of
- * each select box?
- * 'emptyOptionValue': The value passed by the empty option.
- * 'emptyOptionText': The text displayed for the empty option.
- * 'optionIncrement': Step to increase the option values by (works for 'i' and 's')
- *
- * @access private
- * @var array
- */
- var $_options = array(
- 'language' => 'en',
- 'format' => 'dMY',
- 'minYear' => 2001,
- 'maxYear' => 2010,
- 'addEmptyOption' => false,
- 'emptyOptionValue' => '',
- 'emptyOptionText' => ' ',
- 'optionIncrement' => array('i' => 1, 's' => 1)
- );
-
- /**
- * These complement separators, they are appended to the resultant HTML
- * @access private
- * @var array
- */
- var $_wrap = array('', '');
-
- /**
- * Options in different languages
- *
- * Note to potential translators: to avoid encoding problems please send
- * your translations with "weird" letters encoded as HTML Unicode entities
- *
- * @access private
- * @var array
- */
- var $_locale = array(
- 'en' => array (
- 'weekdays_short'=> array ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'),
- 'weekdays_long' => array ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'),
- 'months_short' => array ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'),
- 'months_long' => array ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')
- ),
- 'de' => array (
- 'weekdays_short'=> array ('So', 'Mon', 'Di', 'Mi', 'Do', 'Fr', 'Sa'),
- 'weekdays_long' => array ('Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'),
- 'months_short' => array ('Jan', 'Feb', 'März', 'April', 'Mai', 'Juni', 'Juli', 'Aug', 'Sept', 'Okt', 'Nov', 'Dez'),
- 'months_long' => array ('Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember')
- ),
- 'fr' => array (
- 'weekdays_short'=> array ('Dim', 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam'),
- 'weekdays_long' => array ('Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'),
- 'months_short' => array ('Jan', 'Fev', 'Mar', 'Avr', 'Mai', 'Jun', 'Jul', 'Aou', 'Sep', 'Oct', 'Nov', 'Dec'),
- 'months_long' => array ('Janvier', 'Fevrier', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Aout', 'Septembre', 'Octobre', 'Novembre', 'Decembre')
- ),
- 'fr' => array (
- 'weekdays_short'=> array ('Dim', 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam'),
- 'weekdays_long' => array ('Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'),
- 'months_short' => array ('Jan', 'Fev', 'Mar', 'Avr', 'Mai', 'Jun', 'Jul', 'Aou', 'Sep', 'Oct', 'Nov', 'Dec'),
- 'months_long' => array ('Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre')
- ),
- 'hu' => array (
- 'weekdays_short'=> array ('V', 'H', 'K', 'Sze', 'Cs', 'P', 'Szo'),
- 'weekdays_long' => array ('vasárnap', 'hétfő', 'kedd', 'szerda', 'csütörtök', 'péntek', 'szombat'),
- 'months_short' => array ('jan', 'feb', 'márc', 'ápr', 'máj', 'jún', 'júl', 'aug', 'szept', 'okt', 'nov', 'dec'),
- 'months_long' => array ('január', 'február', 'március', 'április', 'május', 'június', 'július', 'augusztus', 'szeptember', 'október', 'november', 'december')
- ),
- 'pl' => array (
- 'weekdays_short'=> array ('Nie', 'Pn', 'Wt', 'Śr', 'Czw', 'Pt', 'Sob'),
- 'weekdays_long' => array ('Niedziela', 'Poniedziałek', 'Wtorek', 'Środa', 'Czwartek', 'Piątek', 'Sobota'),
- 'months_short' => array ('Sty', 'Lut', 'Mar', 'Kwi', 'Maj', 'Cze', 'Lip', 'Sie', 'Wrz', 'Paź', 'Lis', 'Gru'),
- 'months_long' => array ('Styczeń', 'Luty', 'Marzec', 'Kwiecień', 'Maj', 'Czerwiec', 'Lipiec', 'Sierpień', 'Wrzesień', 'Październik', 'Listopad', 'Grudzień')
- ),
- 'sl' => array (
- 'weekdays_short'=> array ('Ned', 'Pon', 'Tor', 'Sre', 'Cet', 'Pet', 'Sob'),
- 'weekdays_long' => array ('Nedelja', 'Ponedeljek', 'Torek', 'Sreda', 'Cetrtek', 'Petek', 'Sobota'),
- 'months_short' => array ('Jan', 'Feb', 'Mar', 'Apr', 'Maj', 'Jun', 'Jul', 'Avg', 'Sep', 'Okt', 'Nov', 'Dec'),
- 'months_long' => array ('Januar', 'Februar', 'Marec', 'April', 'Maj', 'Junij', 'Julij', 'Avgust', 'September', 'Oktober', 'November', 'December')
- ),
- 'ru' => array (
- 'weekdays_short'=> array ('Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб'),
- 'weekdays_long' => array ('Воскресенье', 'Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота'),
- 'months_short' => array ('Янв', 'Фев', 'Мар', 'Апр', 'Май', 'Июн', 'Июл', 'Авг', 'Сен', 'Окт', 'Ноя', 'Дек'),
- 'months_long' => array ('Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь')
- ),
- 'es' => array (
- 'weekdays_short'=> array ('Dom', 'Lun', 'Mar', 'Mié', 'Jue', 'Vie', 'Sáb'),
- 'weekdays_long' => array ('Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'),
- 'months_short' => array ('Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'),
- 'months_long' => array ('Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septimbre', 'Octubre', 'Noviembre', 'Diciembre')
- ),
- 'da' => array (
- 'weekdays_short'=> array ('Søn', 'Man', 'Tir', 'Ons', 'Tor', 'Fre', 'Lør'),
- 'weekdays_long' => array ('Søndag', 'Mandag', 'Tirsdag', 'Onsdag', 'Torsdag', 'Fredag', 'Lørdag'),
- 'months_short' => array ('Jan', 'Feb', 'Mar', 'Apr', 'Maj', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dec'),
- 'months_long' => array ('Januar', 'Februar', 'Marts', 'April', 'Maj', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'December')
- ),
- 'is' => array (
- 'weekdays_short'=> array ('Sun', 'Mán', 'Þri', 'Mið', 'Fim', 'Fös', 'Lau'),
- 'weekdays_long' => array ('Sunnudagur', 'Mánudagur', 'Þriðjudagur', 'Miðvikudagur', 'Fimmtudagur', 'Föstudagur', 'Laugardagur'),
- 'months_short' => array ('Jan', 'Feb', 'Mar', 'Apr', 'Maí', 'Jún', 'Júl', 'Ágú', 'Sep', 'Okt', 'Nóv', 'Des'),
- 'months_long' => array ('Janúar', 'Febrúar', 'Mars', 'Apríl', 'Maí', 'Júní', 'Júlí', 'Ágúst', 'September', 'Október', 'Nóvember', 'Desember')
- ),
- 'it' => array (
- 'weekdays_short'=> array ('Dom', 'Lun', 'Mar', 'Mer', 'Gio', 'Ven', 'Sab'),
- 'weekdays_long' => array ('Domenica', 'Lunedì', 'Martedì', 'Mercoledì', 'Giovedì', 'Venerdì', 'Sabato'),
- 'months_short' => array ('Gen', 'Feb', 'Mar', 'Apr', 'Mag', 'Giu', 'Lug', 'Ago', 'Set', 'Ott', 'Nov', 'Dic'),
- 'months_long' => array ('Gennaio', 'Febbraio', 'Marzo', 'Aprile', 'Maggio', 'Giugno', 'Luglio', 'Agosto', 'Settembre', 'Ottobre', 'Novembre', 'Dicembre')
- ),
- 'sk' => array (
- 'weekdays_short'=> array ('Ned', 'Pon', 'Uto', 'Str', 'Štv', 'Pia', 'Sob'),
- 'weekdays_long' => array ('Nedeža', 'Pondelok', 'Utorok', 'Streda', 'Štvrtok', 'Piatok', 'Sobota'),
- 'months_short' => array ('Jan', 'Feb', 'Mar', 'Apr', 'Máj', 'Jún', 'Júl', 'Aug', 'Sep', 'Okt', 'Nov', 'Dec'),
- 'months_long' => array ('Január', 'Február', 'Marec', 'Apríl', 'Máj', 'Jún', 'Júl', 'August', 'September', 'Október', 'November', 'December')
- ),
- 'cs' => array (
- 'weekdays_short'=> array ('Ne', 'Po', 'Út', 'St', 'Čt', 'Pá', 'So'),
- 'weekdays_long' => array ('Neděle', 'Pondělí', 'Úterý', 'Středa', 'Čtvrtek', 'Pátek', 'Sobota'),
- 'months_short' => array ('Led', 'Úno', 'Bře', 'Dub', 'Kvě', 'Čen', 'Čec', 'Srp', 'Zář', 'Říj', 'Lis', 'Pro'),
- 'months_long' => array ('Leden', 'Únor', 'Březen', 'Duben', 'Květen', 'Červen', 'Červenec', 'Srpen', 'Září', 'Říjen', 'Listopad', 'Prosinec')
- ),
- 'hy' => array (
- 'weekdays_short'=> array ('Կրկ', 'Երկ', 'Երք', 'Չրք', 'Հնգ', 'Ուր', 'Շբթ'),
- 'weekdays_long' => array ('Կիրակի', 'Երկուշաբթի', 'Երեքշաբթի', 'Չորեքշաբթի', 'Հինգշաբթի', 'Ուրբաթ', 'Շաբաթ'),
- 'months_short' => array ('Հնվ', 'Փտր', 'Մրտ', 'Ապր', 'Մյս', 'Հնս', 'Հլս', 'Օգս', 'Սպտ', 'Հկտ', 'Նյմ', 'Դկտ'),
- 'months_long' => array ('Հունվար', 'Փետրվար', 'Մարտ', 'Ապրիլ', 'Մայիս', 'Հունիս', 'Հուլիս', 'Օգոստոս', 'Սեպտեմբեր', 'Հոկտեմբեր', 'Նոյեմբեր', 'Դեկտեմբեր')
- ),
- 'nl' => array (
- 'weekdays_short'=> array ('Zo', 'Ma', 'Di', 'Wo', 'Do', 'Vr', 'Za'),
- 'weekdays_long' => array ('Zondag', 'Maandag', 'Dinsdag', 'Woensdag', 'Donderdag', 'Vrijdag', 'Zaterdag'),
- 'months_short' => array ('Jan', 'Feb', 'Mar', 'Apr', 'Mei', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dec'),
- 'months_long' => array ('Januari', 'Februari', 'Maart', 'April', 'Mei', 'Juni', 'Juli', 'Augustus', 'September', 'Oktober', 'November', 'December')
- ),
- 'et' => array (
- 'weekdays_short'=> array ('P', 'E', 'T', 'K', 'N', 'R', 'L'),
- 'weekdays_long' => array ('Pühapäev', 'Esmaspäev', 'Teisipäev', 'Kolmapäev', 'Neljapäev', 'Reede', 'Laupäev'),
- 'months_short' => array ('Jaan', 'Veebr', 'Märts', 'Aprill', 'Mai', 'Juuni', 'Juuli', 'Aug', 'Sept', 'Okt', 'Nov', 'Dets'),
- 'months_long' => array ('Jaanuar', 'Veebruar', 'Märts', 'Aprill', 'Mai', 'Juuni', 'Juuli', 'August', 'September', 'Oktoober', 'November', 'Detsember')
- ),
- 'tr' => array (
- 'weekdays_short'=> array ('Paz', 'Pzt', 'Sal', 'Çar', 'Per', 'Cum', 'Cts'),
- 'weekdays_long' => array ('Pazar', 'Pazartesi', 'Salı', 'Çarşamba', 'Perşembe', 'Cuma', 'Cumartesi'),
- 'months_short' => array ('Ock', 'Şbt', 'Mrt', 'Nsn', 'Mys', 'Hzrn', 'Tmmz', 'Ağst', 'Eyl', 'Ekm', 'Ksm', 'Arlk'),
- 'months_long' => array ('Ocak', 'Şubat', 'Mart', 'Nisan', 'Mayıs', 'Haziran', 'Temmuz', 'Ağustos', 'Eylül', 'Ekim', 'Kasım', 'Aralık')
- ),
- 'no' => array (
- 'weekdays_short'=> array ('Søn', 'Man', 'Tir', 'Ons', 'Tor', 'Fre', 'Lør'),
- 'weekdays_long' => array ('Søndag', 'Mandag', 'Tirsdag', 'Onsdag', 'Torsdag', 'Fredag', 'Lørdag'),
- 'months_short' => array ('Jan', 'Feb', 'Mar', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Des'),
- 'months_long' => array ('Januar', 'Februar', 'Mars', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Desember')
- ),
- 'eo' => array (
- 'weekdays_short'=> array ('Dim', 'Lun', 'Mar', 'Mer', 'Ĵaŭ', 'Ven', 'Sab'),
- 'weekdays_long' => array ('Dimanĉo', 'Lundo', 'Mardo', 'Merkredo', 'Ĵaŭdo', 'Vendredo', 'Sabato'),
- 'months_short' => array ('Jan', 'Feb', 'Mar', 'Apr', 'Maj', 'Jun', 'Jul', 'Aŭg', 'Sep', 'Okt', 'Nov', 'Dec'),
- 'months_long' => array ('Januaro', 'Februaro', 'Marto', 'Aprilo', 'Majo', 'Junio', 'Julio', 'Aŭgusto', 'Septembro', 'Oktobro', 'Novembro', 'Decembro')
- ),
- 'ua' => array (
- 'weekdays_short'=> array('Ндл', 'Пнд', 'Втр', 'Срд', 'Чтв', 'Птн', 'Сбт'),
- 'weekdays_long' => array('Неділя', 'Понеділок', 'Вівторок', 'Середа', 'Четвер', 'П\'ятниця', 'Субота'),
- 'months_short' => array('Січ', 'Лют', 'Бер', 'Кві', 'Тра', 'Чер', 'Лип', 'Сер', 'Вер', 'Жов', 'Лис', 'Гру'),
- 'months_long' => array('Січень', 'Лютий', 'Березень', 'Квітень', 'Травень', 'Червень', 'Липень', 'Серпень', 'Вересень', 'Жовтень', 'Листопад', 'Грудень')
- )
- );
-
- // }}}
- // {{{ constructor
-
- /**
- * Class constructor
- *
- * @access public
- * @param string Element's name
- * @param mixed Label(s) for an element
- * @param array Options to control the element's display
- * @param mixed Either a typical HTML attribute string or an associative array
- */
- function HTML_QuickForm_date($elementName = null, $elementLabel = null, $options = array(), $attributes = null)
- {
- $this->HTML_QuickForm_element($elementName, $elementLabel, $attributes);
- $this->_persistantFreeze = true;
- $this->_appendName = true;
- $this->_type = 'date';
- // set the options, do not bother setting bogus ones
- if (is_array($options)) {
- foreach ($options as $name => $value) {
- if ('language' == $name) {
- $this->_options['language'] = isset($this->_locale[$value])? $value: 'en';
- } elseif (isset($this->_options[$name])) {
- if (is_array($value)) {
- $this->_options[$name] = @array_merge($this->_options[$name], $value);
- } else {
- $this->_options[$name] = $value;
- }
- }
- }
- }
- }
-
- // }}}
- // {{{ _createElements()
-
- function _createElements()
- {
- $this->_separator = $this->_elements = array();
- $separator = '';
- $locale =& $this->_locale[$this->_options['language']];
- $backslash = false;
- for ($i = 0, $length = strlen($this->_options['format']); $i < $length; $i++) {
- $sign = $this->_options['format']{$i};
- if ($backslash) {
- $backslash = false;
- $separator .= $sign;
- } else {
- $loadSelect = true;
- switch ($sign) {
- case 'D':
- // Sunday is 0 like with 'w' in date()
- $options = $locale['weekdays_short'];
- break;
- case 'l':
- $options = $locale['weekdays_long'];
- break;
- case 'd':
- $options = $this->_createOptionList(1, 31);
- break;
- case 'M':
- $options = $locale['months_short'];
- array_unshift($options , '');
- unset($options[0]);
- break;
- case 'm':
- $options = $this->_createOptionList(1, 12);
- break;
- case 'F':
- $options = $locale['months_long'];
- array_unshift($options , '');
- unset($options[0]);
- break;
- case 'Y':
- $options = $this->_createOptionList(
- $this->_options['minYear'],
- $this->_options['maxYear'],
- $this->_options['minYear'] > $this->_options['maxYear']? -1: 1
- );
- break;
- case 'y':
- $options = $this->_createOptionList(
- $this->_options['minYear'],
- $this->_options['maxYear'],
- $this->_options['minYear'] > $this->_options['maxYear']? -1: 1
- );
- array_walk($options, create_function('&$v,$k','$v = substr($v,-2);'));
- break;
- case 'h':
- $options = $this->_createOptionList(1, 12);
- break;
- case 'H':
- $options = $this->_createOptionList(0, 23);
- break;
- case 'i':
- $options = $this->_createOptionList(0, 59, $this->_options['optionIncrement']['i']);
- break;
- case 's':
- $options = $this->_createOptionList(0, 59, $this->_options['optionIncrement']['s']);
- break;
- case 'a':
- $options = array('am' => 'am', 'pm' => 'pm');
- break;
- case 'A':
- $options = array('AM' => 'AM', 'PM' => 'PM');
- break;
- case '\\':
- $backslash = true;
- $loadSelect = false;
- break;
- default:
- $separator .= (' ' == $sign? ' ': $sign);
- $loadSelect = false;
- }
-
- if ($loadSelect) {
- if (0 < count($this->_elements)) {
- $this->_separator[] = $separator;
- } else {
- $this->_wrap[0] = $separator;
- }
- $separator = '';
- // Should we add an empty option to the top of the select?
- if ($this->_options['addEmptyOption']) {
- // Preserve the keys
- $options = array($this->_options['emptyOptionValue'] => $this->_options['emptyOptionText']) + $options;
- }
- $this->_elements[] =& new HTML_QuickForm_select($sign, null, $options, $this->getAttributes());
- }
- }
- }
- $this->_wrap[1] = $separator . ($backslash? '\\': '');
- }
-
- // }}}
- // {{{ _createOptionList()
-
- /**
- * Creates an option list containing the numbers from the start number to the end, inclusive
- *
- * @param int The start number
- * @param int The end number
- * @param int Increment by this value
- * @access private
- * @return array An array of numeric options.
- */
- function _createOptionList($start, $end, $step = 1)
- {
- for ($i = $start, $options = array(); $start > $end? $i >= $end: $i <= $end; $i += $step) {
- $options[$i] = sprintf('%02d', $i);
- }
- return $options;
- }
-
- // }}}
- // {{{ setValue()
-
- function setValue($value)
- {
- if (empty($value)) {
- $value = array();
- } elseif (is_scalar($value)) {
- if (!is_numeric($value)) {
- $value = strtotime($value);
- }
- // might be a unix epoch, then we fill all possible values
- $arr = explode('-', date('w-d-n-Y-h-H-i-s-a-A', (int)$value));
- $value = array(
- 'D' => $arr[0],
- 'l' => $arr[0],
- 'd' => $arr[1],
- 'M' => $arr[2],
- 'm' => $arr[2],
- 'F' => $arr[2],
- 'Y' => $arr[3],
- 'y' => $arr[3],
- 'h' => $arr[4],
- 'H' => $arr[5],
- 'i' => $arr[6],
- 's' => $arr[7],
- 'a' => $arr[8],
- 'A' => $arr[9]
- );
- }
- parent::setValue($value);
- }
-
- // }}}
- // {{{ toHtml()
-
- function toHtml()
- {
- include_once('HTML/QuickForm/Renderer/Default.php');
- $renderer =& new HTML_QuickForm_Renderer_Default();
- $renderer->setElementTemplate($this->_wrap[0] . '{element}' . $this->_wrap[1]);
- parent::accept($renderer);
- return $renderer->toHtml();
- }
-
- // }}}
- // {{{ accept()
-
- function accept(&$renderer, $required = false, $error = null)
- {
- $renderer->renderElement($this, $required, $error);
- }
-
- // }}}
- // {{{ onQuickFormEvent()
-
- function onQuickFormEvent($event, $arg, &$caller)
- {
- if ('updateValue' == $event) {
- // we need to call setValue(), 'cause the default/constant value
- // may be in fact a timestamp, not an array
- return HTML_QuickForm_element::onQuickFormEvent($event, $arg, $caller);
- } else {
- return parent::onQuickFormEvent($event, $arg, $caller);
- }
- }
-
- // }}}
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP version 4.0 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997, 1998, 1999, 2000, 2001 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Adam Daniel <adaniel1@eesus.jnj.com> |
-// | Bertrand Mansion <bmansion@mamasam.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: element.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-require_once('HTML/Common.php');
-
-/**
- * Base class for form elements
- *
- * @author Adam Daniel <adaniel1@eesus.jnj.com>
- * @author Bertrand Mansion <bmansion@mamasam.com>
- * @version 1.3
- * @since PHP4.04pl1
- * @access public
- * @abstract
- */
-class HTML_QuickForm_element extends HTML_Common
-{
- // {{{ properties
-
- /**
- * Label of the field
- * @var string
- * @since 1.3
- * @access private
- */
- var $_label = '';
-
- /**
- * Form element type
- * @var string
- * @since 1.0
- * @access private
- */
- var $_type = '';
-
- /**
- * Flag to tell if element is frozen
- * @var boolean
- * @since 1.0
- * @access private
- */
- var $_flagFrozen = false;
-
- /**
- * Does the element support persistant data when frozen
- * @var boolean
- * @since 1.3
- * @access private
- */
- var $_persistantFreeze = false;
-
- // }}}
- // {{{ constructor
-
- /**
- * Class constructor
- *
- * @param string Name of the element
- * @param mixed Label(s) for the element
- * @param mixed Associative array of tag attributes or HTML attributes name="value" pairs
- * @since 1.0
- * @access public
- * @return void
- */
- function HTML_QuickForm_element($elementName=null, $elementLabel=null, $attributes=null)
- {
- HTML_Common::HTML_Common($attributes);
- if (isset($elementName)) {
- $this->setName($elementName);
- }
- if (isset($elementLabel)) {
- $this->setLabel($elementLabel);
- }
- } //end constructor
-
- // }}}
- // {{{ apiVersion()
-
- /**
- * Returns the current API version
- *
- * @since 1.0
- * @access public
- * @return float
- */
- function apiVersion()
- {
- return 2.0;
- } // end func apiVersion
-
- // }}}
- // {{{ getType()
-
- /**
- * Returns element type
- *
- * @since 1.0
- * @access public
- * @return string
- */
- function getType()
- {
- return $this->_type;
- } // end func getType
-
- // }}}
- // {{{ setName()
-
- /**
- * Sets the input field name
- *
- * @param string $name Input field name attribute
- * @since 1.0
- * @access public
- * @return void
- */
- function setName($name)
- {
- // interface method
- } //end func setName
-
- // }}}
- // {{{ getName()
-
- /**
- * Returns the element name
- *
- * @since 1.0
- * @access public
- * @return string
- */
- function getName()
- {
- // interface method
- } //end func getName
-
- // }}}
- // {{{ setValue()
-
- /**
- * Sets the value of the form element
- *
- * @param string $value Default value of the form element
- * @since 1.0
- * @access public
- * @return void
- */
- function setValue($value)
- {
- // interface
- } // end func setValue
-
- // }}}
- // {{{ getValue()
-
- /**
- * Returns the value of the form element
- *
- * @since 1.0
- * @access public
- * @return mixed
- */
- function getValue()
- {
- // interface
- return null;
- } // end func getValue
-
- // }}}
- // {{{ freeze()
-
- /**
- * Freeze the element so that only its value is returned
- *
- * @access public
- * @return void
- */
- function freeze()
- {
- $this->_flagFrozen = true;
- } //end func freeze
-
- // }}}
- // {{{ unfreeze()
-
- /**
- * Unfreezes the element so that it becomes editable
- *
- * @access public
- * @return void
- * @since 3.2.4
- */
- function unfreeze()
- {
- $this->_flagFrozen = false;
- }
-
- // }}}
- // {{{ getFrozenHtml()
-
- /**
- * Returns the value of field without HTML tags
- *
- * @since 1.0
- * @access public
- * @return string
- */
- function getFrozenHtml()
- {
- $value = $this->getValue();
- return ('' != $value? htmlspecialchars($value): ' ') .
- $this->_getPersistantData();
- } //end func getFrozenHtml
-
- // }}}
- // {{{ _getPersistantData()
-
- /**
- * Used by getFrozenHtml() to pass the element's value if _persistantFreeze is on
- *
- * @access private
- * @return string
- */
- function _getPersistantData()
- {
- if (!$this->_persistantFreeze) {
- return '';
- } else {
- $id = $this->getAttribute('id');
- return '<input type="hidden"' .
- (isset($id)? ' id="' . $id . '"': '') .
- ' name="' . $this->getName() . '"' .
- ' value="' . htmlspecialchars($this->getValue()) . '" />';
- }
- }
-
- // }}}
- // {{{ isFrozen()
-
- /**
- * Returns whether or not the element is frozen
- *
- * @since 1.3
- * @access public
- * @return bool
- */
- function isFrozen()
- {
- return $this->_flagFrozen;
- } // end func isFrozen
-
- // }}}
- // {{{ setPersistantFreeze()
-
- /**
- * Sets wether an element value should be kept in an hidden field
- * when the element is frozen or not
- *
- * @param bool $persistant True if persistant value
- * @since 2.0
- * @access public
- * @return void
- */
- function setPersistantFreeze($persistant=false)
- {
- $this->_persistantFreeze = $persistant;
- } //end func setPersistantFreeze
-
- // }}}
- // {{{ setLabel()
-
- /**
- * Sets display text for the element
- *
- * @param string $label Display text for the element
- * @since 1.3
- * @access public
- * @return void
- */
- function setLabel($label)
- {
- $this->_label = $label;
- } //end func setLabel
-
- // }}}
- // {{{ getLabel()
-
- /**
- * Returns display text for the element
- *
- * @since 1.3
- * @access public
- * @return string
- */
- function getLabel()
- {
- return $this->_label;
- } //end func getLabel
-
- // }}}
- // {{{ _findValue()
-
- /**
- * Tries to find the element value from the values array
- *
- * @since 2.7
- * @access private
- * @return mixed
- */
- function _findValue(&$values)
- {
- if (empty($values)) {
- return null;
- }
- $elementName = $this->getName();
- if (isset($values[$elementName])) {
- return $values[$elementName];
- } elseif (strpos($elementName, '[')) {
- $myVar = "['" . str_replace(array(']', '['), array('', "']['"), $elementName) . "']";
- return eval("return (isset(\$values$myVar)) ? \$values$myVar : null;");
- } else {
- return null;
- }
- } //end func _findValue
-
- // }}}
- // {{{ onQuickFormEvent()
-
- /**
- * Called by HTML_QuickForm whenever form event is made on this element
- *
- * @param string $event Name of event
- * @param mixed $arg event arguments
- * @param object $caller calling object
- * @since 1.0
- * @access public
- * @return void
- */
- function onQuickFormEvent($event, $arg, &$caller)
- {
- switch ($event) {
- case 'createElement':
- $className = get_class($this);
- $this->$className($arg[0], $arg[1], $arg[2], $arg[3], $arg[4]);
- break;
- case 'addElement':
- $this->onQuickFormEvent('createElement', $arg, $caller);
- $this->onQuickFormEvent('updateValue', null, $caller);
- break;
- case 'updateValue':
- // constant values override both default and submitted ones
- // default values are overriden by submitted
- $value = $this->_findValue($caller->_constantValues);
- if (null === $value) {
- $value = $this->_findValue($caller->_submitValues);
- if (null === $value) {
- $value = $this->_findValue($caller->_defaultValues);
- }
- }
- if (null !== $value) {
- $this->setValue($value);
- }
- break;
- case 'setGroupValue':
- $this->setValue($arg);
- }
- return true;
- } // end func onQuickFormEvent
-
- // }}}
- // {{{ accept()
-
- /**
- * Accepts a renderer
- *
- * @param object An HTML_QuickForm_Renderer object
- * @param bool Whether an element is required
- * @param string An error message associated with an element
- * @access public
- * @return void
- */
- function accept(&$renderer, $required=false, $error=null)
- {
- $renderer->renderElement($this, $required, $error);
- } // end func accept
-
- // }}}
- // {{{ _generateId()
-
- /**
- * Automatically generates and assigns an 'id' attribute for the element.
- *
- * Currently used to ensure that labels work on radio buttons and
- * checkboxes. Per idea of Alexander Radivanovich.
- *
- * @access private
- * @return void
- */
- function _generateId()
- {
- static $idx = 1;
-
- if (!$this->getAttribute('id')) {
- $this->updateAttributes(array('id' => 'qf_' . substr(md5(microtime() . $idx++), 0, 6)));
- }
- } // end func _generateId
-
- // }}}
- // {{{ exportValue()
-
- /**
- * Returns a 'safe' element's value
- *
- * @param array array of submitted values to search
- * @param bool whether to return the value as associative array
- * @access public
- * @return mixed
- */
- function exportValue(&$submitValues, $assoc = false)
- {
- $value = $this->_findValue($submitValues);
- if (null === $value) {
- $value = $this->getValue();
- }
- return $this->_prepareValue($value, $assoc);
- }
-
- // }}}
- // {{{ _prepareValue()
-
- /**
- * Used by exportValue() to prepare the value for returning
- *
- * @param mixed the value found in exportValue()
- * @param bool whether to return the value as associative array
- * @access private
- * @return mixed
- */
- function _prepareValue($value, $assoc)
- {
- if (null === $value) {
- return null;
- } elseif (!$assoc) {
- return $value;
- } else {
- $name = $this->getName();
- if (!strpos($name, '[')) {
- return array($name => $value);
- } else {
- $valueAry = array();
- $myIndex = "['" . str_replace(array(']', '['), array('', "']['"), $name) . "']";
- eval("\$valueAry$myIndex = \$value;");
- return $valueAry;
- }
- }
- }
-
- // }}}
-} // end class HTML_QuickForm_element
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP version 4.0 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997, 1998, 1999, 2000, 2001 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Adam Daniel <adaniel1@eesus.jnj.com> |
-// | Bertrand Mansion <bmansion@mamasam.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: file.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-require_once("HTML/QuickForm/input.php");
-
-// register file-related rules
-if (class_exists('HTML_QuickForm')) {
- HTML_QuickForm::registerRule('uploadedfile', 'callback', '_ruleIsUploadedFile', 'HTML_QuickForm_file');
- HTML_QuickForm::registerRule('maxfilesize', 'callback', '_ruleCheckMaxFileSize', 'HTML_QuickForm_file');
- HTML_QuickForm::registerRule('mimetype', 'callback', '_ruleCheckMimeType', 'HTML_QuickForm_file');
- HTML_QuickForm::registerRule('filename', 'callback', '_ruleCheckFileName', 'HTML_QuickForm_file');
-}
-
-/**
- * HTML class for a file type element
- *
- * @author Adam Daniel <adaniel1@eesus.jnj.com>
- * @author Bertrand Mansion <bmansion@mamasam.com>
- * @version 1.0
- * @since PHP4.04pl1
- * @access public
- */
-class HTML_QuickForm_file extends HTML_QuickForm_input
-{
- // {{{ properties
-
- /**
- * Uploaded file data, from $_FILES
- * @var array
- */
- var $_value = null;
-
- // }}}
- // {{{ constructor
-
- /**
- * Class constructor
- *
- * @param string Input field name attribute
- * @param string Input field label
- * @param mixed (optional)Either a typical HTML attribute string
- * or an associative array
- * @since 1.0
- * @access public
- */
- function HTML_QuickForm_file($elementName=null, $elementLabel=null, $attributes=null)
- {
- HTML_QuickForm_input::HTML_QuickForm_input($elementName, $elementLabel, $attributes);
- $this->setType('file');
- } //end constructor
-
- // }}}
- // {{{ setSize()
-
- /**
- * Sets size of file element
- *
- * @param int Size of file element
- * @since 1.0
- * @access public
- */
- function setSize($size)
- {
- $this->updateAttributes(array('size' => $size));
- } //end func setSize
-
- // }}}
- // {{{ getSize()
-
- /**
- * Returns size of file element
- *
- * @since 1.0
- * @access public
- * @return int
- */
- function getSize()
- {
- return $this->getAttribute('size');
- } //end func getSize
-
- // }}}
- // {{{ freeze()
-
- /**
- * Freeze the element so that only its value is returned
- *
- * @access public
- * @return bool
- */
- function freeze()
- {
- return false;
- } //end func freeze
-
- // }}}
- // {{{ setValue()
-
- /**
- * Sets value for file element.
- *
- * Actually this does nothing. The function is defined here to override
- * HTML_Quickform_input's behaviour of setting the 'value' attribute. As
- * no sane user-agent uses <input type="file">'s value for anything
- * (because of security implications) we implement file's value as a
- * read-only property with a special meaning.
- *
- * @param mixed Value for file element
- * @since 3.0
- * @access public
- */
- function setValue($value)
- {
- return null;
- } //end func setValue
-
- // }}}
- // {{{ getValue()
-
- /**
- * Returns information about the uploaded file
- *
- * @since 3.0
- * @access public
- * @return array
- */
- function getValue()
- {
- return $this->_value;
- } // end func getValue
-
- // }}}
- // {{{ onQuickFormEvent()
-
- /**
- * Called by HTML_QuickForm whenever form event is made on this element
- *
- * @param string Name of event
- * @param mixed event arguments
- * @param object calling object
- * @since 1.0
- * @access public
- * @return bool
- */
- function onQuickFormEvent($event, $arg, &$caller)
- {
- switch ($event) {
- case 'updateValue':
- if ($caller->getAttribute('method') == 'get') {
- return PEAR::raiseError('Cannot add a file upload field to a GET method form');
- }
- $this->_value = $this->_findValue();
- $caller->updateAttributes(array('enctype' => 'multipart/form-data'));
- $caller->setMaxFileSize();
- break;
- case 'addElement':
- $this->onQuickFormEvent('createElement', $arg, $caller);
- return $this->onQuickFormEvent('updateValue', null, $caller);
- break;
- case 'createElement':
- $className = get_class($this);
- $this->$className($arg[0], $arg[1], $arg[2]);
- break;
- }
- return true;
- } // end func onQuickFormEvent
-
- // }}}
- // {{{ moveUploadedFile()
-
- /**
- * Moves an uploaded file into the destination
- *
- * @param string Destination directory path
- * @param string New file name
- * @access public
- */
- function moveUploadedFile($dest, $fileName = '')
- {
- if ($dest != '' && substr($dest, -1) != '/') {
- $dest .= '/';
- }
- $fileName = ($fileName != '') ? $fileName : basename($this->_value['name']);
- if (move_uploaded_file($this->_value['tmp_name'], $dest . $fileName)) {
- return true;
- } else {
- return false;
- }
- } // end func moveUploadedFile
-
- // }}}
- // {{{ isUploadedFile()
-
- /**
- * Checks if the element contains an uploaded file
- *
- * @access public
- * @return bool true if file has been uploaded, false otherwise
- */
- function isUploadedFile()
- {
- return $this->_ruleIsUploadedFile($this->_value);
- } // end func isUploadedFile
-
- // }}}
- // {{{ _ruleIsUploadedFile()
-
- /**
- * Checks if the given element contains an uploaded file
- *
- * @param array Uploaded file info (from $_FILES)
- * @access private
- * @return bool true if file has been uploaded, false otherwise
- */
- function _ruleIsUploadedFile($elementValue)
- {
- if ((isset($elementValue['error']) && $elementValue['error'] == 0) ||
- (!empty($elementValue['tmp_name']) && $elementValue['tmp_name'] != 'none')) {
- return is_uploaded_file($elementValue['tmp_name']);
- } else {
- return false;
- }
- } // end func _ruleIsUploadedFile
-
- // }}}
- // {{{ _ruleCheckMaxFileSize()
-
- /**
- * Checks that the file does not exceed the max file size
- *
- * @param array Uploaded file info (from $_FILES)
- * @param int Max file size
- * @access private
- * @return bool true if filesize is lower than maxsize, false otherwise
- */
- function _ruleCheckMaxFileSize($elementValue, $maxSize)
- {
- if (!empty($elementValue['error']) &&
- (UPLOAD_ERR_FORM_SIZE == $elementValue['error'] || UPLOAD_ERR_INI_SIZE == $elementValue['error'])) {
- return false;
- }
- if (!HTML_QuickForm_file::_ruleIsUploadedFile($elementValue)) {
- return true;
- }
- return ($maxSize >= @filesize($elementValue['tmp_name']));
- } // end func _ruleCheckMaxFileSize
-
- // }}}
- // {{{ _ruleCheckMimeType()
-
- /**
- * Checks if the given element contains an uploaded file of the right mime type
- *
- * @param array Uploaded file info (from $_FILES)
- * @param mixed Mime Type (can be an array of allowed types)
- * @access private
- * @return bool true if mimetype is correct, false otherwise
- */
- function _ruleCheckMimeType($elementValue, $mimeType)
- {
- if (!HTML_QuickForm_file::_ruleIsUploadedFile($elementValue)) {
- return true;
- }
- if (is_array($mimeType)) {
- return in_array($elementValue['type'], $mimeType);
- }
- return $elementValue['type'] == $mimeType;
- } // end func _ruleCheckMimeType
-
- // }}}
- // {{{ _ruleCheckFileName()
-
- /**
- * Checks if the given element contains an uploaded file of the filename regex
- *
- * @param array Uploaded file info (from $_FILES)
- * @param string Regular expression
- * @access private
- * @return bool true if name matches regex, false otherwise
- */
- function _ruleCheckFileName($elementValue, $regex)
- {
- if (!HTML_QuickForm_file::_ruleIsUploadedFile($elementValue)) {
- return true;
- }
- return preg_match($regex, $elementValue['name']);
- } // end func _ruleCheckFileName
-
- // }}}
- // {{{ _findValue()
-
- /**
- * Tries to find the element value from the values array
- *
- * Needs to be redefined here as $_FILES is populated differently from
- * other arrays when element name is of the form foo[bar]
- *
- * @access private
- * @return mixed
- */
- function _findValue()
- {
- if (empty($_FILES)) {
- return null;
- }
- $elementName = $this->getName();
- if (isset($_FILES[$elementName])) {
- return $_FILES[$elementName];
- } elseif (false !== ($pos = strpos($elementName, '['))) {
- $base = substr($elementName, 0, $pos);
- $idx = "['" . str_replace(array(']', '['), array('', "']['"), substr($elementName, $pos + 1, -1)) . "']";
- $props = array('name', 'type', 'size', 'tmp_name', 'error');
- $code = "if (!isset(\$_FILES['{$base}']['name']{$idx})) {\n" .
- " return null;\n" .
- "} else {\n" .
- " \$value = array();\n";
- foreach ($props as $prop) {
- $code .= " \$value['{$prop}'] = \$_FILES['{$base}']['{$prop}']{$idx};\n";
- }
- return eval($code . " return \$value;\n}\n");
- } else {
- return null;
- }
- }
-
- // }}}
-} // end class HTML_QuickForm_file
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP version 4.0 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997, 1998, 1999, 2000, 2001 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Adam Daniel <adaniel1@eesus.jnj.com> |
-// | Bertrand Mansion <bmansion@mamasam.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: group.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-require_once("HTML/QuickForm/element.php");
-
-/**
- * HTML class for a form element group
- *
- * @author Adam Daniel <adaniel1@eesus.jnj.com>
- * @author Bertrand Mansion <bmansion@mamasam.com>
- * @version 1.0
- * @since PHP4.04pl1
- * @access public
- */
-class HTML_QuickForm_group extends HTML_QuickForm_element
-{
- // {{{ properties
-
- /**
- * Name of the element
- * @var string
- * @since 1.0
- * @access private
- */
- var $_name = '';
-
- /**
- * Array of grouped elements
- * @var array
- * @since 1.0
- * @access private
- */
- var $_elements = array();
-
- /**
- * String to separate elements
- * @var mixed
- * @since 2.5
- * @access private
- */
- var $_separator = null;
-
- /**
- * Required elements in this group
- * @var array
- * @since 2.5
- * @access private
- */
- var $_required = array();
-
- /**
- * Whether to change elements' names to $groupName[$elementName] or leave them as is
- * @var bool
- * @since 3.0
- * @access private
- */
- var $_appendName = true;
-
- // }}}
- // {{{ constructor
-
- /**
- * Class constructor
- *
- * @param string $elementName (optional)Group name
- * @param array $elementLabel (optional)Group label
- * @param array $elements (optional)Group elements
- * @param mixed $separator (optional)Use a string for one separator,
- * use an array to alternate the separators.
- * @param bool $appendName (optional)whether to change elements' names to
- * the form $groupName[$elementName] or leave
- * them as is.
- * @since 1.0
- * @access public
- * @return void
- */
- function HTML_QuickForm_group($elementName=null, $elementLabel=null, $elements=null, $separator=null, $appendName = true)
- {
- $this->HTML_QuickForm_element($elementName, $elementLabel);
- $this->_type = 'group';
- if (isset($elements) && is_array($elements)) {
- $this->setElements($elements);
- }
- if (isset($separator)) {
- $this->_separator = $separator;
- }
- if (isset($appendName)) {
- $this->_appendName = $appendName;
- }
- } //end constructor
-
- // }}}
- // {{{ setName()
-
- /**
- * Sets the group name
- *
- * @param string $name Group name
- * @since 1.0
- * @access public
- * @return void
- */
- function setName($name)
- {
- $this->_name = $name;
- } //end func setName
-
- // }}}
- // {{{ getName()
-
- /**
- * Returns the group name
- *
- * @since 1.0
- * @access public
- * @return string
- */
- function getName()
- {
- return $this->_name;
- } //end func getName
-
- // }}}
- // {{{ setValue()
-
- /**
- * Sets values for group's elements
- *
- * @param mixed Values for group's elements
- * @since 1.0
- * @access public
- * @return void
- */
- function setValue($value)
- {
- if (empty($this->_elements)) {
- $this->_createElements();
- }
- foreach (array_keys($this->_elements) as $key) {
- if (!$this->_appendName) {
- $v = $this->_elements[$key]->_findValue($value);
- if (null !== $v) {
- $this->_elements[$key]->onQuickFormEvent('setGroupValue', $v, $this);
- }
-
- } else {
- $elementName = $this->_elements[$key]->getName();
- $index = (!empty($elementName)) ? $elementName : $key;
- if (is_array($value)) {
- if (isset($value[$index])) {
- $this->_elements[$key]->onQuickFormEvent('setGroupValue', $value[$index], $this);
- }
- } elseif (isset($value)) {
- $this->_elements[$key]->onQuickFormEvent('setGroupValue', $value, $this);
- }
- }
- }
- } //end func setValue
-
- // }}}
- // {{{ getValue()
-
- /**
- * Returns the value of the group
- *
- * @since 1.0
- * @access public
- * @return mixed
- */
- function getValue()
- {
- $value = null;
- foreach (array_keys($this->_elements) as $key) {
- $element =& $this->_elements[$key];
- switch ($element->getType()) {
- case 'radio':
- $v = $element->getChecked()? $element->getValue(): null;
- break;
- case 'checkbox':
- $v = $element->getChecked()? true: null;
- break;
- default:
- $v = $element->getValue();
- }
- if (null !== $v) {
- $elementName = $element->getName();
- if (is_null($elementName)) {
- $value = $v;
- } else {
- if (!is_array($value)) {
- $value = is_null($value)? array(): array($value);
- }
- if ('' == $elementName) {
- $value[] = $v;
- } else {
- $value[$elementName] = $v;
- }
- }
- }
- }
- return $value;
- } // end func getValue
-
- // }}}
- // {{{ setElements()
-
- /**
- * Sets the grouped elements
- *
- * @param array $elements Array of elements
- * @since 1.1
- * @access public
- * @return void
- */
- function setElements($elements)
- {
- $this->_elements = array_values($elements);
- if ($this->_flagFrozen) {
- $this->freeze();
- }
- } // end func setElements
-
- // }}}
- // {{{ getElements()
-
- /**
- * Gets the grouped elements
- *
- * @since 2.4
- * @access public
- * @return array
- */
- function &getElements()
- {
- return $this->_elements;
- } // end func getElements
-
- // }}}
- // {{{ getGroupType()
-
- /**
- * Gets the group type based on its elements
- * Will return 'mixed' if elements contained in the group
- * are of different types.
- *
- * @access public
- * @return string group elements type
- */
- function getGroupType()
- {
- if (empty($this->_elements)) {
- $this->_createElements();
- }
- $prevType = '';
- foreach (array_keys($this->_elements) as $key) {
- $type = $this->_elements[$key]->getType();
- if ($type != $prevType && $prevType != '') {
- return 'mixed';
- }
- $prevType = $type;
- }
- return $type;
- } // end func getGroupType
-
- // }}}
- // {{{ toHtml()
-
- /**
- * Returns Html for the group
- *
- * @since 1.0
- * @access public
- * @return string
- */
- function toHtml()
- {
- include_once('HTML/QuickForm/Renderer/Default.php');
- $renderer =& new HTML_QuickForm_Renderer_Default();
- $renderer->setElementTemplate('{element}');
- $this->accept($renderer);
- return $renderer->toHtml();
- } //end func toHtml
-
- // }}}
- // {{{ getElementName()
-
- /**
- * Returns the element name inside the group such as found in the html form
- *
- * @param mixed $index Element name or element index in the group
- * @since 3.0
- * @access public
- * @return mixed string with element name, false if not found
- */
- function getElementName($index)
- {
- if (empty($this->_elements)) {
- $this->_createElements();
- }
- $elementName = false;
- if (is_int($index) && isset($this->_elements[$index])) {
- $elementName = $this->_elements[$index]->getName();
- if (isset($elementName) && $elementName == '') {
- $elementName = $index;
- }
- if ($this->_appendName) {
- if (is_null($elementName)) {
- $elementName = $this->getName();
- } else {
- $elementName = $this->getName().'['.$elementName.']';
- }
- }
-
- } elseif (is_string($index)) {
- foreach (array_keys($this->_elements) as $key) {
- $elementName = $this->_elements[$key]->getName();
- if ($index == $elementName) {
- if ($this->_appendName) {
- $elementName = $this->getName().'['.$elementName.']';
- }
- break;
- } elseif ($this->_appendName && $this->getName().'['.$elementName.']' == $index) {
- break;
- }
- }
- }
- return $elementName;
- } //end func getElementName
-
- // }}}
- // {{{ getFrozenHtml()
-
- /**
- * Returns the value of field without HTML tags
- *
- * @since 1.3
- * @access public
- * @return string
- */
- function getFrozenHtml()
- {
- $flags = array();
- if (empty($this->_elements)) {
- $this->_createElements();
- }
- foreach (array_keys($this->_elements) as $key) {
- if (false === ($flags[$key] = $this->_elements[$key]->isFrozen())) {
- $this->_elements[$key]->freeze();
- }
- }
- $html = $this->toHtml();
- foreach (array_keys($this->_elements) as $key) {
- if (!$flags[$key]) {
- $this->_elements[$key]->unfreeze();
- }
- }
- return $html;
- } //end func getFrozenHtml
-
- // }}}
- // {{{ onQuickFormEvent()
-
- /**
- * Called by HTML_QuickForm whenever form event is made on this element
- *
- * @param string $event Name of event
- * @param mixed $arg event arguments
- * @param object $caller calling object
- * @since 1.0
- * @access public
- * @return void
- */
- function onQuickFormEvent($event, $arg, &$caller)
- {
- switch ($event) {
- case 'updateValue':
- if (empty($this->_elements)) {
- $this->_createElements();
- }
- foreach (array_keys($this->_elements) as $key) {
- if ($this->_appendName) {
- $elementName = $this->_elements[$key]->getName();
- if (is_null($elementName)) {
- $this->_elements[$key]->setName($this->getName());
- } elseif ('' == $elementName) {
- $this->_elements[$key]->setName($this->getName() . '[' . $key . ']');
- } else {
- $this->_elements[$key]->setName($this->getName() . '[' . $elementName . ']');
- }
- }
- $this->_elements[$key]->onQuickFormEvent('updateValue', $arg, $caller);
- if ($this->_appendName) {
- $this->_elements[$key]->setName($elementName);
- }
- }
- break;
-
- default:
- parent::onQuickFormEvent($event, $arg, $caller);
- }
- return true;
- } // end func onQuickFormEvent
-
- // }}}
- // {{{ accept()
-
- /**
- * Accepts a renderer
- *
- * @param object An HTML_QuickForm_Renderer object
- * @param bool Whether a group is required
- * @param string An error message associated with a group
- * @access public
- * @return void
- */
- function accept(&$renderer, $required = false, $error = null)
- {
- if (empty($this->_elements)) {
- $this->_createElements();
- }
- $renderer->startGroup($this, $required, $error);
- $name = $this->getName();
- foreach (array_keys($this->_elements) as $key) {
- $element =& $this->_elements[$key];
-
- if ($this->_appendName) {
- $elementName = $element->getName();
- if (isset($elementName)) {
- $element->setName($name . '['. (strlen($elementName)? $elementName: $key) .']');
- } else {
- $element->setName($name);
- }
- }
-
- $required = !$element->isFrozen() && in_array($element->getName(), $this->_required);
-
- $element->accept($renderer, $required);
-
- // restore the element's name
- if ($this->_appendName) {
- $element->setName($elementName);
- }
- }
- $renderer->finishGroup($this);
- } // end func accept
-
- // }}}
- // {{{ exportValue()
-
- /**
- * As usual, to get the group's value we access its elements and call
- * their exportValue() methods
- */
- function exportValue(&$submitValues, $assoc = false)
- {
- $value = null;
- foreach (array_keys($this->_elements) as $key) {
- $elementName = $this->_elements[$key]->getName();
- if ($this->_appendName) {
- if (is_null($elementName)) {
- $this->_elements[$key]->setName($this->getName());
- } elseif ('' == $elementName) {
- $this->_elements[$key]->setName($this->getName() . '[' . $key . ']');
- } else {
- $this->_elements[$key]->setName($this->getName() . '[' . $elementName . ']');
- }
- }
- $v = $this->_elements[$key]->exportValue($submitValues, $assoc);
- if ($this->_appendName) {
- $this->_elements[$key]->setName($elementName);
- }
- if (null !== $v) {
- // Make $value an array, we will use it like one
- if (null === $value) {
- $value = array();
- }
- if ($assoc) {
- // just like HTML_QuickForm::exportValues()
- $value = HTML_QuickForm::arrayMerge($value, $v);
- } else {
- // just like getValue(), but should work OK every time here
- if (is_null($elementName)) {
- $value = $v;
- } elseif ('' == $elementName) {
- $value[] = $v;
- } else {
- $value[$elementName] = $v;
- }
- }
- }
- }
- // do not pass the value through _prepareValue, we took care of this already
- return $value;
- }
-
- // }}}
- // {{{ _createElements()
-
- /**
- * Creates the group's elements.
- *
- * This should be overriden by child classes that need to create their
- * elements. The method will be called automatically when needed, calling
- * it from the constructor is discouraged as the constructor is usually
- * called _twice_ on element creation, first time with _no_ parameters.
- *
- * @access private
- * @abstract
- */
- function _createElements()
- {
- // abstract
- }
-
- // }}}
- // {{{ freeze()
-
- function freeze()
- {
- parent::freeze();
- foreach (array_keys($this->_elements) as $key) {
- $this->_elements[$key]->freeze();
- }
- }
-
- // }}}
- // {{{ unfreeze()
-
- function unfreeze()
- {
- parent::unfreeze();
- foreach (array_keys($this->_elements) as $key) {
- $this->_elements[$key]->unfreeze();
- }
- }
-
- // }}}
- // {{{ setPersistantFreeze()
-
- function setPersistantFreeze($persistant = false)
- {
- parent::setPersistantFreeze($persistant);
- foreach (array_keys($this->_elements) as $key) {
- $this->_elements[$key]->setPersistantFreeze($persistant);
- }
- }
-
- // }}}
-} //end class HTML_QuickForm_group
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP version 4.0 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Alexey Borzov <borz_off@cs.msu.su> |
-// +----------------------------------------------------------------------+
-//
-// $Id: header.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-require_once 'HTML/QuickForm/static.php';
-
-/**
- * A pseudo-element used for adding headers to form
- *
- * @author Alexey Borzov <borz_off@cs.msu.su>
- * @access public
- */
-class HTML_QuickForm_header extends HTML_QuickForm_static
-{
- // {{{ constructor
-
- /**
- * Class constructor
- *
- * @param string $elementName Header name
- * @param string $text Header text
- * @access public
- * @return void
- */
- function HTML_QuickForm_header($elementName = null, $text = null)
- {
- $this->HTML_QuickForm_static($elementName, null, $text);
- $this->_type = 'header';
- }
-
- // }}}
- // {{{ accept()
-
- /**
- * Accepts a renderer
- *
- * @param object An HTML_QuickForm_Renderer object
- * @access public
- * @return void
- */
- function accept(&$renderer)
- {
- $renderer->renderHeader($this);
- } // end func accept
-
- // }}}
-
-} //end class HTML_QuickForm_header
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP version 4.0 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997, 1998, 1999, 2000, 2001 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Adam Daniel <adaniel1@eesus.jnj.com> |
-// | Bertrand Mansion <bmansion@mamasam.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: hidden.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-require_once("HTML/QuickForm/input.php");
-
-/**
- * HTML class for a hidden type element
- *
- * @author Adam Daniel <adaniel1@eesus.jnj.com>
- * @author Bertrand Mansion <bmansion@mamasam.com>
- * @version 1.0
- * @since PHP4.04pl1
- * @access public
- */
-class HTML_QuickForm_hidden extends HTML_QuickForm_input
-{
- // {{{ constructor
-
- /**
- * Class constructor
- *
- * @param string $elementName (optional)Input field name attribute
- * @param string $value (optional)Input field value
- * @param mixed $attributes (optional)Either a typical HTML attribute string
- * or an associative array
- * @since 1.0
- * @access public
- * @return void
- */
- function HTML_QuickForm_hidden($elementName=null, $value='', $attributes=null)
- {
- HTML_QuickForm_input::HTML_QuickForm_input($elementName, null, $attributes);
- $this->setType('hidden');
- $this->setValue($value);
- } //end constructor
-
- // }}}
- // {{{ freeze()
-
- /**
- * Freeze the element so that only its value is returned
- *
- * @access public
- * @return void
- */
- function freeze()
- {
- return false;
- } //end func freeze
-
- // }}}
- // {{{ accept()
-
- /**
- * Accepts a renderer
- *
- * @param object An HTML_QuickForm_Renderer object
- * @access public
- * @return void
- */
- function accept(&$renderer)
- {
- $renderer->renderHidden($this);
- } // end func accept
-
- // }}}
-
-} //end class HTML_QuickForm_hidden
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP version 4.0 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997, 1998, 1999, 2000, 2001 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Adam Daniel <adaniel1@eesus.jnj.com> |
-// | Bertrand Mansion <bmansion@mamasam.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: hiddenselect.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-require_once('HTML/QuickForm/select.php');
-
-/**
- * This class takes the same arguments as a select element, but instead
- * of creating a select ring it creates hidden elements for all values
- * already selected with setDefault or setConstant. This is useful if
- * you have a select ring that you don't want visible, but you need all
- * selected values to be passed.
- *
- * @author Isaac Shepard <ishepard@bsiweb.com>
- *
- * @version 1.0
- * @since 2.1
- * @access public
- */
-class HTML_QuickForm_hiddenselect extends HTML_QuickForm_select
-{
- // {{{ constructor
-
- /**
- * Class constructor
- *
- * @param string Select name attribute
- * @param mixed Label(s) for the select (not used)
- * @param mixed Data to be used to populate options
- * @param mixed Either a typical HTML attribute string or an associative array (not used)
- * @since 1.0
- * @access public
- * @return void
- */
- function HTML_QuickForm_hiddenselect($elementName=null, $elementLabel=null, $options=null, $attributes=null)
- {
- HTML_QuickForm_element::HTML_QuickForm_element($elementName, $elementLabel, $attributes);
- $this->_persistantFreeze = true;
- $this->_type = 'hiddenselect';
- if (isset($options)) {
- $this->load($options);
- }
- } //end constructor
-
- // }}}
- // {{{ toHtml()
-
- /**
- * Returns the SELECT in HTML
- *
- * @since 1.0
- * @access public
- * @return string
- * @throws
- */
- function toHtml()
- {
- $tabs = $this->_getTabs();
- $name = $this->getPrivateName();
- $strHtml = '';
-
- foreach ($this->_values as $key => $val) {
- for ($i = 0, $optCount = count($this->_options); $i < $optCount; $i++) {
- if ($val == $this->_options[$i]['attr']['value']) {
- $strHtml .= $tabs . '<input type="hidden" name="' . $name . '" value="' . $val . '" />' . "\n";
- }
- }
- }
-
- return $strHtml;
- } //end func toHtml
-
- // }}}
- // {{{ accept()
-
- /**
- * This is essentially a hidden element and should be rendered as one
- */
- function accept(&$renderer)
- {
- $renderer->renderHidden($this);
- }
-
- // }}}
-} //end class HTML_QuickForm_hiddenselect
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP version 4.0 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Herim Vasquez <vasquezh@iro.umontreal.ca> |
-// | Bertrand Mansion <bmansion@mamasam.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: hierselect.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-require_once('HTML/QuickForm/group.php');
-require_once('HTML/QuickForm/select.php');
-
-/**
- * Class to dynamically create two or more HTML Select elements
- * The first select changes the content of the second select and so on.
- * This element is considered as a group. Selects will be named
- * groupName[0], groupName[1], groupName[2]...
- *
- * @author Herim Vasquez <vasquezh@iro.umontreal.ca>
- * @author Bertrand Mansion <bmansion@mamasam.com>
- * @version 1.0
- * @since PHP4.04pl1
- * @access public
- */
-class HTML_QuickForm_hierselect extends HTML_QuickForm_group
-{
- // {{{ properties
-
- /**
- * Options for all the select elements
- *
- * Format is a bit more complex as we need to know which options
- * are related to the ones in the previous select:
- *
- * Ex:
- * // first select
- * $select1[0] = 'Pop';
- * $select1[1] = 'Classical';
- * $select1[2] = 'Funeral doom';
- *
- * // second select
- * $select2[0][0] = 'Red Hot Chil Peppers';
- * $select2[0][1] = 'The Pixies';
- * $select2[1][0] = 'Wagner';
- * $select2[1][1] = 'Strauss';
- * $select2[2][0] = 'Pantheist';
- * $select2[2][1] = 'Skepticism';
- *
- * // If only need two selects
- * // - and using the depracated functions
- * $sel =& $form->addElement('hierselect', 'cds', 'Choose CD:');
- * $sel->setMainOptions($select1);
- * $sel->setSecOptions($select2);
- *
- * // - and using the new setOptions function
- * $sel =& $form->addElement('hierselect', 'cds', 'Choose CD:');
- * $sel->setOptions(array($select1, $select2));
- *
- * // If you have a third select with prices for the cds
- * $select3[0][0][0] = '15.00$';
- * $select3[0][0][1] = '17.00$';
- * etc
- *
- * // You can now use
- * $sel =& $form->addElement('hierselect', 'cds', 'Choose CD:');
- * $sel->setOptions(array($select1, $select2, $select3));
- *
- * @var array
- * @access private
- */
- var $_options = array();
-
- /**
- * Number of select elements on this group
- *
- * @var int
- * @access private
- */
- var $_nbElements = 0;
-
- /**
- * The javascript used to set and change the options
- *
- * @var string
- * @access private
- */
- var $_js = '';
-
- /**
- * The javascript array name
- */
- var $_jsArrayName = '';
-
- // }}}
- // {{{ constructor
-
- /**
- * Class constructor
- *
- * @param string $elementName (optional)Input field name attribute
- * @param string $elementLabel (optional)Input field label in form
- * @param mixed $attributes (optional)Either a typical HTML attribute string
- * or an associative array. Date format is passed along the attributes.
- * @param mixed $separator (optional)Use a string for one separator,
- * use an array to alternate the separators.
- * @access public
- * @return void
- */
- function HTML_QuickForm_hierselect($elementName=null, $elementLabel=null, $attributes=null, $separator=null)
- {
- $this->HTML_QuickForm_element($elementName, $elementLabel, $attributes);
- $this->_persistantFreeze = true;
- if (isset($separator)) {
- $this->_separator = $separator;
- }
- $this->_type = 'hierselect';
- $this->_appendName = true;
- } //end constructor
-
- // }}}
- // {{{ setOptions()
-
- /**
- * Initialize the array structure containing the options for each select element.
- * Call the functions that actually do the magic.
- *
- * @param array $options Array of options defining each element
- *
- * @access public
- * @return void
- */
- function setOptions($options)
- {
- $this->_options = $options;
-
- if (empty($this->_elements)) {
- $this->_nbElements = count($this->_options);
- $this->_createElements();
- } else {
- // setDefaults has probably been called before this function
- // check if all elements have been created
- $totalNbElements = count($this->_options);
- for ($i = $this->_nbElements; $i < $totalNbElements; $i ++) {
- $this->_elements[] =& new HTML_QuickForm_select($i, null, array(), $this->getAttributes());
- $this->_nbElements++;
- }
- }
-
- $this->_setOptions();
- $this->_setJS();
- } // end func setMainOptions
-
- // }}}
- // {{{ setMainOptions()
-
- /**
- * Sets the options for the first select element. Deprecated. setOptions() should be used.
- *
- * @param array $array Options for the first select element
- *
- * @access public
- * @return void
- */
- function setMainOptions($array)
- {
- $this->_options[0] = $array;
-
- if (empty($this->_elements)) {
- $this->_nbElements = 2;
- $this->_createElements();
- }
- } // end func setMainOptions
-
- // }}}
- // {{{ setSecOptions()
-
- /**
- * Sets the options for the second select element. Deprecated. setOptions() should be used.
- * The main _options array is initialized and the _setOptions function is called.
- *
- * @param array $array Options for the second select element
- *
- * @access public
- * @return void
- */
- function setSecOptions($array)
- {
- $this->_options[1] = $array;
-
- if (empty($this->_elements)) {
- $this->_nbElements = 2;
- $this->_createElements();
- } else {
- // setDefaults has probably been called before this function
- // check if all elements have been created
- $totalNbElements = 2;
- for ($i = $this->_nbElements; $i < $totalNbElements; $i ++) {
- $this->_elements[] =& new HTML_QuickForm_select($i, null, array(), $this->getAttributes());
- $this->_nbElements++;
- }
- }
-
- $this->_setOptions();
- $this->_setJS();
- } // end func setSecOptions
-
- // }}}
- // {{{ _setOptions()
-
- /**
- * Sets the options for each select element
- *
- * @access private
- * @return void
- */
- function _setOptions()
- {
- $toLoad = '';
- foreach (array_keys($this->_elements) AS $key) {
- if (eval("return isset(\$this->_options[{$key}]{$toLoad});") ) {
- $array = eval("return \$this->_options[{$key}]{$toLoad};");
- if (is_array($array)) {
- $select =& $this->_elements[$key];
- $select->_options = array();
- $select->loadArray($array);
-
- $value = is_array($v = $select->getValue()) ? $v[0] : key($array);
- $toLoad .= '[\''.$value.'\']';
- }
- }
- }
- } // end func _setOptions
-
- // }}}
- // {{{ setValue()
-
- /**
- * Sets values for group's elements
- *
- * @param array $value An array of 2 or more values, for the first,
- * the second, the third etc. select
- *
- * @access public
- * @return void
- */
- function setValue($value)
- {
- $this->_nbElements = count($value);
- parent::setValue($value);
- $this->_setOptions();
- } // end func setValue
-
- // }}}
- // {{{ _createElements()
-
- /**
- * Creates all the elements for the group
- *
- * @access private
- * @return void
- */
- function _createElements()
- {
- for ($i = 0; $i < $this->_nbElements; $i++) {
- $this->_elements[] =& new HTML_QuickForm_select($i, null, array(), $this->getAttributes());
- }
- } // end func _createElements
-
- // }}}
- // {{{ _setJS()
-
- /**
- * Set the JavaScript for each select element (excluding de main one).
- *
- * @access private
- * @return void
- */
- function _setJS()
- {
- $this->_js = $js = '';
- $this->_jsArrayName = 'hs_' . $this->getName();
- for ($i = 1; $i < $this->_nbElements; $i++) {
- $this->_setJSArray($this->_jsArrayName, $this->_options[$i], $js);
- }
- } // end func _setJS
-
- // }}}
- // {{{ _setJSArray()
-
- /**
- * Recursively builds the JavaScript array defining the options that a select
- * element can have.
- *
- * @param string $grpName Group Name attribute
- * @param array $options Select element options
- * @param string $js JavaScript definition is build using this variable
- * @param string $optValue The value for the current JavaScript option
- *
- * @access private
- * @return void
- */
- function _setJSArray($grpName, $options, &$js, $optValue = '')
- {
- if (is_array($options)) {
- $js = '';
- // For a hierselect containing 3 elements:
- // if option 1 has been selected for the 1st element
- // and option 3 has been selected for the 2nd element,
- // then the javascript array containing the values to load
- // on the 3rd element will have the following name: grpName_1_3
- $name = ($optValue === '') ? $grpName : $grpName.'_'.$optValue;
- foreach($options AS $k => $v) {
- $this->_setJSArray($name, $v, $js, $k);
- }
-
- // if $js !== '' add it to the JavaScript
- $this->_js .= ($js !== '') ? $name." = {\n".$js."\n}\n" : '';
- $js = '';
- } else {
- // $js empty means that we are adding the first element to the JavaScript.
- if ($js != '') {
- $js .= ",\n";
- }
- $js .= '"'.$optValue.'":"'.$options.'"';
- }
- }
-
- // }}}
- // {{{ toHtml()
-
- /**
- * Returns Html for the group
- *
- * @access public
- * @return string
- */
- function toHtml()
- {
- if ($this->_flagFrozen) {
- $this->_js = '';
- } else {
- // set the onchange attribute for each element
- $keys = array_keys($this->_elements);
- $nbElements = count($keys);
- $nbElementsUsingFnc = $nbElements - 1; // last element doesn't need it
- for ($i = 0; $i < $nbElementsUsingFnc; $i++) {
- $select =& $this->_elements[$keys[$i]];
- $select->updateAttributes(
- array('onChange' => 'swapOptions(this, \''.$this->getName().'\', '.$keys[$i].', '.$nbElements.', \''.$this->_jsArrayName.'\');')
- );
- }
-
- // create the js function to call
- if (!defined('HTML_QUICKFORM_HIERSELECT_EXISTS')) {
- $this->_js .= "function swapOptions(frm, grpName, eleIndex, nbElements, arName)\n"
- ."{\n"
- ." var n = \"\";\n"
- ." var ctl;\n\n"
- ." for (var i = 0; i < nbElements; i++) {\n"
- ." ctl = frm.form[grpName+'['+i+']'];\n"
- ." if (!ctl) {\n"
- ." ctl = frm.form[grpName+'['+i+'][]'];\n"
- ." }\n"
- ." if (i <= eleIndex) {\n"
- ." n += \"_\"+ctl.value;\n"
- ." } else {\n"
- ." ctl.length = 0;\n"
- ." }\n"
- ." }\n\n"
- ." var t = eval(\"typeof(\"+arName + n +\")\");\n"
- ." if (t != 'undefined') {\n"
- ." var the_array = eval(arName+n);\n"
- ." var j = 0;\n"
- ." n = eleIndex + 1;\n"
- ." ctl = frm.form[grpName+'['+ n +']'];\n"
- ." if (!ctl) {\n"
- ." ctl = frm.form[grpName+'['+ n +'][]'];\n"
- ." }\n"
- ." for (var i in the_array) {\n"
- ." opt = new Option(the_array[i], i, false, false);\n"
- ." ctl.options[j++] = opt;\n"
- ." }\n"
- ." }\n"
- ." if (eleIndex+1 < nbElements) {\n"
- ." swapOptions(frm, grpName, eleIndex+1, nbElements, arName);\n"
- ." }\n"
- ."}\n";
- define('HTML_QUICKFORM_HIERSELECT_EXISTS', true);
- }
- }
- include_once('HTML/QuickForm/Renderer/Default.php');
- $renderer =& new HTML_QuickForm_Renderer_Default();
- $renderer->setElementTemplate('{element}');
- parent::accept($renderer);
- return "<script type=\"text/javascript\">\n//<![CDATA[\n" . $this->_js . "//]]>\n</script>" .
- $renderer->toHtml();
- } // end func toHtml
-
- // }}}
- // {{{ accept()
-
- /**
- * Accepts a renderer
- *
- * @param object An HTML_QuickForm_Renderer object
- * @param bool Whether a group is required
- * @param string An error message associated with a group
- * @access public
- * @return void
- */
- function accept(&$renderer, $required = false, $error = null)
- {
- $renderer->renderElement($this, $required, $error);
- } // end func accept
-
- // }}}
- // {{{ onQuickFormEvent()
-
- function onQuickFormEvent($event, $arg, &$caller)
- {
- if ('updateValue' == $event) {
- // we need to call setValue() so that the secondary option
- // matches the main option
- return HTML_QuickForm_element::onQuickFormEvent($event, $arg, $caller);
- } else {
- return parent::onQuickFormEvent($event, $arg, $caller);
- }
- } // end func onQuickFormEvent
-
- // }}}
-} // end class HTML_QuickForm_hierselect
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP version 4.0 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Alexey Borzov <borz_off@cs.msu.su> |
-// +----------------------------------------------------------------------+
-//
-// $Id: html.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-require_once 'HTML/QuickForm/static.php';
-
-/**
- * A pseudo-element used for adding raw HTML to form
- *
- * Intended for use with the default renderer only, template-based
- * ones may (and probably will) completely ignore this
- *
- * @author Alexey Borzov <borz_off@cs.msu.su>
- * @access public
- */
-class HTML_QuickForm_html extends HTML_QuickForm_static
-{
- // {{{ constructor
-
- /**
- * Class constructor
- *
- * @param string $text raw HTML to add
- * @access public
- * @return void
- */
- function HTML_QuickForm_html($text = null)
- {
- $this->HTML_QuickForm_static(null, null, $text);
- $this->_type = 'html';
- }
-
- // }}}
- // {{{ accept()
-
- /**
- * Accepts a renderer
- *
- * @param object An HTML_QuickForm_Renderer object
- * @access public
- * @return void
- */
- function accept(&$renderer)
- {
- $renderer->renderHtml($this);
- } // end func accept
-
- // }}}
-
-} //end class HTML_QuickForm_header
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP version 4.0 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997, 1998, 1999, 2000, 2001 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Adam Daniel <adaniel1@eesus.jnj.com> |
-// | Bertrand Mansion <bmansion@mamasam.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: image.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-require_once("HTML/QuickForm/input.php");
-
-/**
- * HTML class for a image type element
- *
- * @author Adam Daniel <adaniel1@eesus.jnj.com>
- * @author Bertrand Mansion <bmansion@mamasam.com>
- * @version 1.0
- * @since PHP4.04pl1
- * @access public
- */
-class HTML_QuickForm_image extends HTML_QuickForm_input
-{
- // {{{ constructor
-
- /**
- * Class constructor
- *
- * @param string $elementName (optional)Element name attribute
- * @param string $src (optional)Image source
- * @param mixed $attributes (optional)Either a typical HTML attribute string
- * or an associative array
- * @since 1.0
- * @access public
- * @return void
- */
- function HTML_QuickForm_image($elementName=null, $src='', $attributes=null)
- {
- HTML_QuickForm_input::HTML_QuickForm_input($elementName, null, $attributes);
- $this->setType('image');
- $this->setSource($src);
- } // end class constructor
-
- // }}}
- // {{{ setSource()
-
- /**
- * Sets source for image element
- *
- * @param string $src source for image element
- * @since 1.0
- * @access public
- * @return void
- */
- function setSource($src)
- {
- $this->updateAttributes(array('src' => $src));
- } // end func setSource
-
- // }}}
- // {{{ setBorder()
-
- /**
- * Sets border size for image element
- *
- * @param string $border border for image element
- * @since 1.0
- * @access public
- * @return void
- */
- function setBorder($border)
- {
- $this->updateAttributes(array('border' => $border));
- } // end func setBorder
-
- // }}}
- // {{{ setAlign()
-
- /**
- * Sets alignment for image element
- *
- * @param string $align alignment for image element
- * @since 1.0
- * @access public
- * @return void
- */
- function setAlign($align)
- {
- $this->updateAttributes(array('align' => $align));
- } // end func setAlign
-
- // }}}
- // {{{ freeze()
-
- /**
- * Freeze the element so that only its value is returned
- *
- * @access public
- * @return void
- */
- function freeze()
- {
- return false;
- } //end func freeze
-
- // }}}
-
-} // end class HTML_QuickForm_image
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP version 4.0 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997, 1998, 1999, 2000, 2001 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Adam Daniel <adaniel1@eesus.jnj.com> |
-// | Bertrand Mansion <bmansion@mamasam.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: input.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-require_once("HTML/QuickForm/element.php");
-
-/**
- * Base class for input form elements
- *
- * @author Adam Daniel <adaniel1@eesus.jnj.com>
- * @author Bertrand Mansion <bmansion@mamasam.com>
- * @version 1.0
- * @since PHP4.04pl1
- * @access public
- * @abstract
- */
-class HTML_QuickForm_input extends HTML_QuickForm_element
-{
- // {{{ constructor
-
- /**
- * Class constructor
- *
- * @param string Input field name attribute
- * @param mixed Label(s) for the input field
- * @param mixed Either a typical HTML attribute string or an associative array
- * @since 1.0
- * @access public
- * @return void
- */
- function HTML_QuickForm_input($elementName=null, $elementLabel=null, $attributes=null)
- {
- $this->HTML_QuickForm_element($elementName, $elementLabel, $attributes);
- } //end constructor
-
- // }}}
- // {{{ setType()
-
- /**
- * Sets the element type
- *
- * @param string $type Element type
- * @since 1.0
- * @access public
- * @return void
- */
- function setType($type)
- {
- $this->_type = $type;
- $this->updateAttributes(array('type'=>$type));
- } // end func setType
-
- // }}}
- // {{{ setName()
-
- /**
- * Sets the input field name
- *
- * @param string $name Input field name attribute
- * @since 1.0
- * @access public
- * @return void
- */
- function setName($name)
- {
- $this->updateAttributes(array('name'=>$name));
- } //end func setName
-
- // }}}
- // {{{ getName()
-
- /**
- * Returns the element name
- *
- * @since 1.0
- * @access public
- * @return string
- */
- function getName()
- {
- return $this->getAttribute('name');
- } //end func getName
-
- // }}}
- // {{{ setValue()
-
- /**
- * Sets the value of the form element
- *
- * @param string $value Default value of the form element
- * @since 1.0
- * @access public
- * @return void
- */
- function setValue($value)
- {
- $this->updateAttributes(array('value'=>$value));
- } // end func setValue
-
- // }}}
- // {{{ getValue()
-
- /**
- * Returns the value of the form element
- *
- * @since 1.0
- * @access public
- * @return string
- */
- function getValue()
- {
- return $this->getAttribute('value');
- } // end func getValue
-
- // }}}
- // {{{ toHtml()
-
- /**
- * Returns the input field in HTML
- *
- * @since 1.0
- * @access public
- * @return string
- */
- function toHtml()
- {
- if ($this->_flagFrozen) {
- return $this->getFrozenHtml();
- } else {
- return $this->_getTabs() . '<input' . $this->_getAttrString($this->_attributes) . ' />';
- }
- } //end func toHtml
-
- // }}}
- // {{{ onQuickFormEvent()
-
- /**
- * Called by HTML_QuickForm whenever form event is made on this element
- *
- * @param string $event Name of event
- * @param mixed $arg event arguments
- * @param object $caller calling object
- * @since 1.0
- * @access public
- * @return void
- * @throws
- */
- function onQuickFormEvent($event, $arg, &$caller)
- {
- // do not use submit values for button-type elements
- $type = $this->getType();
- if (('updateValue' != $event) ||
- ('submit' != $type && 'reset' != $type && 'image' != $type && 'button' != $type)) {
- parent::onQuickFormEvent($event, $arg, $caller);
- } else {
- $value = $this->_findValue($caller->_constantValues);
- if (null === $value) {
- $value = $this->_findValue($caller->_defaultValues);
- }
- if (null !== $value) {
- $this->setValue($value);
- }
- }
- return true;
- } // end func onQuickFormEvent
-
- // }}}
- // {{{ exportValue()
-
- /**
- * We don't need values from button-type elements (except submit) and files
- */
- function exportValue(&$submitValues, $assoc = false)
- {
- $type = $this->getType();
- if ('reset' == $type || 'image' == $type || 'button' == $type || 'file' == $type) {
- return null;
- } else {
- return parent::exportValue($submitValues, $assoc);
- }
- }
-
- // }}}
-} // end class HTML_QuickForm_element
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP version 4.0 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997, 1998, 1999, 2000, 2001 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Adam Daniel <adaniel1@eesus.jnj.com> |
-// | Bertrand Mansion <bmansion@mamasam.com> |
-// +----------------------------------------------------------------------+
-//
-
-require_once 'HTML/QuickForm/static.php';
-
-/**
- * HTML class for a link type field
- *
- * @author Adam Daniel <adaniel1@eesus.jnj.com>
- * @author Bertrand Mansion <bmansion@mamasam.com>
- * @version 1.0
- * @since PHP4.04pl1
- * @access public
- */
-class HTML_QuickForm_link extends HTML_QuickForm_static
-{
- // {{{ properties
-
- /**
- * Link display text
- * @var string
- * @since 1.0
- * @access private
- */
- var $_text = "";
-
- // }}}
- // {{{ constructor
-
- /**
- * Class constructor
- *
- * @param string $elementLabel (optional)Link label
- * @param string $href (optional)Link href
- * @param string $text (optional)Link display text
- * @param mixed $attributes (optional)Either a typical HTML attribute string
- * or an associative array
- * @since 1.0
- * @access public
- * @return void
- * @throws
- */
- function HTML_QuickForm_link($elementName=null, $elementLabel=null, $href=null, $text=null, $attributes=null)
- {
- HTML_QuickForm_element::HTML_QuickForm_element($elementName, $elementLabel, $attributes);
- $this->_persistantFreeze = false;
- $this->_type = 'link';
- $this->setHref($href);
- $this->_text = $text;
- } //end constructor
-
- // }}}
- // {{{ setName()
-
- /**
- * Sets the input field name
- *
- * @param string $name Input field name attribute
- * @since 1.0
- * @access public
- * @return void
- * @throws
- */
- function setName($name)
- {
- $this->updateAttributes(array('name'=>$name));
- } //end func setName
-
- // }}}
- // {{{ getName()
-
- /**
- * Returns the element name
- *
- * @since 1.0
- * @access public
- * @return string
- * @throws
- */
- function getName()
- {
- return $this->getAttribute('name');
- } //end func getName
-
- // }}}
- // {{{ setValue()
-
- /**
- * Sets value for textarea element
- *
- * @param string $value Value for password element
- * @since 1.0
- * @access public
- * @return void
- * @throws
- */
- function setValue($value)
- {
- return;
- } //end func setValue
-
- // }}}
- // {{{ getValue()
-
- /**
- * Returns the value of the form element
- *
- * @since 1.0
- * @access public
- * @return void
- * @throws
- */
- function getValue()
- {
- return;
- } // end func getValue
-
-
- // }}}
- // {{{ setHref()
-
- /**
- * Sets the links href
- *
- * @param string $href
- * @since 1.0
- * @access public
- * @return void
- * @throws
- */
- function setHref($href)
- {
- $this->updateAttributes(array('href'=>$href));
- } // end func setHref
-
- // }}}
- // {{{ toHtml()
-
- /**
- * Returns the textarea element in HTML
- *
- * @since 1.0
- * @access public
- * @return string
- * @throws
- */
- function toHtml()
- {
- $tabs = $this->_getTabs();
- $html = "$tabs<a".$this->_getAttrString($this->_attributes).">";
- $html .= $this->_text;
- $html .= "</a>";
- return $html;
- } //end func toHtml
-
- // }}}
- // {{{ getFrozenHtml()
-
- /**
- * Returns the value of field without HTML tags (in this case, value is changed to a mask)
- *
- * @since 1.0
- * @access public
- * @return string
- * @throws
- */
- function getFrozenHtml()
- {
- return;
- } //end func getFrozenHtml
-
- // }}}
-
-} //end class HTML_QuickForm_textarea
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP version 4.0 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997, 1998, 1999, 2000, 2001 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Adam Daniel <adaniel1@eesus.jnj.com> |
-// | Bertrand Mansion <bmansion@mamasam.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: password.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-require_once("HTML/QuickForm/input.php");
-
-/**
- * HTML class for a password type field
- *
- * @author Adam Daniel <adaniel1@eesus.jnj.com>
- * @author Bertrand Mansion <bmansion@mamasam.com>
- * @version 1.1
- * @since PHP4.04pl1
- * @access public
- */
-class HTML_QuickForm_password extends HTML_QuickForm_input
-{
- // {{{ constructor
-
- /**
- * Class constructor
- *
- * @param string $elementName (optional)Input field name attribute
- * @param string $elementLabel (optional)Input field label
- * @param mixed $attributes (optional)Either a typical HTML attribute string
- * or an associative array
- * @since 1.0
- * @access public
- * @return void
- * @throws
- */
- function HTML_QuickForm_password($elementName=null, $elementLabel=null, $attributes=null)
- {
- HTML_QuickForm_input::HTML_QuickForm_input($elementName, $elementLabel, $attributes);
- $this->setType('password');
- } //end constructor
-
- // }}}
- // {{{ setSize()
-
- /**
- * Sets size of password element
- *
- * @param string $size Size of password field
- * @since 1.0
- * @access public
- * @return void
- */
- function setSize($size)
- {
- $this->updateAttributes(array('size'=>$size));
- } //end func setSize
-
- // }}}
- // {{{ setMaxlength()
-
- /**
- * Sets maxlength of password element
- *
- * @param string $maxlength Maximum length of password field
- * @since 1.0
- * @access public
- * @return void
- */
- function setMaxlength($maxlength)
- {
- $this->updateAttributes(array('maxlength'=>$maxlength));
- } //end func setMaxlength
-
- // }}}
- // {{{ getFrozenHtml()
-
- /**
- * Returns the value of field without HTML tags (in this case, value is changed to a mask)
- *
- * @since 1.0
- * @access public
- * @return string
- * @throws
- */
- function getFrozenHtml()
- {
- $value = $this->getValue();
- return ('' != $value? '**********': ' ') .
- $this->_getPersistantData();
- } //end func getFrozenHtml
-
- // }}}
-
-} //end class HTML_QuickForm_password
-?>
+++ /dev/null
-/**
- * JavaScript functions to handle standard behaviors of a QuickForm advmultiselect element
- *
- * @category HTML
- * @package HTML_QuickForm_advmultiselect
- * @author Laurent Laville <pear@laurent-laville.org>
- * @copyright 2007 Laurent Laville
- * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: qfamsHandler.js,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @since File available since Release 1.3.0
- */
-
-/**
- * - qfamsInit -
- *
- * initialize onclick event handler for all checkbox element
- * of a QuickForm advmultiselect element with single select box.
- *
- * @return void
- * @public
- * @since 1.3.0
- */
-function qfamsInit()
-{
- if (window.qfamsName) {
- for (var e = 0; e < window.qfamsName.length; e++) {
- var div = document.getElementById('qfams_' + window.qfamsName[e]);
- var inputs = div.getElementsByTagName('input');
- for (var i = 0; i < inputs.length; i++) {
- inputs[i].onclick = qfamsUpdateLiveCounter;
- }
- }
- }
-}
-
-/**
- * - qfamsUpdateCounter -
- *
- * text tools to replace all childs of 'c' element by a new text node of 'v' value
- *
- * @param dom element c html element; <span> is best use in most case
- * @param string v new counter value
- *
- * @return void
- * @public
- * @since 1.3.0
- */
-function qfamsUpdateCounter(c, v)
-{
- if (c != null) {
- // remove all previous child nodes of 'c' element
- if (c.childNodes) {
- for (var i = 0; i < c.childNodes.length; i++) {
- c.removeChild(c.childNodes[i]);
- }
- }
- // add new text value 'v'
- var nodeText = document.createTextNode(v);
- c.appendChild(nodeText);
- }
-}
-
-/**
- * - qfamsUpdateLiveCounter -
- *
- * standard onclick event handler to dynamic change value of counter
- * that display current selection
- *
- * @return void
- * @private
- * @since 1.3.0
- */
-function qfamsUpdateLiveCounter()
-{
- var lbl = this.parentNode;
- var selectedCount = 0;
-
- // Find all the checkboxes...
- var div = lbl.parentNode;
- var inputs = div.getElementsByTagName('input');
- for (var i = 0; i < inputs.length; i++) {
- if (inputs[i].checked == 1) {
- selectedCount++;
- }
- }
- var e = div.id;
- var qfamsName = e.substring(e.indexOf('_', 0) + 1, e.length);
- // updates item count
- var span = document.getElementById(qfamsName + '_selected');
- qfamsUpdateCounter(span, selectedCount + '/' + inputs.length);
-}
-
-/**
- * - qfamsEditSelection -
- *
- * in single select box mode, edit current selection and update live counter
- *
- * @param string qfamsName QuickForm advmultiselect element name
- * @param integer selectMode Selection mode (0 = uncheck, 1 = check, 2 = toggle)
- *
- * @return void
- * @public
- * @since 1.3.0
- */
-function qfamsEditSelection(qfamsName, selectMode)
-{
- if (selectMode !== 0 && selectMode !== 1 && selectMode !== 2) {
- return;
- }
- var selectedCount = 0;
-
- // Find all the checkboxes...
- var fruit = document.getElementById('qfams_' + qfamsName);
- var inputs = fruit.getElementsByTagName('input');
-
- // Loop through all checkboxes (input element)
- for (var i = 0; i < inputs.length; i++) {
- if (selectMode == 2) {
- if (inputs[i].checked == 0) {
- inputs[i].checked = 1;
- } else if (inputs[i].checked == 1) {
- inputs[i].checked = 0;
- }
- } else {
- inputs[i].checked = selectMode;
- }
- if (inputs[i].checked == 1) {
- selectedCount++;
- }
- }
-
- // updates selected item count
- var span = document.getElementById(qfamsName + '_selected');
- qfamsUpdateCounter(span, selectedCount + '/' + inputs.length);
-}
-
-/**
- * - qfamsMoveSelection -
- *
- * in double select box mode, move current selection and update live counter
- *
- * @param string qfamsName QuickForm advmultiselect element name
- * @param dom element selectLeft Data source list
- * @param dom element selectRight Target data list
- * @param dom element selectHidden Full data source (selected, unselected)
- * private usage
- * @param string action Action name (add, remove, all, none, toggle)
- * @param string arrange Sort option (none, asc, desc)
- *
- * @return void
- * @public
- * @since 1.3.0
- */
-function qfamsMoveSelection(qfamsName, selectLeft, selectRight, selectHidden, action, arrange)
-{
- if (action == 'add' || action == 'all' || action == 'toggle') {
- var source = selectLeft;
- var target = selectRight;
- } else {
- var source = selectRight;
- var target = selectLeft;
- }
- // Don't do anything if nothing selected. Otherwise we throw javascript errors.
- if (source.selectedIndex == -1 && (action == 'add' || action == 'remove')) {
- return;
- }
-
- var maxTo = target.length;
-
- // Add items to the 'TO' list.
- for (var i = 0; i < source.length; i++) {
- if (action == 'all' || action == 'none' || action == 'toggle' || source.options[i].selected == true ) {
- target.options[target.length]= new Option(source.options[i].text, source.options[i].value);
- }
- }
-
- // Remove items from the 'FROM' list.
- for (var i = (source.length - 1); i >= 0; i--){
- if (action == 'all' || action == 'none' || action == 'toggle' || source.options[i].selected == true) {
- source.options[i] = null;
- }
- }
-
- // Add items to the 'FROM' list for toggle function
- if (action == 'toggle') {
- for (var i = 0; i < maxTo; i++) {
- source.options[source.length]= new Option(target.options[i].text, target.options[i].value);
- }
- for (var i = (maxTo - 1); i >= 0; i--) {
- target.options[i] = null;
- }
- }
-
- // updates unselected item count
- var c = document.getElementById(qfamsName + '_unselected');
- var s = document.getElementById('__' + qfamsName);
- qfamsUpdateCounter(c, s.length);
-
- // updates selected item count
- var c = document.getElementById(qfamsName + '_selected');
- var s = document.getElementById('_' + qfamsName);
- qfamsUpdateCounter(c, s.length);
-
- // Sort list if required
- if (arrange !== 'none') {
- qfamsSortList(target, qfamsCompareText, arrange);
- }
-
- // Set the appropriate items as 'selected in the hidden select.
- // These are the values that will actually be posted with the form.
- qfamsUpdateHidden(selectHidden, selectRight);
-}
-
-/**
- * - qfamsSortList -
- *
- * sort selection list if option is given in HTML_QuickForm_advmultiselect class constructor
- *
- * @param dom element list Selection data list
- * @param prototype compareFunction to sort each element of a list
- * @param string arrange Sort option (none, asc, desc)
- *
- * @return void
- * @private
- * @since 1.3.0
- */
-function qfamsSortList(list, compareFunction, arrange)
-{
- var options = new Array (list.options.length);
- for (var i = 0; i < options.length; i++) {
- options[i] = new Option (
- list.options[i].text,
- list.options[i].value,
- list.options[i].defaultSelected,
- list.options[i].selected
- );
- }
- options.sort(compareFunction);
- if (arrange == 'desc') {
- options.reverse();
- }
- list.options.length = 0;
- for (var i = 0; i < options.length; i++) {
- list.options[i] = options[i];
- }
-}
-
-/**
- * - qfamsCompareText -
- *
- * callback function to sort each element of two lists A and B
- *
- * @param string option1 single element of list A
- * @param string option2 single element of list B
- *
- * @return integer -1 if option1 is less than option2,
- * 0 if option1 is equal to option2
- * 1 if option1 is greater than option2
- * @private
- * @since 1.3.0
- */
-function qfamsCompareText(option1, option2)
-{
- if (option1.text == option2.text) {
- return 0;
- }
- return option1.text < option2.text ? -1 : 1;
-}
-
-/**
- * - qfamsUpdateHidden -
- *
- * update private list that handle selection of all elements (selected and unselected)
- *
- * @param dom element h hidden list (contains all elements)
- * @param dom element r selection list (contains only elements selected)
- *
- * @return void
- * @private
- * @since 1.3.0
- */
-function qfamsUpdateHidden(h, r)
-{
- for (var i = 0; i < h.length; i++) {
- h.options[i].selected = false;
- }
-
- for (var i = 0; i < r.length; i++) {
- h.options[h.length] = new Option(r.options[i].text, r.options[i].value);
- h.options[h.length - 1].selected = true;
- }
-}
-
-/**
- * - qfamsMoveUp -
- *
- * User-End may arrange and element up to the selection list
- *
- * @param dom element l selection list (contains only elements selected)
- * @param dom element h hidden list (contains all elements)
- *
- * @return void
- * @public
- * @since 1.3.0
- */
-function qfamsMoveUp(l, h)
-{
- var indice = l.selectedIndex;
- if (indice < 0) {
- return;
- }
- if (indice > 0) {
- qfamsMoveSwap(l, indice, indice - 1);
- qfamsUpdateHidden(h, l);
- }
-}
-
-/**
- * - qfamsMoveDown -
- *
- * User-End may arrange and element down to the selection list
- *
- * @param dom element l selection list (contains only elements selected)
- * @param dom element h hidden list (contains all elements)
- *
- * @return void
- * @public
- * @since 1.3.0
- */
-function qfamsMoveDown(l, h)
-{
- var indice = l.selectedIndex;
- if (indice < 0) {
- return;
- }
- if (indice < l.options.length - 1) {
- qfamsMoveSwap(l, indice, indice + 1);
- qfamsUpdateHidden(h, l);
- }
-}
-
-/**
- * - qfamsMoveSwap -
- *
- * User-End may invert two elements position in the selection list
- *
- * @param dom element l selection list (contains only elements selected)
- * @param integer i element source indice
- * @param integer j element target indice
- *
- * @return void
- * @public
- * @since 1.3.0
- */
-function qfamsMoveSwap(l, i, j)
-{
- var valeur = l.options[i].value;
- var texte = l.options[i].text;
- l.options[i].value = l.options[j].value;
- l.options[i].text = l.options[j].text;
- l.options[j].value = valeur;
- l.options[j].text = texte;
- l.selectedIndex = j;
-}
-
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP version 4.0 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997, 1998, 1999, 2000, 2001 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Adam Daniel <adaniel1@eesus.jnj.com> |
-// | Bertrand Mansion <bmansion@mamasam.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: radio.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-require_once('HTML/QuickForm/input.php');
-
-/**
- * HTML class for a radio type element
- *
- * @author Adam Daniel <adaniel1@eesus.jnj.com>
- * @author Bertrand Mansion <bmansion@mamasam.com>
- * @version 1.1
- * @since PHP4.04pl1
- * @access public
- */
-class HTML_QuickForm_radio extends HTML_QuickForm_input
-{
- // {{{ properties
-
- /**
- * Radio display text
- * @var string
- * @since 1.1
- * @access private
- */
- var $_text = '';
-
- // }}}
- // {{{ constructor
-
- /**
- * Class constructor
- *
- * @param string Input field name attribute
- * @param mixed Label(s) for a field
- * @param string Text to display near the radio
- * @param string Input field value
- * @param mixed Either a typical HTML attribute string or an associative array
- * @since 1.0
- * @access public
- * @return void
- */
- function HTML_QuickForm_radio($elementName=null, $elementLabel=null, $text=null, $value=null, $attributes=null)
- {
- $this->HTML_QuickForm_element($elementName, $elementLabel, $attributes);
- if (isset($value)) {
- $this->setValue($value);
- }
- $this->_persistantFreeze = true;
- $this->setType('radio');
- $this->_text = $text;
- $this->_generateId();
- } //end constructor
-
- // }}}
- // {{{ setChecked()
-
- /**
- * Sets whether radio button is checked
- *
- * @param bool $checked Whether the field is checked or not
- * @since 1.0
- * @access public
- * @return void
- */
- function setChecked($checked)
- {
- if (!$checked) {
- $this->removeAttribute('checked');
- } else {
- $this->updateAttributes(array('checked'=>'checked'));
- }
- } //end func setChecked
-
- // }}}
- // {{{ getChecked()
-
- /**
- * Returns whether radio button is checked
- *
- * @since 1.0
- * @access public
- * @return string
- */
- function getChecked()
- {
- return $this->getAttribute('checked');
- } //end func getChecked
-
- // }}}
- // {{{ toHtml()
-
- /**
- * Returns the radio element in HTML
- *
- * @since 1.0
- * @access public
- * @return string
- */
- function toHtml()
- {
- if (0 == strlen($this->_text)) {
- $label = '';
- } elseif ($this->_flagFrozen) {
- $label = $this->_text;
- } else {
- $label = '<label for="' . $this->getAttribute('id') . '">' . $this->_text . '</label>';
- }
- return HTML_QuickForm_input::toHtml() . $label;
- } //end func toHtml
-
- // }}}
- // {{{ getFrozenHtml()
-
- /**
- * Returns the value of field without HTML tags
- *
- * @since 1.0
- * @access public
- * @return string
- */
- function getFrozenHtml()
- {
- if ($this->getChecked()) {
- return '<tt>(x)</tt>' .
- $this->_getPersistantData();
- } else {
- return '<tt>( )</tt>';
- }
- } //end func getFrozenHtml
-
- // }}}
- // {{{ setText()
-
- /**
- * Sets the radio text
- *
- * @param string $text Text to display near the radio button
- * @since 1.1
- * @access public
- * @return void
- */
- function setText($text)
- {
- $this->_text = $text;
- } //end func setText
-
- // }}}
- // {{{ getText()
-
- /**
- * Returns the radio text
- *
- * @since 1.1
- * @access public
- * @return string
- */
- function getText()
- {
- return $this->_text;
- } //end func getText
-
- // }}}
- // {{{ onQuickFormEvent()
-
- /**
- * Called by HTML_QuickForm whenever form event is made on this element
- *
- * @param string $event Name of event
- * @param mixed $arg event arguments
- * @param object $caller calling object
- * @since 1.0
- * @access public
- * @return void
- */
- function onQuickFormEvent($event, $arg, &$caller)
- {
- switch ($event) {
- case 'updateValue':
- // constant values override both default and submitted ones
- // default values are overriden by submitted
- $value = $this->_findValue($caller->_constantValues);
- if (null === $value) {
- $value = $this->_findValue($caller->_submitValues);
- if (null === $value) {
- $value = $this->_findValue($caller->_defaultValues);
- }
- }
- if ($value == $this->getValue()) {
- $this->setChecked(true);
- } else {
- $this->setChecked(false);
- }
- break;
- case 'setGroupValue':
- if ($arg == $this->getValue()) {
- $this->setChecked(true);
- } else {
- $this->setChecked(false);
- }
- break;
- default:
- parent::onQuickFormEvent($event, $arg, $caller);
- }
- return true;
- } // end func onQuickFormLoad
-
- // }}}
- // {{{ exportValue()
-
- /**
- * Returns the value attribute if the radio is checked, null if it is not
- */
- function exportValue(&$submitValues, $assoc = false)
- {
- $value = $this->_findValue($submitValues);
- if (null === $value) {
- $value = $this->getChecked()? $this->getValue(): null;
- } elseif ($value != $this->getValue()) {
- $value = null;
- }
- return $this->_prepareValue($value, $assoc);
- }
-
- // }}}
-} //end class HTML_QuickForm_radio
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP version 4.0 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997, 1998, 1999, 2000, 2001 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Adam Daniel <adaniel1@eesus.jnj.com> |
-// | Bertrand Mansion <bmansion@mamasam.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: reset.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-require_once("HTML/QuickForm/input.php");
-
-/**
- * HTML class for a reset type element
- *
- * @author Adam Daniel <adaniel1@eesus.jnj.com>
- * @author Bertrand Mansion <bmansion@mamasam.com>
- * @version 1.1
- * @since PHP4.04pl1
- * @access public
- */
-class HTML_QuickForm_reset extends HTML_QuickForm_input
-{
- // {{{ constructor
-
- /**
- * Class constructor
- *
- * @param string $elementName (optional)Input field name attribute
- * @param string $value (optional)Input field value
- * @param mixed $attributes (optional)Either a typical HTML attribute string
- * or an associative array
- * @since 1.0
- * @access public
- * @return void
- */
- function HTML_QuickForm_reset($elementName=null, $value=null, $attributes=null)
- {
- HTML_QuickForm_input::HTML_QuickForm_input($elementName, null, $attributes);
- $this->setValue($value);
- $this->setType('reset');
- } //end constructor
-
- // }}}
- // {{{ freeze()
-
- /**
- * Freeze the element so that only its value is returned
- *
- * @access public
- * @return void
- */
- function freeze()
- {
- return false;
- } //end func freeze
-
- // }}}
-
-} //end class HTML_QuickForm_reset
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP version 4.0 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Adam Daniel <adaniel1@eesus.jnj.com> |
-// | Bertrand Mansion <bmansion@mamasam.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: select.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-require_once('HTML/QuickForm/element.php');
-
-/**
- * Class to dynamically create an HTML SELECT
- *
- * @author Adam Daniel <adaniel1@eesus.jnj.com>
- * @author Bertrand Mansion <bmansion@mamasam.com>
- * @version 1.0
- * @since PHP4.04pl1
- * @access public
- */
-class HTML_QuickForm_select extends HTML_QuickForm_element {
-
- // {{{ properties
-
- /**
- * Contains the select options
- *
- * @var array
- * @since 1.0
- * @access private
- */
- var $_options = array();
-
- /**
- * Default values of the SELECT
- *
- * @var string
- * @since 1.0
- * @access private
- */
- var $_values = null;
-
- // }}}
- // {{{ constructor
-
- /**
- * Class constructor
- *
- * @param string Select name attribute
- * @param mixed Label(s) for the select
- * @param mixed Data to be used to populate options
- * @param mixed Either a typical HTML attribute string or an associative array
- * @since 1.0
- * @access public
- * @return void
- */
- function HTML_QuickForm_select($elementName=null, $elementLabel=null, $options=null, $attributes=null)
- {
- HTML_QuickForm_element::HTML_QuickForm_element($elementName, $elementLabel, $attributes);
- $this->_persistantFreeze = true;
- $this->_type = 'select';
- if (isset($options)) {
- $this->load($options);
- }
- } //end constructor
-
- // }}}
- // {{{ apiVersion()
-
- /**
- * Returns the current API version
- *
- * @since 1.0
- * @access public
- * @return double
- */
- function apiVersion()
- {
- return 2.3;
- } //end func apiVersion
-
- // }}}
- // {{{ setSelected()
-
- /**
- * Sets the default values of the select box
- *
- * @param mixed $values Array or comma delimited string of selected values
- * @since 1.0
- * @access public
- * @return void
- */
- function setSelected($values)
- {
- if (is_string($values) && $this->getMultiple()) {
- $values = split("[ ]?,[ ]?", $values);
- }
- if (is_array($values)) {
- $this->_values = array_values($values);
- } else {
- $this->_values = array($values);
- }
- } //end func setSelected
-
- // }}}
- // {{{ getSelected()
-
- /**
- * Returns an array of the selected values
- *
- * @since 1.0
- * @access public
- * @return array of selected values
- */
- function getSelected()
- {
- return $this->_values;
- } // end func getSelected
-
- // }}}
- // {{{ setName()
-
- /**
- * Sets the input field name
- *
- * @param string $name Input field name attribute
- * @since 1.0
- * @access public
- * @return void
- */
- function setName($name)
- {
- $this->updateAttributes(array('name' => $name));
- } //end func setName
-
- // }}}
- // {{{ getName()
-
- /**
- * Returns the element name
- *
- * @since 1.0
- * @access public
- * @return string
- */
- function getName()
- {
- return $this->getAttribute('name');
- } //end func getName
-
- // }}}
- // {{{ getPrivateName()
-
- /**
- * Returns the element name (possibly with brackets appended)
- *
- * @since 1.0
- * @access public
- * @return string
- */
- function getPrivateName()
- {
- if ($this->getAttribute('multiple')) {
- return $this->getName() . '[]';
- } else {
- return $this->getName();
- }
- } //end func getPrivateName
-
- // }}}
- // {{{ setValue()
-
- /**
- * Sets the value of the form element
- *
- * @param mixed $values Array or comma delimited string of selected values
- * @since 1.0
- * @access public
- * @return void
- */
- function setValue($value)
- {
- $this->setSelected($value);
- } // end func setValue
-
- // }}}
- // {{{ getValue()
-
- /**
- * Returns an array of the selected values
- *
- * @since 1.0
- * @access public
- * @return array of selected values
- */
- function getValue()
- {
- return $this->_values;
- } // end func getValue
-
- // }}}
- // {{{ setSize()
-
- /**
- * Sets the select field size, only applies to 'multiple' selects
- *
- * @param int $size Size of select field
- * @since 1.0
- * @access public
- * @return void
- */
- function setSize($size)
- {
- $this->updateAttributes(array('size' => $size));
- } //end func setSize
-
- // }}}
- // {{{ getSize()
-
- /**
- * Returns the select field size
- *
- * @since 1.0
- * @access public
- * @return int
- */
- function getSize()
- {
- return $this->getAttribute('size');
- } //end func getSize
-
- // }}}
- // {{{ setMultiple()
-
- /**
- * Sets the select mutiple attribute
- *
- * @param bool $multiple Whether the select supports multi-selections
- * @since 1.2
- * @access public
- * @return void
- */
- function setMultiple($multiple)
- {
- if ($multiple) {
- $this->updateAttributes(array('multiple' => 'multiple'));
- } else {
- $this->removeAttribute('multiple');
- }
- } //end func setMultiple
-
- // }}}
- // {{{ getMultiple()
-
- /**
- * Returns the select mutiple attribute
- *
- * @since 1.2
- * @access public
- * @return bool true if multiple select, false otherwise
- */
- function getMultiple()
- {
- return (bool)$this->getAttribute('multiple');
- } //end func getMultiple
-
- // }}}
- // {{{ addOption()
-
- /**
- * Adds a new OPTION to the SELECT
- *
- * @param string $text Display text for the OPTION
- * @param string $value Value for the OPTION
- * @param mixed $attributes Either a typical HTML attribute string
- * or an associative array
- * @since 1.0
- * @access public
- * @return void
- */
- function addOption($text, $value, $attributes=null)
- {
- if (null === $attributes) {
- $attributes = array('value' => $value);
- } else {
- $attributes = $this->_parseAttributes($attributes);
- if (isset($attributes['selected'])) {
- // the 'selected' attribute will be set in toHtml()
- $this->_removeAttr('selected', $attributes);
- if (is_null($this->_values)) {
- $this->_values = array($value);
- } elseif (!in_array($value, $this->_values)) {
- $this->_values[] = $value;
- }
- }
- $this->_updateAttrArray($attributes, array('value' => $value));
- }
- $this->_options[] = array('text' => $text, 'attr' => $attributes);
- } // end func addOption
-
- // }}}
- // {{{ loadArray()
-
- /**
- * Loads the options from an associative array
- *
- * @param array $arr Associative array of options
- * @param mixed $values (optional) Array or comma delimited string of selected values
- * @since 1.0
- * @access public
- * @return PEAR_Error on error or true
- * @throws PEAR_Error
- */
- function loadArray($arr, $values=null)
- {
- if (!is_array($arr)) {
- return PEAR::raiseError('Argument 1 of HTML_Select::loadArray is not a valid array');
- }
- if (isset($values)) {
- $this->setSelected($values);
- }
- foreach ($arr as $key => $val) {
- // Warning: new API since release 2.3
- $this->addOption($val, $key);
- }
- return true;
- } // end func loadArray
-
- // }}}
- // {{{ loadDbResult()
-
- /**
- * Loads the options from DB_result object
- *
- * If no column names are specified the first two columns of the result are
- * used as the text and value columns respectively
- * @param object $result DB_result object
- * @param string $textCol (optional) Name of column to display as the OPTION text
- * @param string $valueCol (optional) Name of column to use as the OPTION value
- * @param mixed $values (optional) Array or comma delimited string of selected values
- * @since 1.0
- * @access public
- * @return PEAR_Error on error or true
- * @throws PEAR_Error
- */
- function loadDbResult(&$result, $textCol=null, $valueCol=null, $values=null)
- {
- if (!is_object($result) || !is_a($result, 'db_result')) {
- return PEAR::raiseError('Argument 1 of HTML_Select::loadDbResult is not a valid DB_result');
- }
- if (isset($values)) {
- $this->setValue($values);
- }
- $fetchMode = ($textCol && $valueCol) ? DB_FETCHMODE_ASSOC : DB_FETCHMODE_DEFAULT;
- while (is_array($row = $result->fetchRow($fetchMode)) ) {
- if ($fetchMode == DB_FETCHMODE_ASSOC) {
- $this->addOption($row[$textCol], $row[$valueCol]);
- } else {
- $this->addOption($row[0], $row[1]);
- }
- }
- return true;
- } // end func loadDbResult
-
- // }}}
- // {{{ loadQuery()
-
- /**
- * Queries a database and loads the options from the results
- *
- * @param mixed $conn Either an existing DB connection or a valid dsn
- * @param string $sql SQL query string
- * @param string $textCol (optional) Name of column to display as the OPTION text
- * @param string $valueCol (optional) Name of column to use as the OPTION value
- * @param mixed $values (optional) Array or comma delimited string of selected values
- * @since 1.1
- * @access public
- * @return void
- * @throws PEAR_Error
- */
- function loadQuery(&$conn, $sql, $textCol=null, $valueCol=null, $values=null)
- {
- if (is_string($conn)) {
- require_once('DB.php');
- $dbConn = &DB::connect($conn, true);
- if (DB::isError($dbConn)) {
- return $dbConn;
- }
- } elseif (is_subclass_of($conn, "db_common")) {
- $dbConn = &$conn;
- } else {
- return PEAR::raiseError('Argument 1 of HTML_Select::loadQuery is not a valid type');
- }
- $result = $dbConn->query($sql);
- if (DB::isError($result)) {
- return $result;
- }
- $this->loadDbResult($result, $textCol, $valueCol, $values);
- $result->free();
- if (is_string($conn)) {
- $dbConn->disconnect();
- }
- return true;
- } // end func loadQuery
-
- // }}}
- // {{{ load()
-
- /**
- * Loads options from different types of data sources
- *
- * This method is a simulated overloaded method. The arguments, other than the
- * first are optional and only mean something depending on the type of the first argument.
- * If the first argument is an array then all arguments are passed in order to loadArray.
- * If the first argument is a db_result then all arguments are passed in order to loadDbResult.
- * If the first argument is a string or a DB connection then all arguments are
- * passed in order to loadQuery.
- * @param mixed $options Options source currently supports assoc array or DB_result
- * @param mixed $param1 (optional) See function detail
- * @param mixed $param2 (optional) See function detail
- * @param mixed $param3 (optional) See function detail
- * @param mixed $param4 (optional) See function detail
- * @since 1.1
- * @access public
- * @return PEAR_Error on error or true
- * @throws PEAR_Error
- */
- function load(&$options, $param1=null, $param2=null, $param3=null, $param4=null)
- {
- switch (true) {
- case is_array($options):
- return $this->loadArray($options, $param1);
- break;
- case (is_a($options, 'db_result')):
- return $this->loadDbResult($options, $param1, $param2, $param3);
- break;
- case (is_string($options) && !empty($options) || is_subclass_of($options, "db_common")):
- return $this->loadQuery($options, $param1, $param2, $param3, $param4);
- break;
- }
- } // end func load
-
- // }}}
- // {{{ toHtml()
-
- /**
- * Returns the SELECT in HTML
- *
- * @since 1.0
- * @access public
- * @return string
- */
- function toHtml()
- {
- if ($this->_flagFrozen) {
- return $this->getFrozenHtml();
- } else {
- $tabs = $this->_getTabs();
- $strHtml = '';
-
- if ($this->getComment() != '') {
- $strHtml .= $tabs . '<!-- ' . $this->getComment() . " //-->\n";
- }
-
- if (!$this->getMultiple()) {
- $attrString = $this->_getAttrString($this->_attributes);
- } else {
- $myName = $this->getName();
- $this->setName($myName . '[]');
- $attrString = $this->_getAttrString($this->_attributes);
- $this->setName($myName);
- }
- $strHtml .= $tabs . '<select' . $attrString . ">\n";
-
- foreach ($this->_options as $option) {
- if (is_array($this->_values) && in_array((string)$option['attr']['value'], $this->_values)) {
- $this->_updateAttrArray($option['attr'], array('selected' => 'selected'));
- }
- $strHtml .= $tabs . "\t<option" . $this->_getAttrString($option['attr']) . '>' .
- $option['text'] . "</option>\n";
- }
-
- return $strHtml . $tabs . '</select>';
- }
- } //end func toHtml
-
- // }}}
- // {{{ getFrozenHtml()
-
- /**
- * Returns the value of field without HTML tags
- *
- * @since 1.0
- * @access public
- * @return string
- */
- function getFrozenHtml()
- {
- $value = array();
- if (is_array($this->_values)) {
- foreach ($this->_values as $key => $val) {
- for ($i = 0, $optCount = count($this->_options); $i < $optCount; $i++) {
- if ($val == $this->_options[$i]['attr']['value']) {
- $value[$key] = $this->_options[$i]['text'];
- break;
- }
- }
- }
- }
- $html = empty($value)? ' ': join('<br />', $value);
- if ($this->_persistantFreeze) {
- $name = $this->getPrivateName();
- // Only use id attribute if doing single hidden input
- if (1 == count($value)) {
- $id = $this->getAttribute('id');
- $idAttr = isset($id)? ' id="' . $id . '"': '';
- } else {
- $idAttr = '';
- }
- foreach ($value as $key => $item) {
- $html .= '<input type="hidden"' . $idAttr . ' name="' .
- $name . '" value="' . $this->_values[$key] . '" />';
- }
- }
- return $html;
- } //end func getFrozenHtml
-
- // }}}
- // {{{ exportValue()
-
- /**
- * We check the options and return only the values that _could_ have been
- * selected. We also return a scalar value if select is not "multiple"
- */
- function exportValue(&$submitValues, $assoc = false)
- {
- $value = $this->_findValue($submitValues);
- if (is_null($value)) {
- $value = $this->getValue();
- } elseif(!is_array($value)) {
- $value = array($value);
- }
- if (is_array($value) && !empty($this->_options)) {
- $cleanValue = null;
- foreach ($value as $v) {
- for ($i = 0, $optCount = count($this->_options); $i < $optCount; $i++) {
- if ($v == $this->_options[$i]['attr']['value']) {
- $cleanValue[] = $v;
- break;
- }
- }
- }
- } else {
- $cleanValue = $value;
- }
- if (is_array($cleanValue) && !$this->getMultiple()) {
- return $this->_prepareValue($cleanValue[0], $assoc);
- } else {
- return $this->_prepareValue($cleanValue, $assoc);
- }
- }
-
- // }}}
-} //end class HTML_QuickForm_select
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP version 4.0 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Adam Daniel <adaniel1@eesus.jnj.com> |
-// | Bertrand Mansion <bmansion@mamasam.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: static.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-require_once("HTML/QuickForm/element.php");
-
-/**
- * HTML class for static data
- *
- * @author Wojciech Gdela <eltehaem@poczta.onet.pl>
- * @access public
- */
-class HTML_QuickForm_static extends HTML_QuickForm_element {
-
- // {{{ properties
-
- /**
- * Display text
- * @var string
- * @access private
- */
- var $_text = null;
-
- // }}}
- // {{{ constructor
-
- /**
- * Class constructor
- *
- * @param string $elementLabel (optional)Label
- * @param string $text (optional)Display text
- * @access public
- * @return void
- */
- function HTML_QuickForm_static($elementName=null, $elementLabel=null, $text=null)
- {
- HTML_QuickForm_element::HTML_QuickForm_element($elementName, $elementLabel);
- $this->_persistantFreeze = false;
- $this->_type = 'static';
- $this->_text = $text;
- } //end constructor
-
- // }}}
- // {{{ setName()
-
- /**
- * Sets the element name
- *
- * @param string $name Element name
- * @access public
- * @return void
- */
- function setName($name)
- {
- $this->updateAttributes(array('name'=>$name));
- } //end func setName
-
- // }}}
- // {{{ getName()
-
- /**
- * Returns the element name
- *
- * @access public
- * @return string
- */
- function getName()
- {
- return $this->getAttribute('name');
- } //end func getName
-
- // }}}
- // {{{ setText()
-
- /**
- * Sets the text
- *
- * @param string $text
- * @access public
- * @return void
- */
- function setText($text)
- {
- $this->_text = $text;
- } // end func setText
-
- // }}}
- // {{{ setValue()
-
- /**
- * Sets the text (uses the standard setValue call to emulate a form element.
- *
- * @param string $text
- * @access public
- * @return void
- */
- function setValue($text)
- {
- $this->setText($text);
- } // end func setValue
-
- // }}}
- // {{{ toHtml()
-
- /**
- * Returns the static text element in HTML
- *
- * @access public
- * @return string
- */
- function toHtml()
- {
- return $this->_getTabs() . $this->_text;
- } //end func toHtml
-
- // }}}
- // {{{ getFrozenHtml()
-
- /**
- * Returns the value of field without HTML tags
- *
- * @access public
- * @return string
- */
- function getFrozenHtml()
- {
- return $this->toHtml();
- } //end func getFrozenHtml
-
- // }}}
- // {{{ onQuickFormEvent()
-
- /**
- * Called by HTML_QuickForm whenever form event is made on this element
- *
- * @param string $event Name of event
- * @param mixed $arg event arguments
- * @param object $caller calling object
- * @since 1.0
- * @access public
- * @return void
- * @throws
- */
- function onQuickFormEvent($event, $arg, &$caller)
- {
- switch ($event) {
- case 'updateValue':
- // do NOT use submitted values for static elements
- $value = $this->_findValue($caller->_constantValues);
- if (null === $value) {
- $value = $this->_findValue($caller->_defaultValues);
- }
- if (null !== $value) {
- $this->setValue($value);
- }
- break;
- default:
- parent::onQuickFormEvent($event, $arg, $caller);
- }
- return true;
- } // end func onQuickFormEvent
-
- // }}}
- // {{{ exportValue()
-
- /**
- * We override this here because we don't want any values from static elements
- */
- function exportValue(&$submitValues, $assoc = false)
- {
- return null;
- }
-
- // }}}
-} //end class HTML_QuickForm_static
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP version 4.0 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997, 1998, 1999, 2000, 2001 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Adam Daniel <adaniel1@eesus.jnj.com> |
-// | Bertrand Mansion <bmansion@mamasam.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: submit.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-require_once("HTML/QuickForm/input.php");
-
-/**
- * HTML class for a submit type element
- *
- * @author Adam Daniel <adaniel1@eesus.jnj.com>
- * @author Bertrand Mansion <bmansion@mamasam.com>
- * @version 1.0
- * @since PHP4.04pl1
- * @access public
- */
-class HTML_QuickForm_submit extends HTML_QuickForm_input
-{
- // {{{ constructor
-
- /**
- * Class constructor
- *
- * @param string Input field name attribute
- * @param string Input field value
- * @param mixed Either a typical HTML attribute string or an associative array
- * @since 1.0
- * @access public
- * @return void
- */
- function HTML_QuickForm_submit($elementName=null, $value=null, $attributes=null)
- {
- HTML_QuickForm_input::HTML_QuickForm_input($elementName, null, $attributes);
- $this->setValue($value);
- $this->setType('submit');
- } //end constructor
-
- // }}}
- // {{{ freeze()
-
- /**
- * Freeze the element so that only its value is returned
- *
- * @access public
- * @return void
- */
- function freeze()
- {
- return false;
- } //end func freeze
-
- // }}}
- // {{{ exportValue()
-
- /**
- * Only return the value if it is found within $submitValues (i.e. if
- * this particular submit button was clicked)
- */
- function exportValue(&$submitValues, $assoc = false)
- {
- return $this->_prepareValue($this->_findValue($submitValues), $assoc);
- }
-
- // }}}
-} //end class HTML_QuickForm_submit
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP version 4.0 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997, 1998, 1999, 2000, 2001 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Adam Daniel <adaniel1@eesus.jnj.com> |
-// | Bertrand Mansion <bmansion@mamasam.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: text.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-require_once("HTML/QuickForm/input.php");
-
-/**
- * HTML class for a text field
- *
- * @author Adam Daniel <adaniel1@eesus.jnj.com>
- * @author Bertrand Mansion <bmansion@mamasam.com>
- * @version 1.0
- * @since PHP4.04pl1
- * @access public
- */
-class HTML_QuickForm_text extends HTML_QuickForm_input
-{
-
- // {{{ constructor
-
- /**
- * Class constructor
- *
- * @param string $elementName (optional)Input field name attribute
- * @param string $elementLabel (optional)Input field label
- * @param mixed $attributes (optional)Either a typical HTML attribute string
- * or an associative array
- * @since 1.0
- * @access public
- * @return void
- */
- function HTML_QuickForm_text($elementName=null, $elementLabel=null, $attributes=null)
- {
- HTML_QuickForm_input::HTML_QuickForm_input($elementName, $elementLabel, $attributes);
- $this->_persistantFreeze = true;
- $this->setType('text');
- } //end constructor
-
- // }}}
- // {{{ setSize()
-
- /**
- * Sets size of text field
- *
- * @param string $size Size of text field
- * @since 1.3
- * @access public
- * @return void
- */
- function setSize($size)
- {
- $this->updateAttributes(array('size'=>$size));
- } //end func setSize
-
- // }}}
- // {{{ setMaxlength()
-
- /**
- * Sets maxlength of text field
- *
- * @param string $maxlength Maximum length of text field
- * @since 1.3
- * @access public
- * @return void
- */
- function setMaxlength($maxlength)
- {
- $this->updateAttributes(array('maxlength'=>$maxlength));
- } //end func setMaxlength
-
- // }}}
-
-} //end class HTML_QuickForm_text
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP version 4.0 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997, 1998, 1999, 2000, 2001 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Adam Daniel <adaniel1@eesus.jnj.com> |
-// | Bertrand Mansion <bmansion@mamasam.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: textarea.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-require_once("HTML/QuickForm/element.php");
-
-/**
- * HTML class for a textarea type field
- *
- * @author Adam Daniel <adaniel1@eesus.jnj.com>
- * @author Bertrand Mansion <bmansion@mamasam.com>
- * @version 1.0
- * @since PHP4.04pl1
- * @access public
- */
-class HTML_QuickForm_textarea extends HTML_QuickForm_element
-{
- // {{{ properties
-
- /**
- * Field value
- * @var string
- * @since 1.0
- * @access private
- */
- var $_value = null;
-
- // }}}
- // {{{ constructor
-
- /**
- * Class constructor
- *
- * @param string Input field name attribute
- * @param mixed Label(s) for a field
- * @param mixed Either a typical HTML attribute string or an associative array
- * @since 1.0
- * @access public
- * @return void
- */
- function HTML_QuickForm_textarea($elementName=null, $elementLabel=null, $attributes=null)
- {
- HTML_QuickForm_element::HTML_QuickForm_element($elementName, $elementLabel, $attributes);
- $this->_persistantFreeze = true;
- $this->_type = 'textarea';
- } //end constructor
-
- // }}}
- // {{{ setName()
-
- /**
- * Sets the input field name
- *
- * @param string $name Input field name attribute
- * @since 1.0
- * @access public
- * @return void
- */
- function setName($name)
- {
- $this->updateAttributes(array('name'=>$name));
- } //end func setName
-
- // }}}
- // {{{ getName()
-
- /**
- * Returns the element name
- *
- * @since 1.0
- * @access public
- * @return string
- */
- function getName()
- {
- return $this->getAttribute('name');
- } //end func getName
-
- // }}}
- // {{{ setValue()
-
- /**
- * Sets value for textarea element
- *
- * @param string $value Value for textarea element
- * @since 1.0
- * @access public
- * @return void
- */
- function setValue($value)
- {
- $this->_value = $value;
- } //end func setValue
-
- // }}}
- // {{{ getValue()
-
- /**
- * Returns the value of the form element
- *
- * @since 1.0
- * @access public
- * @return string
- */
- function getValue()
- {
- return $this->_value;
- } // end func getValue
-
- // }}}
- // {{{ setWrap()
-
- /**
- * Sets wrap type for textarea element
- *
- * @param string $wrap Wrap type
- * @since 1.0
- * @access public
- * @return void
- */
- function setWrap($wrap)
- {
- $this->updateAttributes(array('wrap' => $wrap));
- } //end func setWrap
-
- // }}}
- // {{{ setRows()
-
- /**
- * Sets height in rows for textarea element
- *
- * @param string $rows Height expressed in rows
- * @since 1.0
- * @access public
- * @return void
- */
- function setRows($rows)
- {
- $this->updateAttributes(array('rows' => $rows));
- } //end func setRows
-
- // }}}
- // {{{ setCols()
-
- /**
- * Sets width in cols for textarea element
- *
- * @param string $cols Width expressed in cols
- * @since 1.0
- * @access public
- * @return void
- */
- function setCols($cols)
- {
- $this->updateAttributes(array('cols' => $cols));
- } //end func setCols
-
- // }}}
- // {{{ toHtml()
-
- /**
- * Returns the textarea element in HTML
- *
- * @since 1.0
- * @access public
- * @return string
- */
- function toHtml()
- {
- if ($this->_flagFrozen) {
- return $this->getFrozenHtml();
- } else {
- return $this->_getTabs() .
- '<textarea' . $this->_getAttrString($this->_attributes) . '>' .
- // because we wrap the form later we don't want the text indented
- preg_replace("/(\r\n|\n|\r)/", '
', htmlspecialchars($this->_value)) .
- '</textarea>';
- }
- } //end func toHtml
-
- // }}}
- // {{{ getFrozenHtml()
-
- /**
- * Returns the value of field without HTML tags (in this case, value is changed to a mask)
- *
- * @since 1.0
- * @access public
- * @return string
- */
- function getFrozenHtml()
- {
- $value = htmlspecialchars($this->getValue());
- if ($this->getAttribute('wrap') == 'off') {
- $html = $this->_getTabs() . '<pre>' . $value."</pre>\n";
- } else {
- $html = nl2br($value)."\n";
- }
- return $html . $this->_getPersistantData();
- } //end func getFrozenHtml
-
- // }}}
-
-} //end class HTML_QuickForm_textarea
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Alexey Borzov <avb@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: xbutton.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-require_once 'HTML/QuickForm/element.php';
-
-/**
- * Class for HTML 4.0 <button> element
- *
- * @author Alexey Borzov <avb@php.net>
- * @since 3.2.3
- * @access public
- */
-class HTML_QuickForm_xbutton extends HTML_QuickForm_element
-{
- /**
- * Contents of the <button> tag
- * @var string
- * @access private
- */
- var $_content;
-
- /**
- * Class constructor
- *
- * @param string Button name
- * @param string Button content (HTML to add between <button></button> tags)
- * @param mixed Either a typical HTML attribute string or an associative array
- * @access public
- */
- function HTML_QuickForm_xbutton($elementName = null, $elementContent = null, $attributes = null)
- {
- $this->HTML_QuickForm_element($elementName, null, $attributes);
- $this->setContent($elementContent);
- $this->setPersistantFreeze(false);
- $this->_type = 'xbutton';
- }
-
-
- function toHtml()
- {
- return '<button' . $this->getAttributes(true) . '>' . $this->_content . '</button>';
- }
-
-
- function getFrozenHtml()
- {
- return $this->toHtml();
- }
-
-
- function freeze()
- {
- return false;
- }
-
-
- function setName($name)
- {
- $this->updateAttributes(array(
- 'name' => $name
- ));
- }
-
-
- function getName()
- {
- return $this->getAttribute('name');
- }
-
-
- function setValue($value)
- {
- $this->updateAttributes(array(
- 'value' => $value
- ));
- }
-
-
- function getValue()
- {
- return $this->getAttribute('value');
- }
-
-
- /**
- * Sets the contents of the button element
- *
- * @param string Button content (HTML to add between <button></button> tags)
- */
- function setContent($content)
- {
- $this->_content = $content;
- }
-
-
- function onQuickFormEvent($event, $arg, &$caller)
- {
- if ('updateValue' != $event) {
- return parent::onQuickFormEvent($event, $arg, $caller);
- } else {
- $value = $this->_findValue($caller->_constantValues);
- if (null === $value) {
- $value = $this->_findValue($caller->_defaultValues);
- }
- if (null !== $value) {
- $this->setValue($value);
- }
- }
- return true;
- }
-
-
- /**
- * Returns a 'safe' element's value
- *
- * The value is only returned if the button's type is "submit" and if this
- * particlular button was clicked
- */
- function exportValue(&$submitValues, $assoc = false)
- {
- if ('submit' == $this->getAttribute('type')) {
- return $this->_prepareValue($this->_findValue($submitValues), $assoc);
- } else {
- return null;
- }
- }
-}
-?>
+++ /dev/null
-<?php
-/**
- * Class representing a HTML form
- *
- * PHP version 5
- *
- * LICENSE:
- *
- * Copyright (c) 2006, 2007, Alexey Borzov <avb@php.net>,
- * Bertrand Mansion <golgote@mamasam.com>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * The names of the authors may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: QuickForm2.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_QuickForm2
- */
-
-/**
- * Abstract base class for QuickForm2 containers
- */
-require_once 'HTML/QuickForm2/Container.php';
-
-/**
- * Data source for HTML_QuickForm2 objects based on superglobal arrays
- */
-require_once 'HTML/QuickForm2/DataSource/SuperGlobal.php';
-
-/**
- * Class representing a HTML form
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @version Release: 0.2.0
- */
-class HTML_QuickForm2 extends HTML_QuickForm2_Container
-{
- /**
- * Data sources providing values for form elements
- * @var array
- */
- protected $datasources = array();
-
- /**
- * We do not allow setting "method" and "id" other than through constructor
- * @var array
- */
- protected $watchedAttributes = array('id', 'method');
-
- /**
- * Class constructor, form's "id" and "method" attributes can only be set here
- *
- * @param string "id" attribute of <form> tag
- * @param string HTTP method used to submit the form
- * @param mixed Additional attributes (either a string or an array)
- * @param bool Whether to track if the form was submitted by adding
- * a special hidden field
- */
- public function __construct($id, $method = 'post', $attributes = null, $trackSubmit = true)
- {
- $method = ('GET' == strtoupper($method))? 'get': 'post';
- if (empty($id)) {
- $id = self::generateId('');
- $trackSubmit = false;
- } else {
- self::storeId($id);
- }
- $this->attributes = array_merge(
- self::prepareAttributes($attributes),
- array('id' => (string)$id, 'method' => $method)
- );
- if (!isset($this->attributes['action'])) {
- $this->attributes['action'] = $_SERVER['PHP_SELF'];
- }
- if ($trackSubmit && isset($_REQUEST['_qf__' . $id]) ||
- !$trackSubmit && ('get' == $method && !empty($_GET) ||
- 'post' == $method && (!empty($_POST) || !empty($_FILES))))
- {
- $this->addDataSource(new HTML_QuickForm2_DataSource_SuperGlobal(
- $method, get_magic_quotes_gpc()
- ));
- }
- if ($trackSubmit) {
- $this->appendChild(HTML_QuickForm2_Factory::createElement(
- 'hidden', '_qf__' . $id
- ));
- }
- }
-
- protected function onAttributeChange($name, $value = null)
- {
- throw new HTML_QuickForm2_InvalidArgumentException(
- 'Attribute \'' . $name . '\' is read-only'
- );
- }
-
- protected function setContainer(HTML_QuickForm2_Container $container = null)
- {
- throw new HTML_QuickForm2_Exception('Form cannot be added to container');
- }
-
- public function setId($id = null)
- {
- throw new HTML_QuickForm2_InvalidArgumentException(
- "Attribute 'id' is read-only"
- );
- }
-
-
- /**
- * Adds a new data source to the form
- *
- * @param HTML_QuickForm2_DataSource Data source
- */
- public function addDataSource(HTML_QuickForm2_DataSource $datasource)
- {
- $this->datasources[] = $datasource;
- $this->updateValue();
- }
-
- /**
- * Replaces the list of form's data sources with a completely new one
- *
- * @param array A new data source list
- * @throws HTML_QuickForm2_InvalidArgumentException if given array
- * contains something that is not a valid data source
- */
- public function setDataSources(array $datasources)
- {
- foreach ($datasources as $ds) {
- if (!$ds instanceof HTML_QuickForm2_DataSource) {
- throw new HTML_QuickForm2_InvalidArgumentException(
- 'Array should contain only DataSource instances'
- );
- }
- }
- $this->datasources = $datasources;
- $this->updateValue();
- }
-
- /**
- * Returns the list of data sources attached to the form
- *
- * @return array
- */
- public function getDataSources()
- {
- return $this->datasources;
- }
-
- public function getType()
- {
- return 'form';
- }
-
- public function setValue($value)
- {
- throw new HTML_QuickForm2_Exception('Not implemented');
- }
-
- public function __toString()
- {
- throw new HTML_QuickForm2_Exception('Not implemented');
- }
-
- /**
- * Performs the server-side validation
- *
- * @return boolean Whether all form's elements are valid
- */
- public function validate()
- {
- $isSubmitted = false;
- foreach ($this->datasources as $ds) {
- if ($ds instanceof HTML_QuickForm2_DataSource_Submit) {
- $isSubmitted = true;
- break;
- }
- }
- return $isSubmitted? parent::validate(): false;
- }
-}
-?>
+++ /dev/null
-<?php
-/**
- * Base class for simple HTML_QuickForm2 containers
- *
- * PHP version 5
- *
- * LICENSE:
- *
- * Copyright (c) 2006, 2007, Alexey Borzov <avb@php.net>,
- * Bertrand Mansion <golgote@mamasam.com>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * The names of the authors may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: Container.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_QuickForm2
- */
-
-/**
- * Base class for all HTML_QuickForm2 elements
- */
-require_once 'HTML/QuickForm2/Node.php';
-
-/**
- * Abstract base class for simple QuickForm2 containers
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @version Release: 0.2.0
- */
-abstract class HTML_QuickForm2_Container extends HTML_QuickForm2_Node
- implements IteratorAggregate, Countable
-{
- /**
- * Array of elements contained in this container
- * @var array
- */
- protected $elements = array();
-
- /**
- * 'name' and 'id' attributes should be always present and their setting
- * should go through setName() and setId().
- * @var array
- */
- protected $watchedAttributes = array('id', 'name');
-
- protected function onAttributeChange($name, $value = null)
- {
- if ('name' == $name) {
- if (null === $value) {
- throw new HTML_QuickForm2_InvalidArgumentException(
- "Required attribute 'name' can not be removed"
- );
- } else {
- $this->setName($value);
- }
- } elseif ('id' == $name) {
- if (null === $value) {
- throw new HTML_QuickForm2_InvalidArgumentException(
- "Required attribute 'id' can not be removed"
- );
- } else {
- $this->setId($value);
- }
- }
- }
-
- public function getName()
- {
- return $this->attributes['name'];
- }
-
- public function setName($name)
- {
- $this->attributes['name'] = (string)$name;
- return $this;
- }
-
- public function getId()
- {
- return isset($this->attributes['id'])? $this->attributes['id']: null;
- }
-
- public function setId($id = null)
- {
- if (is_null($id)) {
- $id = self::generateId($this->getName());
- } else {
- self::storeId($id);
- }
- $this->attributes['id'] = (string)$id;
- return $this;
- }
-
- public function toggleFrozen($freeze = null)
- {
- if (null !== $freeze) {
- foreach ($this as $child) {
- $child->toggleFrozen($freeze);
- }
- }
- return parent::toggleFrozen($freeze);
- }
-
- public function persistentFreeze($persistent = null)
- {
- if (null !== $persistent) {
- foreach ($this as $child) {
- $child->persistentFreeze($persistent);
- }
- }
- return parent::persistentFreeze($persistent);
- }
-
- /**
- * Returns the element's value
- *
- * The default implementation for Containers is to return an array with
- * contained elements' values. The array is indexed the same way $_GET and
- * $_POST arrays would be for these elements.
- *
- * @return array|null
- */
- public function getValue()
- {
- $values = array();
- foreach ($this as $child) {
- $value = $child->getValue();
- if (null !== $value) {
- if ($child instanceof HTML_QuickForm2_Container) {
- $values = self::arrayMerge($values, $value);
- } else {
- $name = $child->getName();
- if (!strpos($name, '[')) {
- $values[$name] = $value;
- } else {
- $tokens = explode('[', str_replace(']', '', $name));
- $valueAry =& $values;
- do {
- $token = array_shift($tokens);
- if (!isset($valueAry[$token])) {
- $valueAry[$token] = array();
- }
- $valueAry =& $valueAry[$token];
- } while (count($tokens) > 1);
- $valueAry[$tokens[0]] = $value;
- }
- }
- }
- }
- return empty($values)? null: $values;
- }
-
- /**
- * Merges two arrays
- *
- * Merges two arrays like the PHP function array_merge_recursive does,
- * the difference being that existing integer keys will not be renumbered.
- *
- * @param array
- * @param array
- * @return array resulting array
- */
- protected static function arrayMerge($a, $b)
- {
- foreach ($b as $k => $v) {
- if (!is_array($v) || isset($a[$k]) && !is_array($a[$k])) {
- $a[$k] = $v;
- } else {
- $a[$k] = self::arrayMerge(isset($a[$k])? $a[$k]: array(), $v);
- }
- }
- return $a;
- }
-
- /**
- * Returns an array of this container's elements
- *
- * @return array Container elements
- */
- public function getElements()
- {
- return $this->elements;
- }
-
- /**
- * Appends an element to the container
- *
- * If the element was previously added to the container or to another
- * container, it is first removed there.
- *
- * @param HTML_QuickForm2_Node Element to add
- * @return HTML_QuickForm2_Node Added element
- * @throws HTML_QuickForm2_InvalidArgumentException
- */
- public function appendChild(HTML_QuickForm2_Node $element)
- {
- if ($this === $element->getContainer()) {
- $this->removeChild($element);
- }
- $element->setContainer($this);
- $this->elements[] = $element;
- return $element;
- }
-
- /**
- * Appends an element to the container (possibly creating it first)
- *
- * If the first parameter is an instance of HTML_QuickForm2_Node then all
- * other parameters are ignored and the method just calls {@link appendChild()}.
- * In the other case the element is first created via
- * {@link HTML_QuickForm2_Factory::createElement()} and then added via the
- * same method. This is a convenience method to reduce typing and ease
- * porting from HTML_QuickForm.
- *
- * @param string|HTML_QuickForm2_Node Either type name (treated
- * case-insensitively) or an element instance
- * @param mixed Element name
- * @param mixed Element attributes
- * @param array Element-specific data
- * @return HTML_QuickForm2_Node Added element
- * @throws HTML_QuickForm2_InvalidArgumentException
- * @throws HTML_QuickForm2_NotFoundException
- */
- public function addElement($elementOrType, $name = null, $attributes = null,
- array $data = array())
- {
- if ($elementOrType instanceof HTML_QuickForm2_Node) {
- return $this->appendChild($elementOrType);
- } else {
- return $this->appendChild(HTML_QuickForm2_Factory::createElement(
- $elementOrType, $name, $attributes, $data
- ));
- }
- }
-
- /**
- * Removes the element from this container
- *
- * If the reference object is not given, the element will be appended.
- *
- * @param HTML_QuickForm2_Node Element to remove
- * @return HTML_QuickForm2_Node Removed object
- */
- public function removeChild(HTML_QuickForm2_Node $element)
- {
-
- if ($element->getContainer() !== $this) {
- throw new HTML_QuickForm2_NotFoundException(
- "Element with name '".$element->getName()."' was not found"
- );
- }
- foreach ($this as $key => $child){
- if ($child === $element) {
- unset($this->elements[$key]);
- $element->setContainer(null);
- break;
- }
- }
- return $element;
- }
-
-
- /**
- * Returns an element if its id is found
- *
- * @param string Element id to find
- * @return HTML_QuickForm2_Node|null
- */
- public function getElementById($id)
- {
- foreach ($this->getRecursiveIterator() as $element) {
- if ($id == $element->getId()) {
- return $element;
- }
- }
- return null;
- }
-
- /**
- * Returns an array of elements which name corresponds to element
- *
- * @param string Elements name to find
- * @return array
- */
- public function getElementsByName($name)
- {
- $found = array();
- foreach ($this->getRecursiveIterator() as $element) {
- if ($element->getName() == $name) {
- $found[] = $element;
- }
- }
- return $found;
- }
-
- /**
- * Inserts an element in the container
- *
- * If the reference object is not given, the element will be appended.
- *
- * @param HTML_QuickForm2_Node Element to insert
- * @param HTML_QuickForm2_Node Reference to insert before
- * @return HTML_QuickForm2_Node Inserted element
- */
- public function insertBefore(HTML_QuickForm2_Node $element, HTML_QuickForm2_Node $reference = null)
- {
- if (null === $reference) {
- return $this->appendChild($element);
- }
- $offset = 0;
- foreach ($this as $child) {
- if ($child === $reference) {
- if ($this === $element->getContainer()) {
- $this->removeChild($element);
- }
- $element->setContainer($this);
- array_splice($this->elements, $offset, 0, array($element));
- return $element;
- }
- $offset++;
- }
- throw new HTML_QuickForm2_NotFoundException(
- "Reference element with name '".$reference->getName()."' was not found"
- );
- }
-
- /**
- * Returns a recursive iterator for the container elements
- *
- * @return HTML_QuickForm2_ContainerIterator
- */
- public function getIterator()
- {
- return new HTML_QuickForm2_ContainerIterator($this);
- }
-
- /**
- * Returns a recursive iterator iterator for the container elements
- *
- * @return RecursiveIteratorIterator
- */
- public function getRecursiveIterator()
- {
- return new RecursiveIteratorIterator(
- new HTML_QuickForm2_ContainerIterator($this),
- RecursiveIteratorIterator::SELF_FIRST
- );
- }
-
- /**
- * Returns the number of elements in the container
- *
- * @return int
- */
- public function count()
- {
- return count($this->elements);
- }
-
- /**
- * Called when the element needs to update its value from form's data sources
- *
- * The default behaviour is just to call the updateValue() methods of
- * contained elements, since default Container doesn't have any value itself
- */
- protected function updateValue()
- {
- foreach ($this as $child) {
- $child->updateValue();
- }
- }
-
-
- /**
- * Performs the server-side validation
- *
- * This method also calls validate() on all contained elements.
- *
- * @return boolean Whether the container and all contained elements are valid
- */
- protected function validate()
- {
- $valid = parent::validate();
- foreach ($this as $child) {
- $valid = $child->validate() && $valid;
- }
- return $valid;
- }
-
- /**
- * Appends an element to the container, creating it first
- *
- * The element will be created via {@link HTML_QuickForm2_Factory::createElement()}
- * and then added via the {@link appendChild()} method.
- * The element type is deduced from the method name. Camelcases will be
- * converted to underscores and lowercased.
- * This is a convenience method to reduce typing.
- *
- * @param mixed Element name
- * @param mixed Element attributes
- * @param array Element-specific data
- * @return HTML_QuickForm2_Node Added element
- * @throws HTML_QuickForm2_InvalidArgumentException
- * @throws HTML_QuickForm2_NotFoundException
- */
- public function __call($m, $a)
- {
- if (preg_match('/^(add)([a-zA-Z0-9_]+)$/', $m, $match)) {
- if ($match[1] == 'add') {
- $type = strtolower($match[2]);
- $name = isset($a[0]) ? $a[0] : null;
- $attr = isset($a[1]) ? $a[1] : null;
- $data = isset($a[2]) ? $a[2] : array();
- return $this->addElement($type, $name, $attr, $data);
- }
- }
- trigger_error("Fatal error: Call to undefined method ".get_class($this)."::".$m."()", E_USER_ERROR);
- }
-}
-
-/**
- * Implements a recursive iterator for the container elements
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @version Release: 0.2.0
- */
-class HTML_QuickForm2_ContainerIterator extends RecursiveArrayIterator implements RecursiveIterator
-{
- public function __construct(HTML_QuickForm2_Container $container)
- {
- parent::__construct($container->getElements());
- }
-
- public function hasChildren()
- {
- return $this->current() instanceof HTML_QuickForm2_Container;
- }
-
- public function getChildren()
- {
- return new HTML_QuickForm2_ContainerIterator($this->current());
- }
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/**
- * Base class for fieldsets
- *
- * PHP version 5
- *
- * LICENSE:
- *
- * Copyright (c) 2006, 2007, Alexey Borzov <avb@php.net>,
- * Bertrand Mansion <golgote@mamasam.com>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * The names of the authors may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: Fieldset.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_QuickForm2
- */
-
-/**
- * Base class for fieldsets
- */
-require_once 'HTML/QuickForm2/Container.php';
-
-/**
- * Concrete implementation of a container for fieldsets
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @version Release: 0.2.0
- */
-class HTML_QuickForm2_Container_Fieldset extends HTML_QuickForm2_Container
-{
- public function __toString()
- {
- $html = $this->getIndent() . '<fieldset' . $this->getAttributes(true) . '>';
- $this->setIndentLevel($this->getIndentLevel() + 1);
- $lf = self::getOption('linebreak');
-
- if ($this->getLabel()) {
- $legendId = $this->getId() . '-legend';
- $html .= $lf . $this->getIndent() . '<legend id="'.$legendId.'">' . $this->getLabel() . '</legend>';
- }
- foreach ($this->getRecursiveIterator() as $element) {
- $html .= $lf . $element->__toString();
- }
- $this->setIndentLevel($this->getIndentLevel() - 1);
- $html .= $lf . $this->getIndent() . '</fieldset>';
- return $html;
- }
-
- public function getType()
- {
- return 'fieldset';
- }
-
- protected function onAttributeChange($name, $value = null)
- {
- if ('name' == $name) {
- // Fieldsets do not have a name attribute
- } elseif ('id' == $name) {
- if (null === $value) {
- throw new HTML_QuickForm2_InvalidArgumentException(
- "Required attribute 'id' can not be removed"
- );
- } else {
- $this->setId($value);
- }
- }
- }
- public function getName()
- {
- return null;
- }
-
- public function setName($name)
- {
- // Fieldsets do not have a name attribute
- return $this;
- }
-
- public function setValue($value)
- {
- throw new HTML_QuickForm2_Exception('Not implemented');
- }
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/**
- * Interface for data sources used by HTML_QuickForm2 objects
- *
- * PHP version 5
- *
- * LICENSE:
- *
- * Copyright (c) 2006, 2007, Alexey Borzov <avb@php.net>,
- * Bertrand Mansion <golgote@mamasam.com>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * The names of the authors may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: DataSource.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_QuickForm2
- */
-
-/**
- * Interface for data sources used by HTML_QuickForm2 objects
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @version Release: 0.2.0
- * @todo Add filters handling
- */
-interface HTML_QuickForm2_DataSource
-{
- /**
- * Returns value for the element with the given name
- *
- * If data source doesn't have a requested value it should return null
- *
- * @param string Element's name
- * @return mixed Element's value
- */
- public function getValue($name);
-}
-?>
+++ /dev/null
-<?php
-/**
- * Array-based data source for HTML_QuickForm2 objects
- *
- * PHP version 5
- *
- * LICENSE:
- *
- * Copyright (c) 2006, 2007, Alexey Borzov <avb@php.net>,
- * Bertrand Mansion <golgote@mamasam.com>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * The names of the authors may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: Array.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_QuickForm2
- */
-
-/**
- * Interface for data sources used by HTML_QuickForm2 objects
- */
-require_once 'HTML/QuickForm2/DataSource.php';
-
-/**
- * Array-based data source for HTML_QuickForm2 objects
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @version Release: 0.2.0
- */
-class HTML_QuickForm2_DataSource_Array implements HTML_QuickForm2_DataSource
-{
- /**
- * Array containing elements' values
- * @var array
- */
- protected $values;
-
- /**
- * Class constructor, initializes the values array
- *
- * @param array Array containing the elements' values
- */
- public function __construct($values = array())
- {
- $this->values = $values;
- }
-
- public function getValue($name)
- {
- if (empty($this->values)) {
- return null;
- }
- if (strpos($name, '[')) {
- $tokens = explode('[', str_replace(']', '', $name));
- $value = $this->values;
- do {
- $token = array_shift($tokens);
- if (!isset($value[$token])) {
- return null;
- }
- $value = $value[$token];
- } while (!empty($tokens));
- return $value;
- } elseif (isset($this->values[$name])) {
- return $this->values[$name];
- } else {
- return null;
- }
- }
-}
-?>
+++ /dev/null
-<?php
-/**
- * Interface for data sources containing submitted values
- *
- * PHP version 5
- *
- * LICENSE:
- *
- * Copyright (c) 2006, 2007, Alexey Borzov <avb@php.net>,
- * Bertrand Mansion <golgote@mamasam.com>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * The names of the authors may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: Submit.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_QuickForm2
- */
-
-/**
- * Interface for data sources used by HTML_QuickForm2 objects
- */
-require_once 'HTML/QuickForm2/DataSource.php';
-
-/**
- * Interface for data sources containing submitted values
- *
- * This interface provides method for getting information on uploaded files.
- * Additionally some elements will only consider getting their values from data
- * sources implementing this interface.
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @version Release: 0.2.0
- * @todo Add filters handling
- */
-interface HTML_QuickForm2_DataSource_Submit extends HTML_QuickForm2_DataSource
-{
- /**
- * Returns the information about uploaded file
- *
- * If data source doesn't such information it should return null
- *
- * @param string Name of file upload field
- * @return array|null Information on uploaded file, from $_FILES array
- */
- public function getUpload($name);
-}
-?>
+++ /dev/null
-<?php
-/**
- * Data source for HTML_QuickForm2 objects based on superglobal arrays
- *
- * PHP version 5
- *
- * LICENSE:
- *
- * Copyright (c) 2006, 2007, Alexey Borzov <avb@php.net>,
- * Bertrand Mansion <golgote@mamasam.com>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * The names of the authors may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: SuperGlobal.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_QuickForm2
- */
-
-/**
- * Interface for data sources containing submitted values
- */
-require_once 'HTML/QuickForm2/DataSource/Submit.php';
-
-/**
- * Array-based data source for HTML_QuickForm2 objects
- */
-require_once 'HTML/QuickForm2/DataSource/Array.php';
-
-/**
- * Data source for HTML_QuickForm2 objects based on superglobal arrays
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @version Release: 0.2.0
- */
-class HTML_QuickForm2_DataSource_SuperGlobal
- extends HTML_QuickForm2_DataSource_Array
- implements HTML_QuickForm2_DataSource_Submit
-{
- /**
- * Information on file uploads (from $_FILES)
- * @var array
- */
- protected $files = array();
-
- /**
- * Keys present in the $_FILES array
- * @var array
- */
- private static $_fileKeys = array('name', 'type', 'size', 'tmp_name', 'error');
-
- /**
- * Class constructor, intializes the internal arrays from superglobals
- *
- * @param string Request method (GET or POST)
- * @param bool Whether magic_quotes_gpc directive is on
- */
- public function __construct($requestMethod = 'POST', $magicQuotesGPC = false)
- {
- if (!$magicQuotesGPC) {
- if ('GET' == strtoupper($requestMethod)) {
- $this->values = $_GET;
- } else {
- $this->values = $_POST;
- $this->files = $_FILES;
- }
- } else {
- if ('GET' == strtoupper($requestMethod)) {
- $this->values = $this->arrayMapRecursive('stripslashes', $_GET);
- } else {
- $this->values = $this->arrayMapRecursive('stripslashes', $_POST);
- foreach ($_FILES as $key1 => $val1) {
- foreach ($val1 as $key2 => $val2) {
- if ('name' == $key2) {
- $this->files[$key1][$key2] = $this->arrayMapRecursive(
- 'stripslashes', $val2
- );
- } else {
- $this->files[$key1][$key2] = $val2;
- }
- }
- }
- }
- }
- }
-
- /**
- * A recursive version of array_map() function
- *
- * @param callback Callback function to apply
- * @param mixed Input array
- * @return array with callback applied
- */
- protected function arrayMapRecursive($callback, $arr)
- {
- if (!is_array($arr)) {
- return call_user_func($callback, $arr);
- }
- $mapped = array();
- foreach ($arr as $k => $v) {
- $mapped[$k] = is_array($v)?
- $this->arrayMapRecursive($callback, $v):
- call_user_func($callback, $v);
- }
- return $mapped;
- }
-
- public function getUpload($name)
- {
- if (empty($this->files)) {
- return null;
- }
- if (false !== ($pos = strpos($name, '['))) {
- $tokens = explode('[', str_replace(']', '', $name));
- $base = array_shift($tokens);
- $value = array();
- if (!isset($this->files[$base]['name'])) {
- return null;
- }
- foreach (self::$_fileKeys as $key) {
- $value[$key] = $this->files[$base][$key];
- }
-
- do {
- $token = array_shift($tokens);
- if (!isset($value['name'][$token])) {
- return null;
- }
- foreach (self::$_fileKeys as $key) {
- $value[$key] = $value[$key][$token];
- }
- } while (!empty($tokens));
- return $value;
- } elseif(isset($this->files[$name])) {
- return $this->files[$name];
- } else {
- return null;
- }
- }
-}
-?>
+++ /dev/null
-<?php
-/**
- * Base class for simple HTML_QuickForm2 elements (not Containers)
- *
- * PHP version 5
- *
- * LICENSE:
- *
- * Copyright (c) 2006, 2007, Alexey Borzov <avb@php.net>,
- * Bertrand Mansion <golgote@mamasam.com>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * The names of the authors may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: Element.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_QuickForm2
- */
-
-/**
- * Base class for all HTML_QuickForm2 elements
- */
-require_once 'HTML/QuickForm2/Node.php';
-
-/**
- * Abstract base class for simple QuickForm2 elements (not Containers)
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @version Release: 0.2.0
- */
-abstract class HTML_QuickForm2_Element extends HTML_QuickForm2_Node
-{
- /**
- * 'name' and 'id' attributes should be always present and their setting
- * should go through setName() and setId().
- * @var array
- */
- protected $watchedAttributes = array('id', 'name');
-
- protected function onAttributeChange($name, $value = null)
- {
- if ('name' == $name) {
- if (null === $value) {
- throw new HTML_QuickForm2_InvalidArgumentException(
- "Required attribute 'name' can not be removed"
- );
- } else {
- $this->setName($value);
- }
- } elseif ('id' == $name) {
- if (null === $value) {
- throw new HTML_QuickForm2_InvalidArgumentException(
- "Required attribute 'id' can not be removed"
- );
- } else {
- $this->setId($value);
- }
- }
- }
-
- public function getName()
- {
- return $this->attributes['name'];
- }
-
- public function setName($name)
- {
- $this->attributes['name'] = (string)$name;
- $this->updateValue();
- return $this;
- }
-
- public function getId()
- {
- return isset($this->attributes['id'])? $this->attributes['id']: null;
- }
-
- public function setId($id = null)
- {
- if (is_null($id)) {
- $id = self::generateId($this->getName());
- } else {
- self::storeId($id);
- }
- $this->attributes['id'] = (string)$id;
- return $this;
- }
-
- /**
- * Generates hidden form field containing the element's value
- *
- * This is used to pass the frozen element's value if 'persistent freeze'
- * feature is on
- *
- * @return string
- */
- protected function getPersistentContent()
- {
- if (!$this->persistent || null === ($value = $this->getValue())) {
- return '';
- }
- return '<input type="hidden"' . self::getAttributesString(array(
- 'name' => $this->getName(),
- 'value' => $value,
- 'id' => $this->getId()
- )) . ' />';
- }
-
- /**
- * Called when the element needs to update its value from form's data sources
- *
- * The default behaviour is to go through the complete list of the data
- * sources until the non-null value is found.
- */
- protected function updateValue()
- {
- $name = $this->getName();
- foreach ($this->getDataSources() as $ds) {
- if (null !== ($value = $ds->getValue($name))) {
- $this->setValue($value);
- return;
- }
- }
- }
-}
-?>
+++ /dev/null
-<?php
-/**
- * Class for <button> elements
- *
- * PHP version 5
- *
- * LICENSE:
- *
- * Copyright (c) 2006, 2007, Alexey Borzov <avb@php.net>,
- * Bertrand Mansion <golgote@mamasam.com>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * The names of the authors may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: Button.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_QuickForm2
- */
-
-/**
- * Base class for simple HTML_QuickForm2 elements
- */
-require_once 'HTML/QuickForm2/Element.php';
-
-/**
- * Class for <button> elements
- *
- * Note that this element was named 'xbutton' in previous version of QuickForm,
- * the name 'button' being used for current 'inputbutton' element.
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @version Release: 0.2.0
- */
-class HTML_QuickForm2_Element_Button extends HTML_QuickForm2_Element
-{
- /**
- * Contains options and data used for the element creation
- * - content: Content to be displayed between <button></button> tags
- * @var array
- */
- protected $data = array('content' => '');
-
- /**
- * Element's submit value
- * @var string
- */
- protected $submitValue = null;
-
-
- public function getType()
- {
- return 'button';
- }
-
- /**
- * Buttons can not be frozen
- *
- * @param bool Whether element should be frozen or editable. This
- * parameter is ignored in case of buttons
- * @return bool Always returns false
- */
- public function toggleFrozen($freeze = null)
- {
- return false;
- }
-
- /**
- * Sets the contents of the button element
- *
- * @param string Button content (HTML to add between <button></button> tags)
- */
- function setContent($content)
- {
- $this->data['content'] = $content;
- }
-
- /**
- * Button's value cannot be set via this method
- *
- * @param mixed Element's value, this parameter is ignored
- * @return HTML_QuickForm2_Element_Button
- */
- public function setValue($value)
- {
- return $this;
- }
-
- /**
- * Returns the element's value
- *
- * The value is only returned if the following is true
- * - button has 'type' attribute set to 'submit' (or no 'type' attribute)
- * - the form was submitted by clicking on this button
- *
- * This method returns the actual value submitted by the browser. Note that
- * different browsers submit different values!
- *
- * @return string|null
- */
- public function getValue()
- {
- if ((empty($this->attributes['type']) || 'submit' == $this->attributes['type']) &&
- !$this->getAttribute('disabled'))
- {
- return $this->submitValue;
- } else {
- return null;
- }
- }
-
- public function __toString()
- {
- return $this->getIndent() . '<button' . $this->getAttributes(true) .
- '>' . $this->data['content'] . '</button>';
- }
-
- protected function updateValue()
- {
- foreach ($this->getDataSources() as $ds) {
- if ($ds instanceof HTML_QuickForm2_DataSource_Submit &&
- null !== ($value = $ds->getValue($this->getName())))
- {
- $this->submitValue = $value;
- return;
- }
- }
- $this->submitValue = null;
- }
-}
-?>
+++ /dev/null
-<?php
-/**
- * Base class for <input> elements
- *
- * PHP version 5
- *
- * LICENSE:
- *
- * Copyright (c) 2006, 2007, Alexey Borzov <avb@php.net>,
- * Bertrand Mansion <golgote@mamasam.com>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * The names of the authors may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: Input.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_QuickForm2
- */
-
-/**
- * Base class for simple HTML_QuickForm2 elements (not Containers)
- */
-require_once 'HTML/QuickForm2/Element.php';
-
-/**
- * Base class for <input> elements
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @version Release: 0.2.0
- */
-class HTML_QuickForm2_Element_Input extends HTML_QuickForm2_Element
-{
- /**
- * 'type' attribute should not be changeable
- * @var array
- */
- protected $watchedAttributes = array('id', 'name', 'type');
-
- protected function onAttributeChange($name, $value = null)
- {
- if ('type' == $name) {
- throw new HTML_QuickForm2_InvalidArgumentException(
- "Attribute 'type' is read-only"
- );
- }
- parent::onAttributeChange($name, $value);
- }
-
- public function getType()
- {
- return $this->attributes['type'];
- }
-
- public function setValue($value)
- {
- $this->setAttribute('value', $value);
- return $this;
- }
-
- public function getValue()
- {
- return $this->getAttribute('disabled')? null: $this->getAttribute('value');
- }
-
- public function __toString()
- {
- if ($this->frozen) {
- return $this->getFrozenHtml();
- } else {
- return '<input' . $this->getAttributes(true) . ' />';
- }
- }
-
- /**
- * Returns the field's value without HTML tags
- * @return string
- */
- protected function getFrozenHtml()
- {
- $value = $this->getAttribute('value');
- return (('' != $value)? htmlspecialchars($value, ENT_QUOTES, self::getOption('charset')): ' ') .
- $this->getPersistentContent();
- }
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/**
- * Class for <input type="button" /> elements
- *
- * PHP version 5
- *
- * LICENSE:
- *
- * Copyright (c) 2006, 2007, Alexey Borzov <avb@php.net>,
- * Bertrand Mansion <golgote@mamasam.com>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * The names of the authors may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: InputButton.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_QuickForm2
- */
-
-/**
- * Base class for <input> elements
- */
-require_once 'HTML/QuickForm2/Element/Input.php';
-
-/**
- * Class for <input type="button" /> elements
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @version Release: 0.2.0
- */
-class HTML_QuickForm2_Element_InputButton extends HTML_QuickForm2_Element_Input
-{
- protected $attributes = array('type' => 'button');
-
- /**
- * Buttons can not be frozen
- *
- * @param bool Whether element should be frozen or editable. This
- * parameter is ignored in case of buttons
- * @return bool Always returns false
- */
- public function toggleFrozen($freeze = null)
- {
- return false;
- }
-
- /**
- * Button elements cannot have any submit values
- *
- * @param mixed Element's value, this parameter is ignored
- * @return HTML_QuickForm2_Element_InputButton
- */
- public function setValue($value)
- {
- return $this;
- }
-
- /**
- * Button elements cannot have any submit values
- *
- * This method always returns null
- *
- * return string|null
- */
- public function getValue()
- {
- return null;
- }
-}
-?>
+++ /dev/null
-<?php
-/**
- * Base class for checkboxes and radios
- *
- * PHP version 5
- *
- * LICENSE:
- *
- * Copyright (c) 2006, 2007, Alexey Borzov <avb@php.net>,
- * Bertrand Mansion <golgote@mamasam.com>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * The names of the authors may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: InputCheckable.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_QuickForm2
- */
-
-/**
- * Base class for <input> elements
- */
-require_once 'HTML/QuickForm2/Element/Input.php';
-
-/**
- * Base class for <input> elements having 'checked' attribute (checkboxes and radios)
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @version Release: 0.2.0
- */
-class HTML_QuickForm2_Element_InputCheckable extends HTML_QuickForm2_Element_Input
-{
- protected $persistent = true;
-
- /**
- * HTML to represent the element in "frozen" state
- *
- * Array index "checked" contains HTML for element's "checked" state,
- * "unchecked" for not checked
- * @var array
- */
- protected $frozenHtml = array(
- 'checked' => 'On',
- 'unchecked' => 'Off'
- );
-
- /**
- * Contains options and data used for the element creation
- * - content: Label "glued" to a checkbox or radio
- * @var array
- */
- protected $data = array('content' => '');
-
-
- /**
- * Sets the label to be rendered glued to the element
- *
- * This label is returned by {@link __toString()} method with the element's
- * HTML. It is automatically wrapped into the <label> tag.
- *
- * @param string
- * @return HTML_QuickForm2_Element_InputCheckable
- */
- public function setContent($content)
- {
- $this->data['content'] = $content;
- return $this;
- }
-
- /**
- * Returns the label that will be "glued" to element's HTML
- *
- * @return string
- */
- public function getContent()
- {
- return $this->data['content'];
- }
-
-
- public function setValue($value)
- {
- if ((string)$value == $this->getAttribute('value')) {
- return $this->setAttribute('checked');
- } else {
- return $this->removeAttribute('checked');
- }
- }
-
- public function getValue()
- {
- if (!empty($this->attributes['checked']) && empty($this->attributes['disabled'])) {
- return $this->getAttribute('value');
- } else {
- return null;
- }
- }
-
- public function __toString()
- {
- if (0 == strlen($this->data['content'])) {
- $label = '';
- } elseif ($this->frozen) {
- $label = $this->data['content'];
- } else {
- $label = '<label for="' . htmlspecialchars(
- $this->getId(), ENT_QUOTES, self::getOption('charset')
- ) . '">' . $this->data['content'] . '</label>';
- }
- return parent::__toString() . $label;
- }
-
- public function getFrozenHtml()
- {
- if ($this->getAttribute('checked')) {
- return $this->frozenHtml['checked'] . $this->getPersistentContent();
- } else {
- return $this->frozenHtml['unchecked'];
- }
- }
-}
-?>
+++ /dev/null
-<?php
-/**
- * Class for <input type="checkbox" /> elements
- *
- * PHP version 5
- *
- * LICENSE:
- *
- * Copyright (c) 2006, 2007, Alexey Borzov <avb@php.net>,
- * Bertrand Mansion <golgote@mamasam.com>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * The names of the authors may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: InputCheckbox.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_QuickForm2
- */
-
-/**
- * Base class for checkboxes and radios
- */
-require_once 'HTML/QuickForm2/Element/InputCheckable.php';
-
-/**
- * Class for <input type="checkbox" /> elements
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @version Release: 0.2.0
- */
-class HTML_QuickForm2_Element_InputCheckbox extends HTML_QuickForm2_Element_InputCheckable
-{
- protected $attributes = array('type' => 'checkbox');
-
- protected $frozenHtml = array(
- 'checked' => '<tt>[x]</tt>',
- 'unchecked' => '<tt>[ ]</tt>'
- );
-
- public function __construct($name = null, $attributes = null, array $data = array())
- {
- parent::__construct($name, $attributes, $data);
- if (!$this->getAttribute('value')) {
- $this->setAttribute('value', 1);
- }
- }
-
- protected function updateValue()
- {
- $name = $this->getName();
- foreach ($this->getDataSources() as $ds) {
- if (null !== ($value = $ds->getValue($name)) ||
- $ds instanceof HTML_QuickForm2_DataSource_Submit)
- {
- $this->setValue($value);
- return;
- }
- }
- }
-}
-?>
+++ /dev/null
-<?php
-/**
- * Class for <input type="file" /> elements
- *
- * PHP version 5
- *
- * LICENSE:
- *
- * Copyright (c) 2006, 2007, Alexey Borzov <avb@php.net>,
- * Bertrand Mansion <golgote@mamasam.com>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * The names of the authors may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: InputFile.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_QuickForm2
- */
-
-/**
- * Base class for <input> elements
- */
-require_once 'HTML/QuickForm2/Element/Input.php';
-
-/**
- * Class for <input type="file" /> elements
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @version Release: 0.2.0
- */
-class HTML_QuickForm2_Element_InputFile extends HTML_QuickForm2_Element_Input
-{
- /**
- * Default language for error messages
- */
- const DEFAULT_LANGUAGE = 'en';
-
- /**
- * Localized error messages for PHP's file upload errors
- * @var array
- */
- protected $errorMessages = array(
- 'en' => array(
- UPLOAD_ERR_INI_SIZE => 'The uploaded file exceeds size permitted by PHP configuration (%d bytes)',
- UPLOAD_ERR_FORM_SIZE => 'The uploaded file exceeds the MAX_FILE_SIZE directive in HTML form (%d bytes)',
- UPLOAD_ERR_PARTIAL => 'The file was only partially uploaded',
- UPLOAD_ERR_NO_TMP_DIR => 'Server error: temporary directory is missing',
- UPLOAD_ERR_CANT_WRITE => 'Server error: failed to write the file to disk',
- UPLOAD_ERR_EXTENSION => 'File upload was stopped by extension'
- ),
- 'fr' => array(
- UPLOAD_ERR_INI_SIZE => 'Le fichier envoyé excède la taille autorisée par la configuration de PHP (%d octets)',
- UPLOAD_ERR_FORM_SIZE => 'Le fichier envoyé excède la taille de MAX_FILE_SIZE spécifiée dans le formulaire HTML (%d octets)',
- UPLOAD_ERR_PARTIAL => 'Le fichier n\'a été que partiellement téléchargé',
- UPLOAD_ERR_NO_TMP_DIR => 'Erreur serveur: le répertoire temporaire est manquant',
- UPLOAD_ERR_CANT_WRITE => 'Erreur serveur: échec de l\'écriture du fichier sur le disque',
- UPLOAD_ERR_EXTENSION => 'L\'envoi de fichier est arrêté par l\'extension'
- ),
- 'ru' => array(
- UPLOAD_ERR_INI_SIZE => 'Размер загруженного файла превосходит максимально разрешённый настройками PHP (%d байт)',
- UPLOAD_ERR_FORM_SIZE => 'Размер загруженного файла превосходит директиву MAX_FILE_SIZE, указанную в форме (%d байт)',
- UPLOAD_ERR_PARTIAL => 'Файл был загружен не полностью',
- UPLOAD_ERR_NO_TMP_DIR => 'Ошибка на сервере: отсутствует каталог для временных файлов',
- UPLOAD_ERR_CANT_WRITE => 'Ошибка на сервере: не удалось записать файл на диск',
- UPLOAD_ERR_EXTENSION => 'Загрузка файла была остановлена расширением'
- )
- );
-
- /**
- * Language to display error messages in
- * @var string
- */
- protected $language;
-
- /**
- * Information on uploaded file, from submit data source
- * @var array
- */
- protected $value = null;
-
- protected $attributes = array('type' => 'file');
-
-
- /**
- * Class constructor
- *
- * Possible keys in $data array are:
- * - 'language': language to display error messages in, it should either be
- * already available in the class or provided in 'errorMessages'
- * - 'errorMessages': an array of error messages with the following format
- * <pre>
- * 'language code 1' => array(
- * UPLOAD_ERR_... => 'message',
- * ...
- * UPLOAD_ERR_... => 'message'
- * ),
- * ...
- * 'language code N' => array(
- * ...
- * )
- * </pre>
- * Note that error messages for UPLOAD_ERR_INI_SIZE and UPLOAD_ERR_FORM_SIZE
- * may contain '%d' placeholders that will be automatically replaced by the
- * appropriate size limits. Note also that you don't need to provide messages
- * for every possible error code in the arrays, you may e.g. override just
- * one error message for a particular language.
- *
- * @param string Element name
- * @param mixed Attributes (either a string or an array)
- * @param array Data used to set up error messages for PHP's file
- * upload errors.
- */
- public function __construct($name = null, $attributes = null, array $data = array())
- {
- if (isset($data['errorMessages'])) {
- // neither array_merge() nor array_merge_recursive will do
- foreach ($data['errorMessages'] as $lang => $ary) {
- foreach ($ary as $code => $message) {
- $this->errorMessages[$lang][$code] = $message;
- }
- }
- unset($data['errorMessages']);
- }
- if (!isset($data['language'])) {
- $this->language = self::DEFAULT_LANGUAGE;
- } else {
- $this->language = isset($this->errorMessages[$data['language']])?
- $data['language']: self::DEFAULT_LANGUAGE;
- unset($data['language']);
- }
- parent::__construct($name, $attributes, $data);
- }
-
-
- /**
- * File upload elements cannot be frozen
- *
- * To properly "freeze" a file upload element one has to store the uploaded
- * file somewhere and store the file info in session. This is way outside
- * the scope of this class.
- *
- * @param bool Whether element should be frozen or editable. This
- * parameter is ignored in case of file uploads
- * @return bool Always returns false
- */
- public function toggleFrozen($freeze = null)
- {
- return false;
- }
-
- /**
- * Returns the information on uploaded file
- *
- * @return array|null
- */
- public function getValue()
- {
- return $this->value;
- }
-
- /**
- * File upload's value cannot be set here
- *
- * @param mixed Value for file element, this parameter is ignored
- * @return HTML_QuickForm2_Element_InputFile
- */
- public function setValue($value)
- {
- return $this;
- }
-
- protected function updateValue()
- {
- foreach ($this->getDataSources() as $ds) {
- if ($ds instanceof HTML_QuickForm2_DataSource_Submit) {
- $value = $ds->getUpload($this->getName());
- if (null !== $value) {
- $this->value = $value;
- return;
- }
- }
- }
- $this->value = null;
- }
-
- /**
- * Performs the server-side validation
- *
- * Before the Rules added to the element kick in, the element checks the
- * error code added to the $_FILES array by PHP. If the code isn't
- * UPLOAD_ERR_OK or UPLOAD_ERR_NO_FILE then a built-in error message will be
- * displayed and no further validation will take place.
- *
- * @return boolean Whether the element is valid
- */
- protected function validate()
- {
- if (strlen($this->error)) {
- return false;
- }
- if (isset($this->value['error']) &&
- !in_array($this->value['error'], array(UPLOAD_ERR_OK, UPLOAD_ERR_NO_FILE)))
- {
- if (isset($this->errorMessages[$this->language][$this->value['error']])) {
- $errorMessage = $this->errorMessages[$this->language][$this->value['error']];
- } else {
- $errorMessage = $this->errorMessages[self::DEFAULT_LANGUAGE][$this->value['error']];
- }
- if (UPLOAD_ERR_INI_SIZE == $this->value['error']) {
- $iniSize = ini_get('upload_max_filesize');
- $size = intval($iniSize);
- switch (strtoupper(substr($iniSize, -1))) {
- case 'G': $size *= 1024;
- case 'M': $size *= 1024;
- case 'K': $size *= 1024;
- }
-
- } elseif (UPLOAD_ERR_FORM_SIZE == $this->value['error']) {
- foreach ($this->getDataSources() as $ds) {
- if ($ds instanceof HTML_QuickForm2_DataSource_Submit) {
- $size = intval($ds->getValue('MAX_FILE_SIZE'));
- break;
- }
- }
- }
- $this->error = isset($size)? sprintf($errorMessage, $size): $errorMessage;
- return false;
- }
- return parent::validate();
- }
-}
-?>
+++ /dev/null
-<?php
-/**
- * Class for <input type="hidden" /> elements
- *
- * PHP version 5
- *
- * LICENSE:
- *
- * Copyright (c) 2006, 2007, Alexey Borzov <avb@php.net>,
- * Bertrand Mansion <golgote@mamasam.com>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * The names of the authors may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: InputHidden.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_QuickForm2
- */
-
-/**
- * Base class for <input> elements
- */
-require_once 'HTML/QuickForm2/Element/Input.php';
-
-/**
- * Class for <input type="hidden" /> elements
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @version Release: 0.2.0
- */
-class HTML_QuickForm2_Element_InputHidden extends HTML_QuickForm2_Element_Input
-{
- protected $attributes = array('type' => 'hidden');
-
- /**
- * Hidden elements can not be frozen
- *
- * @param bool Whether element should be frozen or editable. This
- * parameter is ignored in case of hidden elements
- * @return bool Always returns false
- */
- public function toggleFrozen($freeze = null)
- {
- return false;
- }
-}
-?>
+++ /dev/null
-<?php
-/**
- * Class for <input type="image" /> elements
- *
- * PHP version 5
- *
- * LICENSE:
- *
- * Copyright (c) 2006, 2007, Alexey Borzov <avb@php.net>,
- * Bertrand Mansion <golgote@mamasam.com>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * The names of the authors may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: InputImage.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_QuickForm2
- */
-
-/**
- * Base class for <input> elements
- */
-require_once 'HTML/QuickForm2/Element/Input.php';
-
-/**
- * Class for <input type="image" /> elements
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @version Release: 0.2.0
- */
-class HTML_QuickForm2_Element_InputImage extends HTML_QuickForm2_Element_Input
-{
- protected $attributes = array('type' => 'image');
-
- /**
- * Coordinates of user click within the image, array contains keys 'x' and 'y'
- * @var array
- */
- protected $coordinates = null;
-
- /**
- * Image buttons can not be frozen
- *
- * @param bool Whether element should be frozen or editable. This
- * parameter is ignored in case of image elements
- * @return bool Always returns false
- */
- public function toggleFrozen($freeze = null)
- {
- return false;
- }
-
- /**
- * Image button's value cannot be set via this method
- *
- * @param mixed Element's value, this parameter is ignored
- * @return HTML_QuickForm2_Element_InputImage
- */
- public function setValue($value)
- {
- return $this;
- }
-
- /**
- * Returns the element's value
- *
- * The value is only returned if the form was actually submitted and this
- * image button was clicked. Returns null in all other cases.
- *
- * @return array|null An array with keys 'x' and 'y' containing the
- * coordinates of user click if the image was clicked,
- * null otherwise
- */
- public function getValue()
- {
- return $this->getAttribute('disabled')? null: $this->coordinates;
- }
-
- /**
- * Returns the HTML representation of the element
- *
- * The method changes the element's name to foo[bar][] if it was foo[bar]
- * originally. If it is not done, then one of the click coordinates will be
- * lost, see {@link http://bugs.php.net/bug.php?id=745}
- *
- * @return string
- */
- public function __toString()
- {
- if (false === strpos($this->attributes['name'], '[') ||
- '[]' == substr($this->attributes['name'], -2))
- {
- return parent::__toString();
- } else {
- $this->attributes['name'] .= '[]';
- $html = parent::__toString();
- $this->attributes['name'] = substr($this->attributes['name'], 0, -2);
- return $html;
- }
- }
-
- protected function updateValue()
- {
- foreach ($this->getDataSources() as $ds) {
- if ($ds instanceof HTML_QuickForm2_DataSource_Submit) {
- $name = $this->getName();
- if (false === strpos($name, '[') &&
- null !== ($value = $ds->getValue($name . '_x')))
- {
- $this->coordinates = array(
- 'x' => $value,
- 'y' => $ds->getValue($name . '_y')
- );
- return;
-
- } elseif (false !== strpos($name, '[')) {
- if ('[]' == substr($name, -2)) {
- $name = substr($name, 0, -2);
- }
- if (null !== ($value = $ds->getValue($name))) {
- $this->coordinates = array(
- 'x' => $value[0],
- 'y' => $value[1]
- );
- return;
- }
- }
- }
- }
- $this->coordinates = null;
- }
-}
-?>
+++ /dev/null
-<?php
-/**
- * Class for <input type="password" /> elements
- *
- * PHP version 5
- *
- * LICENSE:
- *
- * Copyright (c) 2006, 2007, Alexey Borzov <avb@php.net>,
- * Bertrand Mansion <golgote@mamasam.com>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * The names of the authors may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: InputPassword.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_QuickForm2
- */
-
-/**
- * Base class for <input> elements
- */
-require_once 'HTML/QuickForm2/Element/Input.php';
-
-/**
- * Class for <input type="password" /> elements
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @version Release: 0.2.0
- */
-class HTML_QuickForm2_Element_InputPassword extends HTML_QuickForm2_Element_Input
-{
- protected $attributes = array('type' => 'password');
-
- protected function getFrozenHtml()
- {
- $value = $this->getValue();
- return (('' != $value)? '********': ' ') .
- $this->getPersistentContent();
- }
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/**
- * Class for <input type="radio" /> elements
- *
- * PHP version 5
- *
- * LICENSE:
- *
- * Copyright (c) 2006, 2007, Alexey Borzov <avb@php.net>,
- * Bertrand Mansion <golgote@mamasam.com>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * The names of the authors may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: InputRadio.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_QuickForm2
- */
-
-/**
- * Base class for checkboxes and radios
- */
-require_once 'HTML/QuickForm2/Element/InputCheckable.php';
-
-/**
- * Class for <input type="radio" /> elements
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @version Release: 0.2.0
- */
-class HTML_QuickForm2_Element_InputRadio extends HTML_QuickForm2_Element_InputCheckable
-{
- protected $attributes = array('type' => 'radio');
-
- protected $frozenHtml = array(
- 'checked' => '<tt>(x)</tt>',
- 'unchecked' => '<tt>( )</tt>'
- );
-}
-?>
+++ /dev/null
-<?php
-/**
- * Class for <input type="reset" /> elements
- *
- * PHP version 5
- *
- * LICENSE:
- *
- * Copyright (c) 2006, 2007, Alexey Borzov <avb@php.net>,
- * Bertrand Mansion <golgote@mamasam.com>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * The names of the authors may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: InputReset.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_QuickForm2
- */
-
-/**
- * Base class for <input> elements
- */
-require_once 'HTML/QuickForm2/Element/Input.php';
-
-/**
- * Class for <input type="reset" /> elements
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @version Release: 0.2.0
- */
-class HTML_QuickForm2_Element_InputReset extends HTML_QuickForm2_Element_Input
-{
- protected $attributes = array('type' => 'reset');
-
- /**
- * Reset buttons can not be frozen
- *
- * @param bool Whether element should be frozen or editable. This
- * parameter is ignored in case of reset buttons
- * @return bool Always returns false
- */
- public function toggleFrozen($freeze = null)
- {
- return false;
- }
-
- /**
- * Reset elements cannot have any submit values
- *
- * @param mixed Element's value, this parameter is ignored
- * @return HTML_QuickForm2_Element_InputReset
- */
- public function setValue($value)
- {
- return $this;
- }
-
- /**
- * Reset elements cannot have any submit values
- *
- * This method always returns null
- *
- * @return string|null
- */
- public function getValue()
- {
- return null;
- }
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/**
- * Class for <input type="submit" /> elements
- *
- * PHP version 5
- *
- * LICENSE:
- *
- * Copyright (c) 2006, 2007, Alexey Borzov <avb@php.net>,
- * Bertrand Mansion <golgote@mamasam.com>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * The names of the authors may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: InputSubmit.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_QuickForm2
- */
-
-/**
- * Base class for <input> elements
- */
-require_once 'HTML/QuickForm2/Element/Input.php';
-
-/**
- * Class for <input type="submit" /> elements
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @version Release: 0.2.0
- */
-class HTML_QuickForm2_Element_InputSubmit extends HTML_QuickForm2_Element_Input
-{
- protected $attributes = array('type' => 'submit');
-
- /**
- * Element's submit value
- * @var string
- */
- protected $submitValue = null;
-
-
- /**
- * Submit buttons can not be frozen
- *
- * @param bool Whether element should be frozen or editable. This
- * parameter is ignored in case of submit elements
- * @return bool Always returns false
- */
- public function toggleFrozen($freeze = null)
- {
- return false;
- }
-
- /**
- * Submit's value cannot be set via this method
- *
- * @param mixed Element's value, this parameter is ignored
- * @return HTML_QuickForm2_Element_InputSubmit
- */
- public function setValue($value)
- {
- return $this;
- }
-
- /**
- * Returns the element's value
- *
- * The value is only returned if the form was actually submitted and this
- * submit button was clicked. Returns null in all other cases
- *
- * @return string|null
- */
- public function getValue()
- {
- return $this->getAttribute('disabled')? null: $this->submitValue;
- }
-
- protected function updateValue()
- {
- foreach ($this->getDataSources() as $ds) {
- if ($ds instanceof HTML_QuickForm2_DataSource_Submit &&
- null !== ($value = $ds->getValue($this->getName())))
- {
- $this->submitValue = $value;
- return;
- }
- }
- $this->submitValue = null;
- }
-}
-?>
+++ /dev/null
-<?php
-/**
- * Class for <input type="text" /> elements
- *
- * PHP version 5
- *
- * LICENSE:
- *
- * Copyright (c) 2006, 2007, Alexey Borzov <avb@php.net>,
- * Bertrand Mansion <golgote@mamasam.com>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * The names of the authors may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: InputText.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_QuickForm2
- */
-
-/**
- * Base class for <input> elements
- */
-require_once 'HTML/QuickForm2/Element/Input.php';
-
-/**
- * Class for <input type="text" /> elements
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @version Release: 0.2.0
- */
-class HTML_QuickForm2_Element_InputText extends HTML_QuickForm2_Element_Input
-{
- protected $attributes = array('type' => 'text');
-}
-?>
+++ /dev/null
-<?php
-/**
- * Classes for <select> elements
- *
- * PHP version 5
- *
- * LICENSE:
- *
- * Copyright (c) 2006, 2007, Alexey Borzov <avb@php.net>,
- * Bertrand Mansion <golgote@mamasam.com>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * The names of the authors may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: Select.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_QuickForm2
- */
-
-/**
- * Base class for simple HTML_QuickForm2 elements
- */
-require_once 'HTML/QuickForm2/Element.php';
-
-
-/**
- * Collection of <option>s and <optgroup>s
- *
- * This class handles the output of <option> tags. The class is not intended to
- * be used directly.
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @version Release: 0.2.0
- */
-class HTML_QuickForm2_Element_Select_OptionContainer extends HTML_Common2
- implements IteratorAggregate, Countable
-{
- /**
- * List of options and optgroups in this container
- *
- * Options are stored as arrays (for performance reasons), optgroups as
- * instances of Optgroup class.
- *
- * @var array
- */
- protected $options = array();
-
- /**
- * Reference to parent <select>'s values
- * @var array
- */
- protected $values;
-
- /**
- * Reference to parent <select>'s possible values
- * @var array
- */
- protected $possibleValues;
-
-
- /**
- * Class constructor
- *
- * @param array Reference to values of parent <select> element
- * @param array Reference to possible values of parent <select> element
- */
- public function __construct(&$values, &$possibleValues)
- {
- $this->values =& $values;
- $this->possibleValues =& $possibleValues;
- }
-
- /**
- * Adds a new option
- *
- * Please note that if you pass 'selected' attribute in the $attributes
- * parameter then this option's value will be added to <select>'s values.
- *
- * @param string Option text
- * @param string 'value' attribute for <option> tag
- * @param mixed Additional attributes for <option> tag (either as a
- * string or as an associative array)
- */
- public function addOption($text, $value, $attributes = null)
- {
- if (null === $attributes) {
- $attributes = array('value' => (string)$value);
- } else {
- $attributes = self::prepareAttributes($attributes);
- if (isset($attributes['selected'])) {
- // the 'selected' attribute will be set in __toString()
- unset($attributes['selected']);
- if (!in_array($value, $this->values)) {
- $this->values[] = $value;
- }
- }
- $attributes['value'] = (string)$value;
- }
- if (!isset($attributes['disabled'])) {
- $this->possibleValues[(string)$value] = true;
- }
- $this->options[] = array('text' => $text, 'attr' => $attributes);
- }
-
- /**
- * Adds a new optgroup
- *
- * @param string 'label' attribute for optgroup tag
- * @param mixed Additional attributes for <optgroup> tag (either as a
- * string or as an associative array)
- * @return HTML_QuickForm2_Element_Select_Optgroup
- */
- public function addOptgroup($label, $attributes = null)
- {
- $optgroup = new HTML_QuickForm2_Element_Select_Optgroup(
- $this->values, $this->possibleValues,
- $label, $attributes
- );
- $this->options[] = $optgroup;
- return $optgroup;
- }
-
- /**
- * Returns an array of contained options
- *
- * @return array
- */
- public function getOptions()
- {
- return $this->options;
- }
-
- public function __toString()
- {
- $indentLvl = $this->getIndentLevel();
- $indent = $this->getIndent() . self::getOption('indent');
- $linebreak = self::getOption('linebreak');
- $html = '';
- $strValues = array_map('strval', $this->values);
- foreach ($this->options as $option) {
- if (is_array($option)) {
- if (in_array($option['attr']['value'], $strValues, true)) {
- $option['attr']['selected'] = 'selected';
- }
- $html .= $indent . '<option' .
- self::getAttributesString($option['attr']) .
- '>' . $option['text'] . '</option>' . $linebreak;
- } elseif ($option instanceof HTML_QuickForm2_Element_Select_OptionContainer) {
- $option->setIndentLevel($indentLvl + 1);
- $html .= $option->__toString();
- }
- }
- return $html;
- }
-
- /**
- * Returns an iterator over contained elements
- *
- * @return HTML_QuickForm2_Element_Select_OptionIterator
- */
- public function getIterator()
- {
- return new HTML_QuickForm2_Element_Select_OptionIterator($this->options);
- }
-
- /**
- * Returns a recursive iterator over contained elements
- *
- * @return RecursiveIteratorIterator
- */
- public function getRecursiveIterator()
- {
- return new RecursiveIteratorIterator(
- new HTML_QuickForm2_Element_Select_OptionIterator($this->options),
- RecursiveIteratorIterator::SELF_FIRST
- );
- }
-
- /**
- * Returns the number of options in the container
- *
- * @return int
- */
- public function count()
- {
- return count($this->options);
- }
-}
-
-
-/**
- * Class representing an <optgroup> tag
- *
- * Do not instantiate this class yourself, use
- * {@link HTML_QuickForm2_Element_Select::addOptgroup()} method
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @version Release: 0.2.0
- */
-class HTML_QuickForm2_Element_Select_Optgroup
- extends HTML_QuickForm2_Element_Select_OptionContainer
-{
- /**
- * Class constructor
- *
- * @param array Reference to values of parent <select> element
- * @param array Reference to possible values of parent <select> element
- * @param string 'label' attribute for optgroup tag
- * @param mixed Additional attributes for <optgroup> tag (either as a
- * string or as an associative array)
- */
- public function __construct(&$values, &$possibleValues, $label, $attributes = null)
- {
- parent::__construct($values, $possibleValues);
- $this->setAttributes($attributes);
- $this->attributes['label'] = (string)$label;
- }
-
- public function __toString()
- {
- $indent = $this->getIndent();
- $linebreak = self::getOption('linebreak');
- return $indent . '<optgroup' . $this->getAttributes(true) . '>' .
- $linebreak . parent::__toString() . $indent . '</optgroup>' . $linebreak;
- }
-}
-
-/**
- * Implements a recursive iterator for options arrays
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @version Release: 0.2.0
- */
-class HTML_QuickForm2_Element_Select_OptionIterator extends RecursiveArrayIterator
- implements RecursiveIterator
-{
- public function hasChildren()
- {
- return $this->current() instanceof HTML_QuickForm2_Element_Select_OptionContainer;
- }
-
- public function getChildren()
- {
- return new HTML_QuickForm2_Element_Select_OptionIterator(
- $this->current()->getOptions()
- );
- }
-}
-
-
-/**
- * Class representing a <select> element
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @version Release: 0.2.0
- */
-class HTML_QuickForm2_Element_Select extends HTML_QuickForm2_Element
-{
- protected $persistent = true;
-
- /**
- * Values for the select element (i.e. values of the selected options)
- * @var array
- */
- protected $values = array();
-
- /**
- * Possible values for select elements
- *
- * A value is considered possible if it is present as a value attribute of
- * some option and that option is not disabled.
- * @var array
- */
- protected $possibleValues = array();
-
-
- /**
- * Object containing options for the <select> element
- * @var HTML_QuickForm2_Element_Select_OptionContainer
- */
- protected $optionContainer;
-
- /**
- * Class constructor
- *
- * @param string Element name
- * @param mixed Attributes (either a string or an array)
- * @param array Data used to populate the element's options, passed to
- * {@link loadOptions()} method. Format:
- * <code>
- * $data = array('options' => array('option1', 'option2'));
- * </code>
- * @throws HTML_QuickForm2_InvalidArgumentException if junk is given in $options
- */
- public function __construct($name = null, $attributes = null, array $data = array())
- {
- $options = isset($data['options'])? $data['options']: array();
- unset($data['options']);
- parent::__construct($name, $attributes, $data);
- $this->loadOptions($options);
- }
-
- public function getType()
- {
- return 'select';
- }
-
- public function __toString()
- {
- if ($this->frozen) {
- return $this->getFrozenHtml();
- } else {
- if (empty($this->attributes['multiple'])) {
- $attrString = $this->getAttributes(true);
- } else {
- $this->attributes['name'] .= '[]';
- $attrString = $this->getAttributes(true);
- $this->attributes['name'] = substr($this->attributes['name'], 0, -2);
- }
- $indent = $this->getIndent();
- return $indent . '<select' . $attrString . '>' .
- self::getOption('linebreak') .
- $this->optionContainer->__toString() .
- $indent . '</select>';
- }
- }
-
- protected function getFrozenHtml()
- {
- if (null === ($value = $this->getValue())) {
- return ' ';
- }
- $valueHash = is_array($value)? array_flip($value): array($value => true);
- $options = array();
- foreach ($this->optionContainer->getRecursiveIterator() as $child) {
- if (is_array($child) && isset($valueHash[$child['attr']['value']]) &&
- empty($child['attr']['disabled']))
- {
- $options[] = $child['text'];
- }
- }
-
- $html = implode('<br />', $options);
- if ($this->persistent) {
- $name = $this->attributes['name'] .
- (empty($this->attributes['multiple'])? '': '[]');
- // Only use id attribute if doing single hidden input
- $idAttr = (1 == count($valueHash))? array('id' => $this->getId()): array();
- foreach ($valueHash as $key => $item) {
- $html .= '<input type="hidden"' . self::getAttributesString(array(
- 'name' => $name,
- 'value' => $key
- ) + $idAttr) . ' />';
- }
- }
- return $html;
- }
-
- /**
- * Returns the value of the <select> element
- *
- * Please note that the returned value may not necessarily be equal to that
- * passed to {@link setValue()}. It passes "intrinsic validation" confirming
- * that such value could possibly be submitted by this <select> element.
- * Specifically, this method will return null if the elements "disabled"
- * attribute is set, it will not return values if there are no options having
- * such a "value" attribute or if such options' "disabled" attribute is set.
- * It will also only return a scalar value for single selects, mimicking
- * the common browsers' behaviour.
- *
- * @return mixed "value" attribute of selected option in case of single
- * select, array of selected options' "value" attributes in
- * case of multiple selects, null if no options selected
- */
- public function getValue()
- {
- if (0 == count($this->optionContainer) || 0 == count($this->values) ||
- 0 == count($this->possibleValues) || !empty($this->attributes['disabled']))
- {
- return null;
- }
-
- $values = array();
- foreach ($this->values as $value) {
- if (!empty($this->possibleValues[$value])) {
- $values[] = $value;
- }
- }
- if (0 == count($values)) {
- return null;
- } elseif (!empty($this->attributes['multiple'])) {
- return $values;
- } elseif (1 == count($values)) {
- return $values[0];
- } else {
- // The <select> is not multiple, but several options are to be
- // selected. At least IE and Mozilla select the last selected
- // option in this case, we should do the same
- foreach ($this->optionContainer->getRecursiveIterator() as $child) {
- if (is_array($child) && in_array($child['attr']['value'], $values)) {
- $lastValue = $child['attr']['value'];
- }
- }
- return $lastValue;
- }
- }
-
- public function setValue($value)
- {
- if (is_array($value)) {
- $this->values = array_values($value);
- } else {
- $this->values = array($value);
- }
- return $this;
- }
-
- /**
- * Loads <option>s (and <optgroup>s) for select element
- *
- * The method expects a array of options and optgroups:
- * <pre>
- * array(
- * 'option value 1' => 'option text 1',
- * ...
- * 'option value N' => 'option text N',
- * 'optgroup label 1' => array(
- * 'option value' => 'option text',
- * ...
- * ),
- * ...
- * )
- * </pre>
- * If value is a scalar, then array key is treated as "value" attribute of
- * <option> and value as this <option>'s text. If value is an array, then
- * key is treated as a "label" attribute of <optgroup> and value as an
- * array of <option>s for this <optgroup>.
- *
- * If you need to specify additional attributes for <option> and <optgroup>
- * tags, then you need to use {@link addOption()} and {@link addOptgroup()}
- * methods instead of this one.
- *
- * @param array
- * @throws HTML_QuickForm2_InvalidArgumentException if junk is given in $options
- * @return HTML_QuickForm2_Element_Select
- */
- public function loadOptions(array $options)
- {
- $this->possibleValues = array();
- $this->optionContainer = new HTML_QuickForm2_Element_Select_OptionContainer(
- $this->values, $this->possibleValues
- );
- $this->loadOptionsFromArray($this->optionContainer, $options);
- return $this;
- }
-
-
- /**
- * Adds options from given array into given container
- *
- * @param HTML_QuickForm2_Element_Select_OptionContainer options will be
- * added to this container
- * @param array options array
- */
- protected function loadOptionsFromArray(
- HTML_QuickForm2_Element_Select_OptionContainer $container, $options
- )
- {
- foreach ($options as $key => $value) {
- if (is_array($value)) {
- $optgroup = $container->addOptgroup($key);
- $this->loadOptionsFromArray($optgroup, $value);
- } else {
- $container->addOption($value, $key);
- }
- }
- }
-
-
- /**
- * Adds a new option
- *
- * Please note that if you pass 'selected' attribute in the $attributes
- * parameter then this option's value will be added to <select>'s values.
- *
- * @param string Option text
- * @param string 'value' attribute for <option> tag
- * @param mixed Additional attributes for <option> tag (either as a
- * string or as an associative array)
- */
- public function addOption($text, $value, $attributes = null)
- {
- return $this->optionContainer->addOption($text, $value, $attributes);
- }
-
- /**
- * Adds a new optgroup
- *
- * @param string 'label' attribute for optgroup tag
- * @param mixed Additional attributes for <optgroup> tag (either as a
- * string or as an associative array)
- * @return HTML_QuickForm2_Element_Select_Optgroup
- */
- public function addOptgroup($label, $attributes = null)
- {
- return $this->optionContainer->addOptgroup($label, $attributes);
- }
-
- protected function updateValue()
- {
- if (!$this->getAttribute('multiple')) {
- parent::updateValue();
- } else {
- $name = $this->getName();
- foreach ($this->getDataSources() as $ds) {
- if (null !== ($value = $ds->getValue($name)) ||
- $ds instanceof HTML_QuickForm2_DataSource_Submit)
- {
- $this->setValue(null === $value? array(): $value);
- return;
- }
- }
- }
- }
-}
-?>
+++ /dev/null
-<?php
-/**
- * Class for <textarea> elements
- *
- * PHP version 5
- *
- * LICENSE:
- *
- * Copyright (c) 2006, 2007, Alexey Borzov <avb@php.net>,
- * Bertrand Mansion <golgote@mamasam.com>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * The names of the authors may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: Textarea.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_QuickForm2
- */
-
-/**
- * Base class for simple HTML_QuickForm2 elements
- */
-require_once 'HTML/QuickForm2/Element.php';
-
-/**
- * Class for <textarea> elements
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @version Release: 0.2.0
- */
-class HTML_QuickForm2_Element_Textarea extends HTML_QuickForm2_Element
-{
- protected $persistent = true;
-
- /**
- * Value for textarea field
- * @var string
- */
- protected $value = null;
-
- public function getType()
- {
- return 'textarea';
- }
-
- public function setValue($value)
- {
- $this->value = $value;
- return $this;
- }
-
- public function getValue()
- {
- return empty($this->attributes['disabled'])? $this->value: null;
- }
-
- public function __toString()
- {
- if ($this->frozen) {
- return $this->getFrozenHtml();
- } else {
- return $this->getIndent() . '<textarea' . $this->getAttributes(true) .
- '>' . preg_replace("/(\r\n|\n|\r)/", '
', htmlspecialchars(
- $this->value, ENT_QUOTES, self::getOption('charset')
- )) . '</textarea>';
- }
- }
-
- public function getFrozenHtml()
- {
- $value = htmlspecialchars($this->value, ENT_QUOTES, self::getOption('charset'));
- if ('off' == $this->getAttribute('wrap')) {
- $html = $this->getIndent() . '<pre>' . $value .
- '</pre>' . self::getOption('linebreak');
- } else {
- $html = nl2br($value) . self::getOption('linbebreak');
- }
- return $html . $this->getPersistentContent();
- }
-}
-?>
+++ /dev/null
-<?php
-/**
- * Exception classes for HTML_QuickForm2
- *
- * PHP version 5
- *
- * LICENSE:
- *
- * Copyright (c) 2006, 2007, Alexey Borzov <avb@php.net>,
- * Bertrand Mansion <golgote@mamasam.com>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * The names of the authors may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: Exception.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_QuickForm2
- */
-
-/**
- * Base class for exceptions in PEAR
- */
-require_once 'PEAR/Exception.php';
-
-/**
- * Base class for exceptions in HTML_QuickForm2 package
- *
- * Such a base class is required by the Exception RFC:
- * http://pear.php.net/pepr/pepr-proposal-show.php?id=132
- * It will rarely be thrown directly, its specialized subclasses will be
- * thrown most of the time.
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @version Release: 0.2.0
- */
-class HTML_QuickForm2_Exception extends PEAR_Exception
-{
-}
-
-/**
- * Exception that denotes some resource was not found
- *
- * One example is trying to instantiate a nonexistent class in Factory
- * <code>
- * try {
- * HTML_QuickForm2_Factory::registerElement('missing', 'NonExistent');
- * $el = HTML_QuickForm2_Factory::createElement('missing');
- * } catch (HTML_QuickForm2_NotFoundException $e) {
- * echo $e->getMessage();
- * }
- * </code>
- * This code fill output "Class 'NonExistent' does not exist and no file to load"
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @version Release: 0.2.0
- */
-class HTML_QuickForm2_NotFoundException extends HTML_QuickForm2_Exception
-{
-}
-
-/**
- * Exception that denotes invalid arguments were passed
- *
- * One example is trying to create an element of type which is unknown to Factory
- * <code>
- * try {
- * $el = HTML_QuickForm2_Factory::createElement('unknown');
- * } catch (HTML_QuickForm2_InvalidArgumentException $e) {
- * echo $e->getMessage();
- * }
- * </code>
- * This code will output "Element type 'unknown' is not known"
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @version Release: 0.2.0
- */
-class HTML_QuickForm2_InvalidArgumentException extends HTML_QuickForm2_Exception
-{
-}
-?>
+++ /dev/null
-<?php
-/**
- * Static Factory class for HTML_QuickForm2 package
- *
- * PHP version 5
- *
- * LICENSE:
- *
- * Copyright (c) 2006, 2007, Alexey Borzov <avb@php.net>,
- * Bertrand Mansion <golgote@mamasam.com>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * The names of the authors may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: Factory.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_QuickForm2
- */
-
-/**
- * Exception classes for HTML_QuickForm2
- */
-require_once 'HTML/QuickForm2/Exception.php';
-
-/**
- * Static factory class
- *
- * The class handles instantiation of Element and Rule objects as well as
- * registering of new Element and Rule classes.
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @version Release: 0.2.0
- */
-class HTML_QuickForm2_Factory
-{
- /**
- * List of element types known to Factory
- * @var array
- */
- protected static $elementTypes = array(
- 'button' => array('HTML_QuickForm2_Element_Button',
- 'HTML/QuickForm2/Element/Button.php'),
- 'checkbox' => array('HTML_QuickForm2_Element_InputCheckbox',
- 'HTML/QuickForm2/Element/InputCheckbox.php'),
- 'fieldset' => array('HTML_QuickForm2_Container_Fieldset',
- 'HTML/QuickForm2/Container/Fieldset.php'),
- 'file' => array('HTML_QuickForm2_Element_InputFile',
- 'HTML/QuickForm2/Element/InputFile.php'),
- 'hidden' => array('HTML_QuickForm2_Element_InputHidden',
- 'HTML/QuickForm2/Element/InputHidden.php'),
- 'image' => array('HTML_QuickForm2_Element_InputImage',
- 'HTML/QuickForm2/Element/InputImage.php'),
- 'inputbutton' => array('HTML_QuickForm2_Element_InputButton',
- 'HTML/QuickForm2/Element/InputButton.php'),
- 'password' => array('HTML_QuickForm2_Element_InputPassword',
- 'HTML/QuickForm2/Element/InputPassword.php'),
- 'radio' => array('HTML_QuickForm2_Element_InputRadio',
- 'HTML/QuickForm2/Element/InputRadio.php'),
- 'reset' => array('HTML_QuickForm2_Element_InputReset',
- 'HTML/QuickForm2/Element/InputReset.php'),
- 'select' => array('HTML_QuickForm2_Element_Select',
- 'HTML/QuickForm2/Element/Select.php'),
- 'submit' => array('HTML_QuickForm2_Element_InputSubmit',
- 'HTML/QuickForm2/Element/InputSubmit.php'),
- 'text' => array('HTML_QuickForm2_Element_InputText',
- 'HTML/QuickForm2/Element/InputText.php'),
- 'textarea' => array('HTML_QuickForm2_Element_Textarea',
- 'HTML/QuickForm2/Element/Textarea.php')
- );
-
- /**
- * List of registered rules
- * @var array
- */
- protected static $registeredRules = array(
- 'nonempty' => array('HTML_QuickForm2_Rule_Nonempty',
- 'HTML/QuickForm2/Rule/Nonempty.php'),
- 'empty' => array('HTML_QuickForm2_Rule_Empty',
- 'HTML/QuickForm2/Rule/Empty.php'),
- 'required' => array('HTML_QuickForm2_Rule_Required',
- 'HTML/QuickForm2/Rule/Required.php'),
- 'compare' => array('HTML_QuickForm2_Rule_Compare',
- 'HTML/QuickForm2/Rule/Compare.php'),
- 'eq' => array('HTML_QuickForm2_Rule_Compare',
- 'HTML/QuickForm2/Rule/Compare.php',
- array('operator' => '===')),
- 'neq' => array('HTML_QuickForm2_Rule_Compare',
- 'HTML/QuickForm2/Rule/Compare.php',
- array('operator' => '!==')),
- 'lt' => array('HTML_QuickForm2_Rule_Compare',
- 'HTML/QuickForm2/Rule/Compare.php',
- array('operator' => '<')),
- 'lte' => array('HTML_QuickForm2_Rule_Compare',
- 'HTML/QuickForm2/Rule/Compare.php',
- array('operator' => '<=')),
- 'gt' => array('HTML_QuickForm2_Rule_Compare',
- 'HTML/QuickForm2/Rule/Compare.php',
- array('operator' => '>')),
- 'gte' => array('HTML_QuickForm2_Rule_Compare',
- 'HTML/QuickForm2/Rule/Compare.php',
- array('operator' => '>=')),
- 'regex' => array('HTML_QuickForm2_Rule_Regex',
- 'HTML/QuickForm2/Rule/Regex.php'),
- 'callback' => array('HTML_QuickForm2_Rule_Callback',
- 'HTML/QuickForm2/Rule/Callback.php'),
- 'length' => array('HTML_QuickForm2_Rule_Length',
- 'HTML/QuickForm2/Rule/Length.php'),
- 'minlength' => array('HTML_QuickForm2_Rule_Length',
- 'HTML/QuickForm2/Rule/Length.php',
- array('max' => 0)),
- 'maxlength' => array('HTML_QuickForm2_Rule_Length',
- 'HTML/QuickForm2/Rule/Length.php',
- array('min' => 0)),
- 'maxfilesize' => array('HTML_QuickForm2_Rule_MaxFileSize',
- 'HTML/QuickForm2/Rule/MaxFileSize.php'),
- 'mimetype' => array('HTML_QuickForm2_Rule_MimeType',
- 'HTML/QuickForm2/Rule/MimeType.php')
- );
-
-
- /**
- * Checks whether the file exists in the include path
- *
- * @param string file name
- * @return bool
- */
- protected static function fileExists($fileName)
- {
- $fp = @fopen($fileName, 'r', true);
- if (is_resource($fp)) {
- fclose($fp);
- return true;
- }
- return false;
- }
-
- /**
- * Tries to load a given class from a given file
- *
- * @param string Class name to load
- * @param string Name of the file (supposedly) containing the given class
- * @throws HTML_QuickForm2_NotFoundException If the file either can't be
- * loaded or doesn't contain the given class
- */
- protected static function loadClass($className, $includeFile)
- {
- if (empty($includeFile)) {
- throw new HTML_QuickForm2_NotFoundException(
- "Class '$className' does not exist and no file to load"
- );
- } elseif (!self::fileExists($includeFile)) {
- throw new HTML_QuickForm2_NotFoundException("File '$includeFile' was not found");
- }
- // Do not silence the errors with @, parse errors will not be seen
- include_once $includeFile;
- // Still no class?
- if (!class_exists($className, false)) {
- throw new HTML_QuickForm2_NotFoundException(
- "Class '$className' was not found within file '$includeFile'"
- );
- }
- }
-
- /**
- * Registers a new element type
- *
- * @param string Type name (treated case-insensitively)
- * @param string Class name
- * @param string File containing the class, leave empty if class already loaded
- */
- public static function registerElement($type, $className, $includeFile = null)
- {
- self::$elementTypes[strtolower($type)] = array($className, $includeFile);
- }
-
-
- /**
- * Checks whether an element type is known to factory
- *
- * @param string Type name (treated case-insensitively)
- * @return bool
- */
- public static function isElementRegistered($type)
- {
- return isset(self::$elementTypes[strtolower($type)]);
- }
-
-
- /**
- * Creates a new element object of the given type
- *
- * @param string Type name (treated case-insensitively)
- * @param mixed Element name (passed to element's constructor)
- * @param mixed Element attributes (passed to element's constructor)
- * @param array Element-specific data (passed to element's constructor)
- * @return HTML_QuickForm2_Node A created element
- * @throws HTML_QuickForm2_InvalidArgumentException If type name is unknown
- * @throws HTML_QuickForm2_NotFoundException If class for the element can
- * not be found and/or loaded from file
- */
- public static function createElement($type, $name = null, $attributes = null,
- array $data = array())
- {
- $type = strtolower($type);
- if (!isset(self::$elementTypes[$type])) {
- throw new HTML_QuickForm2_InvalidArgumentException("Element type '$type' is not known");
- }
- list($className, $includeFile) = self::$elementTypes[$type];
- if (!class_exists($className, false)) {
- self::loadClass($className, $includeFile);
- }
- return new $className($name, $attributes, $data);
- }
-
-
- /**
- * Registers a new rule type
- *
- * @param string Rule type name (treated case-insensitively)
- * @param string Class name
- * @param string File containing the class, leave empty if class already loaded
- * @param mixed Configuration data for rules of the given type
- */
- public static function registerRule($type, $className, $includeFile = null,
- $config = null)
- {
- self::$registeredRules[strtolower($type)] = array($className, $includeFile, $config);
- }
-
-
- /**
- * Returns configuration data for rules of the given type
- *
- * @param string Rule type name (treated case-insensitively)
- * @return mixed Configuration data (set when registering the rule)
- * @throws HTML_QuickForm2_InvalidArgumentException If rule type is unknown
- */
- public static function getRuleConfig($type)
- {
- $type = strtolower($type);
- if (!isset(self::$registeredRules[$type])) {
- throw new HTML_QuickForm2_InvalidArgumentException("Rule '$type' is not known");
- } elseif (isset(self::$registeredRules[$type][2])) {
- return self::$registeredRules[$type][2];
- } else {
- return null;
- }
- }
-
-
- /**
- * Checks whether a rule type is known to Factory
- *
- * @param string Rule type name (treated case-insensitively)
- * @return bool
- */
- public static function isRuleRegistered($type)
- {
- return isset(self::$registeredRules[strtolower($type)]);
- }
-
-
- /**
- * Creates a new Rule of the given type
- *
- * @param string Rule type name (treated case-insensitively)
- * @param HTML_QuickForm2_Node Element to validate by the rule
- * @param string Message to display if validation fails
- * @param mixed Additional data for the rule
- * @return HTML_QuickForm2_Rule A created Rule
- * @throws HTML_QuickForm2_InvalidArgumentException If rule type is unknown
- * @throws HTML_QuickForm2_NotFoundException If class for the rule
- * can't be found and/or loaded from file
- */
- public static function createRule($type, HTML_QuickForm2_Node $owner,
- $message = '', $options = null)
- {
- $type = strtolower($type);
- if (!isset(self::$registeredRules[$type])) {
- throw new HTML_QuickForm2_InvalidArgumentException("Rule '$type' is not known");
- }
- list($className, $includeFile) = self::$registeredRules[$type];
- if (!class_exists($className, false)) {
- self::loadClass($className, $includeFile);
- }
- return new $className($owner, $message, $options, $type);
- }
-}
-?>
+++ /dev/null
-<?php
-/**
- * Base class for all HTML_QuickForm2 elements
- *
- * PHP version 5
- *
- * LICENSE:
- *
- * Copyright (c) 2006, 2007, Alexey Borzov <avb@php.net>,
- * Bertrand Mansion <golgote@mamasam.com>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * The names of the authors may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: Node.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_QuickForm2
- */
-
-/**
- * HTML_Common2 - base class for HTML elements
- */
-require_once 'HTML/Common2.php';
-
-/**
- * Exception classes for HTML_QuickForm2
- */
-require_once 'HTML/QuickForm2/Exception.php';
-
-/**
- * Static factory class for QuickForm2 elements
- */
-require_once 'HTML/QuickForm2/Factory.php';
-
-/**
- * Abstract base class for all QuickForm2 Elements and Containers
- *
- * This class is mostly here to define the interface that should be implemented
- * by the subclasses. It also contains static methods handling generation
- * of unique ids for elements which do not have ids explicitly set.
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @version Release: 0.2.0
- */
-abstract class HTML_QuickForm2_Node extends HTML_Common2
-{
- /**
- * Array containing the parts of element ids
- * @var array
- */
- protected static $ids = array();
-
- /**
- * Element's "frozen" status
- * @var boolean
- */
- protected $frozen = false;
-
- /**
- * Whether element's value should persist when element is frozen
- * @var boolean
- */
- protected $persistent = false;
-
- /**
- * Element containing current
- * @var HTML_QuickForm2_Container
- */
- protected $container = null;
-
- /**
- * Contains options and data used for the element creation
- * @var array
- */
- protected $data = null;
-
- /**
- * Validation rules for element
- * @var array
- */
- protected $rules = array();
-
- /**
- * Error message (usually set via Rule if validation fails)
- * @var string
- */
- protected $error = null;
-
- /**
- * Class constructor
- *
- * @param string Element name
- * @param mixed Attributes (either a string or an array)
- * @param array Element data (label, options and data used for element creation)
- */
- public function __construct($name = null, $attributes = null, array $data = array())
- {
- parent::__construct($attributes);
- $this->setName($name);
- // Autogenerating the id if not set on previous steps
- if ('' == $this->getId()) {
- $this->setId();
- }
- $this->data = $data;
- }
-
-
- /**
- * Generates an id for the element
- *
- * Called when an element is created without explicitly given id
- *
- * @param string Element name
- * @return string The generated element id
- */
- protected static function generateId($elementName)
- {
- $tokens = strlen($elementName)?
- explode('[', str_replace(']', '', $elementName)):
- array('qfauto');
- $container =& self::$ids;
- $id = '';
-
- do {
- $token = array_shift($tokens);
- // Handle the 'array[]' names
- if ('' === $token) {
- if (empty($container)) {
- $token = 0;
- } else {
- $keys = array_keys($container);
- $token = end($keys);
- while (isset($container[$token])) {
- $token++;
- }
- }
- }
- $id .= '-' . $token;
- if (!isset($container[$token])) {
- $container[$token] = array();
- }
- $container =& $container[$token];
- } while (!empty($tokens));
-
- // Append the final index
- $index = count($keys = array_keys($container))? end($keys): 0;
- while (isset($container[$index])) {
- $index++;
- }
- $container[$index] = array();
- $id .= '-' . $index;
-
- return substr($id, 1);
- }
-
-
- /**
- * Stores the explicitly given id to prevent duplicate id generation
- *
- * @param string Element id
- */
- protected static function storeId($id)
- {
- $tokens = explode('-', $id);
- $container =& self::$ids;
-
- do {
- $token = array_shift($tokens);
- if (!isset($container[$token])) {
- $container[$token] = array();
- }
- $container =& $container[$token];
- } while (!empty($tokens));
- }
-
-
- /**
- * Returns the element's type
- *
- * @return string
- */
- abstract public function getType();
-
-
- /**
- * Returns the element's name
- *
- * @return string
- */
- abstract public function getName();
-
-
- /**
- * Sets the element's name
- *
- * @param string
- * @return HTML_QuickForm2_Node
- */
- abstract public function setName($name);
-
-
- /**
- * Returns the element's id
- *
- * @return string
- */
- abstract public function getId();
-
-
- /**
- * Sets the elements id
- *
- * Please note that elements should always have an id in QuickForm2 and
- * therefore it will not be possible to remove the element's id or set it to
- * an empty value. If id is not explicitly given, it will be autogenerated.
- *
- * @param string Element's id, will be autogenerated if not given
- * @return HTML_QuickForm2_Node
- */
- abstract public function setId($id = null);
-
-
- /**
- * Returns the element's value
- *
- * @return mixed
- */
- abstract public function getValue();
-
-
- /**
- * Sets the element's value
- *
- * @param mixed
- * @return HTML_QuickForm2_Node
- */
- abstract public function setValue($value);
-
-
- /**
- * Returns the element's label(s)
- *
- * @return string|array
- */
- public function getLabel()
- {
- if (isset($this->data['label'])) {
- return $this->data['label'];
- }
- return null;
- }
-
-
- /**
- * Sets the element's label(s)
- *
- * @param string|array Label for the element (may be an array of labels)
- * @return HTML_QuickForm2_Node
- */
- public function setLabel($label)
- {
- $this->data['label'] = $label;
- return $this;
- }
-
-
- /**
- * Changes the element's frozen status
- *
- * @param bool Whether the element should be frozen or editable. If
- * omitted, the method will not change the frozen status,
- * just return its current value
- * @return bool Old value of element's frozen status
- */
- public function toggleFrozen($freeze = null)
- {
- $old = $this->frozen;
- if (null !== $freeze) {
- $this->frozen = (bool)$freeze;
- }
- return $old;
- }
-
-
- /**
- * Changes the element's persistent freeze behaviour
- *
- * If persistent freeze is on, the element's value will be kept (and
- * submitted) in a hidden field when the element is frozen.
- *
- * @param bool New value for "persistent freeze". If omitted, the
- * method will not set anything, just return the current
- * value of the flag.
- * @return bool Old value of "persistent freeze" flag
- */
- public function persistentFreeze($persistent = null)
- {
- $old = $this->persistent;
- if (null !== $persistent) {
- $this->persistent = (bool)$persistent;
- }
- return $old;
- }
-
-
- /**
- * Adds the link to the element containing current
- *
- * @param HTML_QuickForm2_Container Element containing the current one,
- * null if the link should really be
- * removed (if removing from container)
- * @throws HTML_QuickForm2_InvalidArgumentException If trying to set a
- * child of an element as its container
- */
- protected function setContainer(HTML_QuickForm2_Container $container = null)
- {
- if (null !== $container) {
- $check = $container;
- do {
- if ($this === $check) {
- throw new HTML_QuickForm2_InvalidArgumentException(
- 'Cannot set an element or its child as its own container'
- );
- }
- } while ($check = $check->getContainer());
- if (null !== $this->container && $container !== $this->container) {
- $this->container->removeChild($this);
- }
- }
- $this->container = $container;
- if (null !== $container) {
- $this->updateValue();
- }
- }
-
-
- /**
- * Returns the element containing current
- *
- * @return HTML_QuickForm2_Container|null
- */
- public function getContainer()
- {
- return $this->container;
- }
-
- /**
- * Returns the data sources for this element
- *
- * @return array
- */
- protected function getDataSources()
- {
- if (empty($this->container)) {
- return array();
- } else {
- return $this->container->getDataSources();
- }
- }
-
- /**
- * Called when the element needs to update its value from form's data sources
- */
- abstract protected function updateValue();
-
- /**
- * Adds a validation rule
- *
- * @param HTML_QuickForm2_Rule|string Validation rule or rule type
- * @param string Message to display if validation fails
- * @param mixed Additional data for the rule
- * @return HTML_QuickForm2_Rule The added rule
- * @throws HTML_QuickForm2_InvalidArgumentException if $rule is of a
- * wrong type or rule name isn't registered with Factory
- * @throws HTML_QuickForm2_NotFoundException if class for a given rule
- * name cannot be found
- */
- public function addRule($rule, $message = '', $options = null)
- {
- if ($rule instanceof HTML_QuickForm2_Rule) {
- $rule->setOwner($this);
- } elseif (is_string($rule)) {
- $rule = HTML_QuickForm2_Factory::createRule($rule, $this, $message, $options);
- } else {
- throw new HTML_QuickForm2_InvalidArgumentException(
- 'addRule() expects either a rule type or ' .
- 'a HTML_QuickForm2_Rule instance'
- );
- }
-
- $this->rules[] = $rule;
- return $rule;
- }
-
-
- /**
- * Creates a validation rule
- *
- * This method is mostly useful when when chaining several rules together
- * via {@link HTML_QuickForm2_Rule::and_()} and {@link HTML_QuickForm2_Rule::or_()}
- * methods:
- * <code>
- * $first->addRule('nonempty', 'Fill in either first or second field')
- * ->or_($second->createRule('nonempty'));
- * </code>
- *
- * @param string Rule type
- * @param string Message to display if validation fails
- * @param mixed Additional data for the rule
- * @return HTML_QuickForm2_Rule The created rule
- * @throws HTML_QuickForm2_InvalidArgumentException If rule type is unknown
- * @throws HTML_QuickForm2_NotFoundException If class for the rule
- * can't be found and/or loaded from file
- */
- public function createRule($type, $message = '', $options = null)
- {
- return HTML_QuickForm2_Factory::createRule($type, $this, $message, $options);
- }
-
-
- /**
- * Checks whether an element is required
- *
- * @return boolean
- */
- public function isRequired()
- {
- foreach ($this->rules as $rule) {
- if ($rule instanceof HTML_QuickForm2_Rule_Required) {
- return true;
- }
- }
- return false;
- }
-
-
- /**
- * Performs the server-side validation
- *
- * @return boolean Whether the element is valid
- */
- protected function validate()
- {
- foreach ($this->rules as $rule) {
- if (strlen($this->error)) {
- break;
- }
- $rule->validate();
- }
- return !strlen($this->error);
- }
-
- /**
- * Sets the error message to the element
- *
- * @param string
- * @return HTML_QuickForm2_Node
- */
- public function setError($error = null)
- {
- $this->error = (string)$error;
- return $this;
- }
-
- /**
- * Returns the error message for the element
- *
- * @return string
- */
- public function getError()
- {
- return $this->error;
- }
-}
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 foldmethod=marker: */
-/**
- * PEAR_Exception
- *
- * PHP versions 4 and 5
- *
- * LICENSE: This source file is subject to version 3.0 of the PHP license
- * that is available through the world-wide-web at the following URI:
- * http://www.php.net/license/3_0.txt. If you did not receive a copy of
- * the PHP License and are unable to obtain it through the web, please
- * send a note to license@php.net so we can mail you a copy immediately.
- *
- * @category pear
- * @package PEAR
- * @author Tomas V. V. Cox <cox@idecnet.com>
- * @author Hans Lellelid <hans@velum.net>
- * @author Bertrand Mansion <bmansion@mamasam.com>
- * @author Greg Beaver <cellog@php.net>
- * @copyright 1997-2008 The PHP Group
- * @license http://www.php.net/license/3_0.txt PHP License 3.0
- * @version CVS: $Id: Exception.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/PEAR
- * @since File available since Release 1.3.3
- */
-
-
-/**
- * Base PEAR_Exception Class
- *
- * 1) Features:
- *
- * - Nestable exceptions (throw new PEAR_Exception($msg, $prev_exception))
- * - Definable triggers, shot when exceptions occur
- * - Pretty and informative error messages
- * - Added more context info available (like class, method or cause)
- * - cause can be a PEAR_Exception or an array of mixed
- * PEAR_Exceptions/PEAR_ErrorStack warnings
- * - callbacks for specific exception classes and their children
- *
- * 2) Ideas:
- *
- * - Maybe a way to define a 'template' for the output
- *
- * 3) Inherited properties from PHP Exception Class:
- *
- * protected $message
- * protected $code
- * protected $line
- * protected $file
- * private $trace
- *
- * 4) Inherited methods from PHP Exception Class:
- *
- * __clone
- * __construct
- * getMessage
- * getCode
- * getFile
- * getLine
- * getTraceSafe
- * getTraceSafeAsString
- * __toString
- *
- * 5) Usage example
- *
- * <code>
- * require_once 'PEAR/Exception.php';
- *
- * class Test {
- * function foo() {
- * throw new PEAR_Exception('Error Message', ERROR_CODE);
- * }
- * }
- *
- * function myLogger($pear_exception) {
- * echo $pear_exception->getMessage();
- * }
- * // each time a exception is thrown the 'myLogger' will be called
- * // (its use is completely optional)
- * PEAR_Exception::addObserver('myLogger');
- * $test = new Test;
- * try {
- * $test->foo();
- * } catch (PEAR_Exception $e) {
- * print $e;
- * }
- * </code>
- *
- * @category pear
- * @package PEAR
- * @author Tomas V.V.Cox <cox@idecnet.com>
- * @author Hans Lellelid <hans@velum.net>
- * @author Bertrand Mansion <bmansion@mamasam.com>
- * @author Greg Beaver <cellog@php.net>
- * @copyright 1997-2008 The PHP Group
- * @license http://www.php.net/license/3_0.txt PHP License 3.0
- * @version Release: 1.7.0RC2
- * @link http://pear.php.net/package/PEAR
- * @since Class available since Release 1.3.3
- *
- */
-class PEAR_Exception extends Exception
-{
- const OBSERVER_PRINT = -2;
- const OBSERVER_TRIGGER = -4;
- const OBSERVER_DIE = -8;
- protected $cause;
- private static $_observers = array();
- private static $_uniqueid = 0;
- private $_trace;
-
- /**
- * Supported signatures:
- * - PEAR_Exception(string $message);
- * - PEAR_Exception(string $message, int $code);
- * - PEAR_Exception(string $message, Exception $cause);
- * - PEAR_Exception(string $message, Exception $cause, int $code);
- * - PEAR_Exception(string $message, PEAR_Error $cause);
- * - PEAR_Exception(string $message, PEAR_Error $cause, int $code);
- * - PEAR_Exception(string $message, array $causes);
- * - PEAR_Exception(string $message, array $causes, int $code);
- * @param string exception message
- * @param int|Exception|PEAR_Error|array|null exception cause
- * @param int|null exception code or null
- */
- public function __construct($message, $p2 = null, $p3 = null)
- {
- if (is_int($p2)) {
- $code = $p2;
- $this->cause = null;
- } elseif (is_object($p2) || is_array($p2)) {
- // using is_object allows both Exception and PEAR_Error
- if (is_object($p2) && !($p2 instanceof Exception)) {
- if (!class_exists('PEAR_Error') || !($p2 instanceof PEAR_Error)) {
- throw new PEAR_Exception('exception cause must be Exception, ' .
- 'array, or PEAR_Error');
- }
- }
- $code = $p3;
- if (is_array($p2) && isset($p2['message'])) {
- // fix potential problem of passing in a single warning
- $p2 = array($p2);
- }
- $this->cause = $p2;
- } else {
- $code = null;
- $this->cause = null;
- }
- parent::__construct($message, $code);
- $this->signal();
- }
-
- /**
- * @param mixed $callback - A valid php callback, see php func is_callable()
- * - A PEAR_Exception::OBSERVER_* constant
- * - An array(const PEAR_Exception::OBSERVER_*,
- * mixed $options)
- * @param string $label The name of the observer. Use this if you want
- * to remove it later with removeObserver()
- */
- public static function addObserver($callback, $label = 'default')
- {
- self::$_observers[$label] = $callback;
- }
-
- public static function removeObserver($label = 'default')
- {
- unset(self::$_observers[$label]);
- }
-
- /**
- * @return int unique identifier for an observer
- */
- public static function getUniqueId()
- {
- return self::$_uniqueid++;
- }
-
- private function signal()
- {
- foreach (self::$_observers as $func) {
- if (is_callable($func)) {
- call_user_func($func, $this);
- continue;
- }
- settype($func, 'array');
- switch ($func[0]) {
- case self::OBSERVER_PRINT :
- $f = (isset($func[1])) ? $func[1] : '%s';
- printf($f, $this->getMessage());
- break;
- case self::OBSERVER_TRIGGER :
- $f = (isset($func[1])) ? $func[1] : E_USER_NOTICE;
- trigger_error($this->getMessage(), $f);
- break;
- case self::OBSERVER_DIE :
- $f = (isset($func[1])) ? $func[1] : '%s';
- die(printf($f, $this->getMessage()));
- break;
- default:
- trigger_error('invalid observer type', E_USER_WARNING);
- }
- }
- }
-
- /**
- * Return specific error information that can be used for more detailed
- * error messages or translation.
- *
- * This method may be overridden in child exception classes in order
- * to add functionality not present in PEAR_Exception and is a placeholder
- * to define API
- *
- * The returned array must be an associative array of parameter => value like so:
- * <pre>
- * array('name' => $name, 'context' => array(...))
- * </pre>
- * @return array
- */
- public function getErrorData()
- {
- return array();
- }
-
- /**
- * Returns the exception that caused this exception to be thrown
- * @access public
- * @return Exception|array The context of the exception
- */
- public function getCause()
- {
- return $this->cause;
- }
-
- /**
- * Function must be public to call on caused exceptions
- * @param array
- */
- public function getCauseMessage(&$causes)
- {
- $trace = $this->getTraceSafe();
- $cause = array('class' => get_class($this),
- 'message' => $this->message,
- 'file' => 'unknown',
- 'line' => 'unknown');
- if (isset($trace[0])) {
- if (isset($trace[0]['file'])) {
- $cause['file'] = $trace[0]['file'];
- $cause['line'] = $trace[0]['line'];
- }
- }
- $causes[] = $cause;
- if ($this->cause instanceof PEAR_Exception) {
- $this->cause->getCauseMessage($causes);
- } elseif ($this->cause instanceof Exception) {
- $causes[] = array('class' => get_class($this->cause),
- 'message' => $this->cause->getMessage(),
- 'file' => $this->cause->getFile(),
- 'line' => $this->cause->getLine());
- } elseif (class_exists('PEAR_Error') && $this->cause instanceof PEAR_Error) {
- $causes[] = array('class' => get_class($this->cause),
- 'message' => $this->cause->getMessage(),
- 'file' => 'unknown',
- 'line' => 'unknown');
- } elseif (is_array($this->cause)) {
- foreach ($this->cause as $cause) {
- if ($cause instanceof PEAR_Exception) {
- $cause->getCauseMessage($causes);
- } elseif ($cause instanceof Exception) {
- $causes[] = array('class' => get_class($cause),
- 'message' => $cause->getMessage(),
- 'file' => $cause->getFile(),
- 'line' => $cause->getLine());
- } elseif (class_exists('PEAR_Error') && $cause instanceof PEAR_Error) {
- $causes[] = array('class' => get_class($cause),
- 'message' => $cause->getMessage(),
- 'file' => 'unknown',
- 'line' => 'unknown');
- } elseif (is_array($cause) && isset($cause['message'])) {
- // PEAR_ErrorStack warning
- $causes[] = array(
- 'class' => $cause['package'],
- 'message' => $cause['message'],
- 'file' => isset($cause['context']['file']) ?
- $cause['context']['file'] :
- 'unknown',
- 'line' => isset($cause['context']['line']) ?
- $cause['context']['line'] :
- 'unknown',
- );
- }
- }
- }
- }
-
- public function getTraceSafe()
- {
- if (!isset($this->_trace)) {
- $this->_trace = $this->getTrace();
- if (empty($this->_trace)) {
- $backtrace = debug_backtrace();
- $this->_trace = array($backtrace[count($backtrace)-1]);
- }
- }
- return $this->_trace;
- }
-
- public function getErrorClass()
- {
- $trace = $this->getTraceSafe();
- return $trace[0]['class'];
- }
-
- public function getErrorMethod()
- {
- $trace = $this->getTraceSafe();
- return $trace[0]['function'];
- }
-
- public function __toString()
- {
- if (isset($_SERVER['REQUEST_URI'])) {
- return $this->toHtml();
- }
- return $this->toText();
- }
-
- public function toHtml()
- {
- $trace = $this->getTraceSafe();
- $causes = array();
- $this->getCauseMessage($causes);
- $html = '<table border="1" cellspacing="0">' . "\n";
- foreach ($causes as $i => $cause) {
- $html .= '<tr><td colspan="3" bgcolor="#ff9999">'
- . str_repeat('-', $i) . ' <b>' . $cause['class'] . '</b>: '
- . htmlspecialchars($cause['message']) . ' in <b>' . $cause['file'] . '</b> '
- . 'on line <b>' . $cause['line'] . '</b>'
- . "</td></tr>\n";
- }
- $html .= '<tr><td colspan="3" bgcolor="#aaaaaa" align="center"><b>Exception trace</b></td></tr>' . "\n"
- . '<tr><td align="center" bgcolor="#cccccc" width="20"><b>#</b></td>'
- . '<td align="center" bgcolor="#cccccc"><b>Function</b></td>'
- . '<td align="center" bgcolor="#cccccc"><b>Location</b></td></tr>' . "\n";
-
- foreach ($trace as $k => $v) {
- $html .= '<tr><td align="center">' . $k . '</td>'
- . '<td>';
- if (!empty($v['class'])) {
- $html .= $v['class'] . $v['type'];
- }
- $html .= $v['function'];
- $args = array();
- if (!empty($v['args'])) {
- foreach ($v['args'] as $arg) {
- if (is_null($arg)) $args[] = 'null';
- elseif (is_array($arg)) $args[] = 'Array';
- elseif (is_object($arg)) $args[] = 'Object('.get_class($arg).')';
- elseif (is_bool($arg)) $args[] = $arg ? 'true' : 'false';
- elseif (is_int($arg) || is_double($arg)) $args[] = $arg;
- else {
- $arg = (string)$arg;
- $str = htmlspecialchars(substr($arg, 0, 16));
- if (strlen($arg) > 16) $str .= '…';
- $args[] = "'" . $str . "'";
- }
- }
- }
- $html .= '(' . implode(', ',$args) . ')'
- . '</td>'
- . '<td>' . (isset($v['file']) ? $v['file'] : 'unknown')
- . ':' . (isset($v['line']) ? $v['line'] : 'unknown')
- . '</td></tr>' . "\n";
- }
- $html .= '<tr><td align="center">' . ($k+1) . '</td>'
- . '<td>{main}</td>'
- . '<td> </td></tr>' . "\n"
- . '</table>';
- return $html;
- }
-
- public function toText()
- {
- $causes = array();
- $this->getCauseMessage($causes);
- $causeMsg = '';
- foreach ($causes as $i => $cause) {
- $causeMsg .= str_repeat(' ', $i) . $cause['class'] . ': '
- . $cause['message'] . ' in ' . $cause['file']
- . ' on line ' . $cause['line'] . "\n";
- }
- return $causeMsg . $this->getTraceAsString();
- }
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/**
- * Base class for HTML_QuickForm2 rules
- *
- * PHP version 5
- *
- * LICENSE:
- *
- * Copyright (c) 2006, 2007, Alexey Borzov <avb@php.net>,
- * Bertrand Mansion <golgote@mamasam.com>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * The names of the authors may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: Rule.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_QuickForm2
- */
-
-/**
- * Abstract base class for HTML_QuickForm2 rules
- *
- * This class provides methods that allow chaining several rules together.
- * Its validate() method executes the whole rule chain starting from this rule.
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @version Release: 0.2.0
- */
-abstract class HTML_QuickForm2_Rule
-{
- /**
- * An element whose value will be validated by this rule
- * @var HTML_QuickForm2_Node
- */
- protected $owner;
-
- /**
- * An error message to display if validation fails
- * @var string
- */
- protected $message;
-
- /**
- * Additional data for the rule
- * @var mixed
- */
- protected $options;
-
- /**
- * Rules chained to this via "and" and "or" operators
- *
- * The contents can be described as "disjunctive normal form", where an outer
- * array represents a disjunction of conjunctive clauses represented by inner
- * arrays.
- *
- * @var array
- */
- protected $chainedRules = array(array());
-
- /**
- * Type that was provided to Factory when creating this Rule instance
- *
- * Used to get the common configuration data for the Rules of that type from
- * Factory.
- *
- * @var string
- */
- protected $registeredType = null;
-
-
- /**
- * Class constructor
- *
- * @param HTML_QuickForm2_Node Element to validate
- * @param string Error message to display if validation fails
- * @param mixed Additional data for the rule
- * @param string Type that was provided to Factory when
- * creating this Rule instance, shouldn't
- * be set if instantiating the Rule object
- * manually.
- */
- public function __construct(HTML_QuickForm2_Node $owner, $message = '',
- $options = null, $registeredType = null)
- {
- $this->setOwner($owner);
- $this->setMessage($message);
- $this->setOptions($options);
- $this->registeredType = $registeredType;
- }
-
- /**
- * Sets additional configuration data for the rule
- *
- * @param mixed Rule configuration data (rule-dependent)
- * @return HTML_QuickForm2_Rule
- */
- public function setOptions($options)
- {
- $this->options = $options;
- return $this;
- }
-
- /**
- * Returns the rule's configuration data
- *
- * @return mixed
- */
- public function getOptions()
- {
- return $this->options;
- }
-
- /**
- * Sets the error message output by the rule
- *
- * @param string Error message to display if validation fails
- * @return HTML_QuickForm2_Rule
- */
- public function setMessage($message)
- {
- $this->message = (string)$message;
- return $this;
- }
-
- /**
- * Returns the error message output by the rule
- *
- * @return string Error message
- */
- public function getMessage()
- {
- return $this->message;
- }
-
- /**
- * Sets the element that will be validated by this rule
- *
- * @param HTML_QuickForm2_Node Element to validate
- * @todo We should consider removing the rule from previous owner
- */
- public function setOwner(HTML_QuickForm2_Node $owner)
- {
- $this->owner = $owner;
- }
-
- /**
- * Adds a rule to the chain with an "and" operator
- *
- * Evaluation is short-circuited, next rule will not be evaluated if the
- * previous one returns false. The method is named this way because "and" is
- * a reserved word in PHP.
- *
- * @param HTML_QuickForm2_Rule
- * @return HTML_QuickForm2_Rule first rule in the chain (i.e. $this)
- * @throws HTML_QuickForm2_InvalidArgumentException when trying to add
- * a "required" rule to the chain
- */
- public function and_(HTML_QuickForm2_Rule $next)
- {
- if ($next instanceof HTML_QuickForm2_Rule_Required) {
- throw new HTML_QuickForm2_InvalidArgumentException(
- 'and_(): Cannot add a "required" rule'
- );
- }
- $this->chainedRules[count($this->chainedRules) - 1][] = $next;
- return $this;
- }
-
- /**
- * Adds a rule to the chain with an "or" operator
- *
- * Evaluation is short-circuited, next rule will not be evaluated if the
- * previous one returns true. The method is named this way because "or" is
- * a reserved word in PHP.
- *
- * @param HTML_QuickForm2_Rule
- * @return HTML_QuickForm2_Rule first rule in the chain (i.e. $this)
- * @throws HTML_QuickForm2_InvalidArgumentException when trying to add
- * a "required" rule to the chain
- */
- public function or_(HTML_QuickForm2_Rule $next)
- {
- if ($next instanceof HTML_QuickForm2_Rule_Required) {
- throw new HTML_QuickForm2_InvalidArgumentException(
- 'or_(): Cannot add a "required" rule'
- );
- }
- $this->chainedRules[] = array($next);
- return $this;
- }
-
- /**
- * Performs validation
- *
- * The whole rule chain is executed. Note that the side effect of this
- * method is setting the error message on element if validation fails
- *
- * @return boolean Whether the element is valid
- */
- public function validate()
- {
- $globalValid = false;
- $localValid = $this->checkValue($this->owner->getValue());
- foreach ($this->chainedRules as $item) {
- foreach ($item as $multiplier) {
- if (!$localValid) {
- break;
- }
- $localValid = $localValid && $multiplier->validate();
- }
- $globalValid = $globalValid || $localValid;
- if ($globalValid) {
- break;
- }
- $localValid = true;
- }
- if (!$globalValid && strlen($this->message) && !$this->owner->getError()) {
- $this->owner->setError($this->message);
- }
- return $globalValid;
- }
-
- /**
- * Validates the element's value
- *
- * Note that the error message will be set for an element if such message
- * exists in the rule and that method returns false
- *
- * @param mixed Form element's value
- * @return boolean Whether the value is valid according to the rule
- */
- abstract protected function checkValue($value);
-}
-?>
+++ /dev/null
-<?php
-/**
- * Rule checking the value via a callback function (method)
- *
- * PHP version 5
- *
- * LICENSE:
- *
- * Copyright (c) 2006, 2007, Alexey Borzov <avb@php.net>,
- * Bertrand Mansion <golgote@mamasam.com>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * The names of the authors may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: Callback.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_QuickForm2
- */
-
-/**
- * Base class for HTML_QuickForm2 rules
- */
-require_once 'HTML/QuickForm2/Rule.php';
-
-/**
- * Rule checking the value via a callback function (method)
- *
- * The Rule needs a valid callback as a configuration parameter for its work, it
- * may also be given additional arguments to pass to the callback alongside the
- * element's value.
- *
- * Parameters can be passed to {@link HTML_QuickForm2_Rule::setOptions() setOptions()} in
- * either of the following formats
- * - callback or arguments (the semantics depend on whether the Rule was
- * registered in the {@link HTML_QuickForm2_Factory Factory} with the
- * callback already given)
- * - array(['callback' => callback, ]['arguments' => array(...)])
- * and also may be passed to {@link HTML_QuickForm2_Factory::registerRule()} in
- * either of the following formats
- * - callback
- * - array(['callback' => callback, ]['arguments' => array(...)])
- * global config registered with the Factory overrides options set for the
- * particular Rule instance. In any case you are advised to use the associative
- * array format to prevent ambiguity.
- *
- * The callback will be called with element's value as the first argument, if
- * additional arguments were provided they'll be passed as well. It is expected
- * to return false if the value is invalid and true if it is valid.
- *
- * Checking that the value is not empty:
- * <code>
- * $str->addRule('callback', 'The field should not be empty', 'strlen');
- * </code>
- * Checking that the value is in the given array:
- * <code>
- * $meta->addRule('callback', 'Unknown variable name',
- * array('callback' => 'in_array',
- * 'arguments' => array(array('foo', 'bar', 'baz'))));
- * </code>
- * The same, but with rule registering first:
- * <code>
- * HTML_QuickForm2_Factory::registerRule(
- * 'in_array', 'HTML_QuickForm2_Rule_Callback',
- * 'HTML/QuickForm2/Rule/Callback.php', 'in_array'
- * );
- * $meta->addRule('in_array', 'Unknown variable name', array(array('foo', 'bar', 'baz')));
- * </code>
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @version Release: 0.2.0
- */
-class HTML_QuickForm2_Rule_Callback extends HTML_QuickForm2_Rule
-{
- /**
- * Set to true if callback function was registered in Factory
- * @var bool
- */
- protected $registeredCallback = false;
-
- /**
- * Validates the element's value
- *
- * @return bool the value returned by a callback function
- * @throws HTML_QuickForm2_InvalidArgumentException if a bogus $registeredType
- * was passed to constructor or a bogus callback was provided
- * @throws HTML_QuickForm2_Exception if the callback is missing
- */
- protected function checkValue($value)
- {
- if (!empty($this->registeredType)) {
- $config = HTML_QuickForm2_Factory::getRuleConfig($this->registeredType);
- } else {
- $config = null;
- }
- $callback = $this->findCallback($config);
- $arguments = $this->findArguments($config);
- if (!is_callable($callback, false, $callbackName)) {
- throw new HTML_QuickForm2_InvalidArgumentException(
- 'Callback Rule requires a valid callback, \'' . $callbackName .
- '\' was given'
- );
- }
- return call_user_func_array($callback, array_merge(array($value), $arguments));
- }
-
- /**
- * Searches in global config and Rule's options for a callback function to use
- *
- * @param mixed config returned by {@link HTML_QuickForm2_Factory::getRuleConfig()},
- * if applicable
- * @return callback
- * @throws HTML_QuickForm2_Exception if a callback wasn't found anywhere
- */
- protected function findCallback($globalConfig)
- {
- $this->registeredCallback = false;
- if (!empty($globalConfig)) {
- if (!is_array($globalConfig) ||
- !isset($globalConfig['callback']) && !isset($globalConfig['arguments']))
- {
- $this->registeredCallback = true;
- return $globalConfig;
- } elseif (isset($globalConfig['callback'])) {
- $this->registeredCallback = true;
- return $globalConfig['callback'];
- }
- }
- if (is_array($this->options) && isset($this->options['callback'])) {
- return $this->options['callback'];
- } elseif (!empty($this->options)) {
- return $this->options;
- } else {
- throw new HTML_QuickForm2_Exception(
- 'Callback Rule requires a callback to check value with'
- );
- }
- }
-
- /**
- * Searches in global config and Rule's options for callback's additional arguments
- *
- * @param mixed config returned by {@link HTML_QuickForm2_Factory::getRuleConfig()},
- * if applicable
- * @return array additional arguments to pass to a callback
- */
- protected function findArguments($globalConfig)
- {
- if (is_array($globalConfig) && isset($globalConfig['arguments'])) {
- return $globalConfig['arguments'];
- }
- if (is_array($this->options) && isset($this->options['arguments'])) {
- return $this->options['arguments'];
- } elseif ($this->registeredCallback && !empty($this->options)) {
- return $this->options;
- }
- return array();
- }
-}
-?>
+++ /dev/null
-<?php
-/**
- * Rule comparing the value of the field with some other value
- *
- * PHP version 5
- *
- * LICENSE:
- *
- * Copyright (c) 2006, 2007, Alexey Borzov <avb@php.net>,
- * Bertrand Mansion <golgote@mamasam.com>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * The names of the authors may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: Compare.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_QuickForm2
- */
-
-/**
- * Base class for HTML_QuickForm2 rules
- */
-require_once 'HTML/QuickForm2/Rule.php';
-
-/**
- * Rule comparing the value of the field with some other value
- *
- * The Rule needs two configuration parameters for its work
- * - comparison operator (defaults to equality)
- * - operand to compare with; this can be either a constant or another form
- * element (its value will be used)
- *
- * Parameters can be passed to {@link HTML_QuickForm2_Rule::setOptions() setOptions()} in
- * either of the following formats
- * - operand
- * - array([operator, ]operand)
- * - array(['operator' => operator, ]['operand' => operand])
- * and also may be passed to {@link HTML_QuickForm2_Factory::registerRule()} in
- * either of the following formats
- * - operator
- * - array(operator[, operand])
- * - array(['operator' => operator, ]['operand' => operand])
- * global config registered with the Factory overrides options set for the
- * particular Rule instance.
- *
- * Note that 'less than [or equal]' and 'greater than [or equal]' operators
- * compare the operands numerically, since this is considered as more useful
- * approach by the authors.
- *
- * For convenience, this Rule is already registered in the Factory with the
- * names 'eq', 'neq', 'lt', 'gt', 'lte', 'gte' corresponding to the relevant
- * operators:
- * <code>
- * $password->addRule('eq', 'Passwords do not match', $passwordRepeat);
- * $orderQty->addRule('lte', 'Should not order more than 10 of these', 10);
- * </code>
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @version Release: 0.2.0
- */
-class HTML_QuickForm2_Rule_Compare extends HTML_QuickForm2_Rule
-{
- /**
- * Possible comparison operators
- * @var array
- */
- protected $operators = array('==', '!=', '===', '!==', '<', '<=', '>', '>=');
-
-
- /**
- * Validates the element's value
- *
- * @return bool whether (element_value operator operand) expression is true
- * @throws HTML_QuickForm2_InvalidArgumentException if a bogus $registeredType
- * was passed to constructor or a bogus comparison operator is used
- * for configuration
- * @throws HTML_QuickForm2_Exception if an operand to compare with is missing
- */
- protected function checkValue($value)
- {
- if (!empty($this->registeredType)) {
- $config = HTML_QuickForm2_Factory::getRuleConfig($this->registeredType);
- } else {
- $config = null;
- }
- $operator = $this->findOperator($config);
- $operand = $this->findOperand($config);
- if (!in_array($operator, array('===', '!=='))) {
- $compareFn = create_function('$a, $b', 'return floatval($a) ' . $operator . ' floatval($b);');
- } else {
- $compareFn = create_function('$a, $b', 'return strval($a) ' . $operator . ' strval($b);');
- }
- return $compareFn($value, $operand instanceof HTML_QuickForm2_Node?
- $operand->getValue(): $operand);
- }
-
-
- /**
- * Finds a comparison operator to use in global config and Rule's options
- *
- * @param mixed config returned by {@link HTML_QuickForm2_Factory::getRuleConfig()},
- * if applicable
- * @return string operator to use, defaults to '==='
- * @throws HTML_QuickForm2_InvalidArgumentException if a bogus comparison
- * operator is used for configuration
- */
- protected function findOperator($globalConfig)
- {
- if (!empty($globalConfig)) {
- if (!is_array($globalConfig)) {
- $operator = $globalConfig;
- } elseif (isset($globalConfig['operator'])) {
- $operator = $globalConfig['operator'];
- } else {
- $operator = array_shift($globalConfig);
- }
- }
- if (empty($operator)) {
- if (is_array($this->options) && isset($this->options['operator'])) {
- $operator = $this->options['operator'];
- } elseif (!is_array($this->options) || count($this->options) < 2) {
- return '===';
- } else {
- reset($this->options);
- $operator = current($this->options);
- }
- }
- if (!in_array($operator, $this->operators)) {
- throw new HTML_QuickForm2_InvalidArgumentException(
- 'Compare Rule requires a valid comparison operator, ' .
- preg_replace('/\s+/', ' ', var_export($operator, true)) . ' given'
- );
- }
- if (in_array($operator, array('==', '!='))) {
- return $operator . '=';
- }
- return $operator;
- }
-
-
- /**
- * Finds an operand to compare element's value with in global config and Rule's options
- *
- * @param mixed config returned by {@link HTML_QuickForm2_Factory::getRuleConfig()},
- * if applicable
- * @return mixed an operand to compare with
- * @throws HTML_QuickForm2_Exception if an operand is missing
- */
- protected function findOperand($globalConfig)
- {
- if (count($globalConfig) > 1) {
- if (isset($globalConfig['operand'])) {
- return $globalConfig['operand'];
- } else {
- return end($globalConfig);
- }
- }
- if (0 == count($this->options)) {
- throw new HTML_QuickForm2_Exception(
- 'Compare Rule requires an argument to compare with'
- );
- } elseif (!is_array($this->options)) {
- return $this->options;
- } elseif (isset($this->options['operand'])) {
- return $this->options['operand'];
- } else {
- return end($this->options);
- }
- }
-}
-?>
+++ /dev/null
-<?php
-/**
- * Rule checking that the field is empty
- *
- * PHP version 5
- *
- * LICENSE:
- *
- * Copyright (c) 2006, 2007, Alexey Borzov <avb@php.net>,
- * Bertrand Mansion <golgote@mamasam.com>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * The names of the authors may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: Empty.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_QuickForm2
- */
-
-/**
- * Base class for HTML_QuickForm2 rules
- */
-require_once 'HTML/QuickForm2/Rule.php';
-
-/**
- * Rule checking that the field is empty
- *
- * Handles both simple form fields and file uploads, the latter are considered
- * valid iff no file upload was attempted.
- *
- * The rule doesn't make much sense if used separately, but can be very helpful
- * if chained:
- * <code>
- * $spamCheck->addRule('empty')
- * ->or_($email->createRule('nonempty', 'Supply a valid email if you want to receive our spam')
- * ->and_($email->createRule('email')));
- * </code>
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @version Release: 0.2.0
- */
-class HTML_QuickForm2_Rule_Empty extends HTML_QuickForm2_Rule
-{
- protected function checkValue($value)
- {
- if (!$this->owner instanceof HTML_QuickForm2_Element_InputFile) {
- return 0 == strlen($value);
- } else {
- return isset($value['error']) && UPLOAD_ERR_NO_FILE == $value['error'];
- }
- }
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/**
- * Rule checking the value's length
- *
- * PHP version 5
- *
- * LICENSE:
- *
- * Copyright (c) 2006, 2007, Alexey Borzov <avb@php.net>,
- * Bertrand Mansion <golgote@mamasam.com>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * The names of the authors may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: Length.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_QuickForm2
- */
-
-/**
- * Base class for HTML_QuickForm2 rules
- */
-require_once 'HTML/QuickForm2/Rule.php';
-
-/**
- * Rule checking the value's length
- *
- * The rule needs an "allowed length" parameter for its work, it can be either
- * - a scalar: the value will be valid if it is exactly this long
- * - an array: the value will be valid if its length is between the given values
- * (inclusive). If one of these evaluates to 0, then length will be compared
- * only with the remaining one.
- *
- * Parameters can be passed to {@link HTML_QuickForm2_Rule::setOptions() setOptions()} in
- * either of the following formats
- * - scalar (if no parameters were registered with Factory then it is treated as
- * an exact length, if 'min' or 'max' was already registered then it is treated
- * as 'max' or 'min', respectively)
- * - array(minlength, maxlength)
- * - array(['min' => minlength, ]['max' => maxlength])
- * and also may be passed to {@link HTML_QuickForm2_Factory::registerRule()} in
- * either of the following formats
- * - scalar (exact length)
- * - array(minlength, maxlength)
- * - array(['min' => minlength, ]['max' => maxlength])
- * global config registered with the Factory overrides options set for the
- * particular Rule instance.
- *
- * The Rule considers empty fields as valid and doesn't try to compare their
- * lengths with provided limits.
- *
- * For convenience this Rule is also registered with the names 'minlength' and
- * 'maxlength' (having, respectively, 'max' and 'min' parameters set to 0):
- * <code>
- * $password->addRule('minlength', 'The password should be at least 6 characters long', 6);
- * $message->addRule('maxlength', 'Your message is too verbose', 1000);
- * </code>
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @version Release: 0.2.0
- */
-class HTML_QuickForm2_Rule_Length extends HTML_QuickForm2_Rule
-{
- /**
- * Validates the element's value
- *
- * @return bool whether length of the element's value is within allowed range
- * @throws HTML_QuickForm2_InvalidArgumentException if a bogus $registeredType
- * was passed to constructor or bogus allowed length(s) were used
- * for rule configuration
- * @throws HTML_QuickForm2_Exception if rule configuration is missing
- */
- protected function checkValue($value)
- {
- if (!empty($this->registeredType)) {
- $config = HTML_QuickForm2_Factory::getRuleConfig($this->registeredType);
- } else {
- $config = null;
- }
- $allowedLength = $this->findAllowedLength($config);
-
- if (0 == ($valueLength = strlen($value))) {
- return true;
- }
- if (is_scalar($allowedLength)) {
- return $valueLength == $allowedLength;
- } else {
- return (!empty($allowedLength['min'])? $valueLength >= $allowedLength['min']: true) &&
- (!empty($allowedLength['max'])? $valueLength <= $allowedLength['max']: true);
- }
- }
-
- /**
- * Adds the 'min' and 'max' fields from one array to the other
- *
- * @param array Rule configuration, array with 'min' and 'max' keys
- * @param array Additional configuration, fields will be added to
- * $length if it doesn't contain such a key already
- * @return array
- */
- protected function mergeMinMaxLength($length, $config)
- {
- if (array_key_exists('min', $config) || array_key_exists('max', $config)) {
- if (!array_key_exists('min', $length) && array_key_exists('min', $config)) {
- $length['min'] = $config['min'];
- }
- if (!array_key_exists('max', $length) && array_key_exists('max', $config)) {
- $length['max'] = $config['max'];
- }
- } else {
- if (!array_key_exists('min', $length)) {
- $length['min'] = reset($config);
- }
- if (!array_key_exists('max', $length)) {
- $length['max'] = end($config);
- }
- }
- return $length;
- }
-
- /**
- * Searches in global config and Rule's options for allowed length limits
- *
- * @param mixed config returned by {@link HTML_QuickForm2_Factory::getRuleConfig()},
- * if applicable
- * @return int|array
- * @throws HTML_QuickForm2_Exception if length limits weren't found anywhere
- * @throws HTML_QuickForm2_InvalidArgumentException if bogus length limits
- * were provided
- */
- protected function findAllowedLength($globalConfig)
- {
- if (0 == count($globalConfig) && 0 == count($this->options)) {
- throw new HTML_QuickForm2_Exception(
- 'Length Rule requires an allowed length parameter'
- );
- }
- if (!is_array($globalConfig)) {
- $length = $globalConfig;
- } else {
- $length = $this->mergeMinMaxLength(array(), $globalConfig);
- }
-
- if (is_array($this->options)) {
- if (!isset($length)) {
- $length = $this->mergeMinMaxLength(array(), $this->options);
- } else {
- $length = $this->mergeMinMaxLength($length, $this->options);
- }
-
- } elseif (isset($this->options)) {
- if (!isset($length)) {
- $length = $this->options;
- } elseif (is_array($length)) {
- if (!array_key_exists('min', $length)) {
- $length['min'] = $this->options;
- } else {
- $length['max'] = $this->options;
- }
- }
- }
-
- if (is_array($length)) {
- $length += array('min' => 0, 'max' => 0);
- }
- if (is_array($length) && ($length['min'] < 0 || $length['max'] < 0) ||
- !is_array($length) && $length < 0)
- {
- throw new HTML_QuickForm2_InvalidArgumentException(
- 'Length Rule requires parameters to be nonnegative, ' .
- preg_replace('/\s+/', ' ', var_export($length, true)) . ' given'
- );
- } elseif (is_array($length) && $length['min'] == 0 && $length['max'] == 0 ||
- !is_array($length) && 0 == $length)
- {
- throw new HTML_QuickForm2_InvalidArgumentException(
- 'Length Rule requires at least one non-zero parameter, ' .
- preg_replace('/\s+/', ' ', var_export($length, true)) . ' given'
- );
- }
-
- if (!empty($length['min']) && !empty($length['max'])) {
- if ($length['min'] > $length['max']) {
- list($length['min'], $length['max']) = array($length['max'], $length['min']);
- } elseif ($length['min'] == $length['max']) {
- $length = $length['min'];
- }
- }
- return $length;
- }
-}
-?>
+++ /dev/null
-<?php
-/**
- * Rule checking that uploaded file size does not exceed the given limit
- *
- * PHP version 5
- *
- * LICENSE:
- *
- * Copyright (c) 2006, 2007, Alexey Borzov <avb@php.net>,
- * Bertrand Mansion <golgote@mamasam.com>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * The names of the authors may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: MaxFileSize.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_QuickForm2
- */
-
-/**
- * Rule checking that uploaded file size does not exceed the given limit
- *
- * The Rule needs one configuration parameter for its work: the size limit.
- * This limit can be passed either to
- * {@link HTML_QuickForm2_Rule::setOptions() setOptions()} or to
- * {@link HTML_QuickForm2_Factory::registerRule()}. Limit registered with the
- * Factory overrides one set for the particular Rule instance via setOptions().
- *
- * Note that if file upload failed due to upload_max_filesize php.ini setting
- * or MAX_FILE_SIZE form field, then this rule won't even be called, due to
- * File element's built-in validation setting the error message.
- *
- * The Rule considers missing file uploads (UPLOAD_ERR_NO_FILE) valid.
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @version Release: 0.2.0
- */
-class HTML_QuickForm2_Rule_MaxFileSize extends HTML_QuickForm2_Rule
-{
- /**
- * Validates the element's value
- *
- * @return bool whether uploaded file's size is within given limit
- * @throws HTML_QuickForm2_InvalidArgumentException if a bogus $registeredType
- * was passed to constructor or a bogus size limit was provided
- */
- protected function checkValue($value)
- {
- if (!empty($this->registeredType)) {
- $limit = HTML_QuickForm2_Factory::getRuleConfig($this->registeredType);
- } else {
- $limit = null;
- }
- if (null === $limit) {
- $limit = $this->getOptions();
- }
- if (0 >= $limit) {
- throw new HTML_QuickForm2_InvalidArgumentException(
- 'MaxFileSize Rule requires a positive size limit, ' .
- preg_replace('/\s+/', ' ', var_export($limit, true)) . ' given'
- );
- }
-
- if (!isset($value['error']) || UPLOAD_ERR_NO_FILE == $value['error']) {
- return true;
- }
- return ($limit >= @filesize($value['tmp_name']));
- }
-
-
- /**
- * Sets the element that will be validated by this rule
- *
- * @param HTML_QuickForm2_Element_InputFile File upload field to validate
- * @throws HTML_QuickForm2_InvalidArgumentException if trying to use
- * this Rule on something that isn't a file upload field
- */
- public function setOwner(HTML_QuickForm2_Node $owner)
- {
- if (!$owner instanceof HTML_QuickForm2_Element_InputFile) {
- throw new HTML_QuickForm2_InvalidArgumentException(
- 'MaxFileSize Rule can only validate file upload fields, '.
- get_class($owner) . ' given'
- );
- }
- parent::setOwner($owner);
- }
-}
-?>
+++ /dev/null
-<?php
-/**
- * Rule checking that uploaded file is of the correct MIME type
- *
- * PHP version 5
- *
- * LICENSE:
- *
- * Copyright (c) 2006, 2007, Alexey Borzov <avb@php.net>,
- * Bertrand Mansion <golgote@mamasam.com>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * The names of the authors may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: MimeType.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_QuickForm2
- */
-
-/**
- * Rule checking that uploaded file is of the correct MIME type
- *
- * The Rule needs one configuration parameter for its work: a string with a
- * desired MIME type or array of such strings. The parameter may be passed to
- * {@link HTML_QuickForm2_Rule::setOptions() setOptions()} or to
- * {@link HTML_QuickForm2_Factory::registerRule()}. Parameter registered with the
- * Factory overrides one set for the particular Rule instance via setOptions().
- *
- * The Rule considers missing file uploads (UPLOAD_ERR_NO_FILE) valid.
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @version Release: 0.2.0
- */
-class HTML_QuickForm2_Rule_MimeType extends HTML_QuickForm2_Rule
-{
- /**
- * Validates the element's value
- *
- * @return bool whether uploaded file's MIME type is correct
- * @throws HTML_QuickForm2_InvalidArgumentException if a bogus $registeredType
- * was passed to constructor or bogus MIME type(s) provided
- */
- protected function checkValue($value)
- {
- if (!empty($this->registeredType)) {
- $mime = HTML_QuickForm2_Factory::getRuleConfig($this->registeredType);
- } else {
- $mime = null;
- }
- if (null === $mime) {
- $mime = $this->getOptions();
- }
- if (0 == count($mime) || !is_string($mime) && !is_array($mime)) {
- throw new HTML_QuickForm2_InvalidArgumentException(
- 'MimeType Rule requires MIME type(s), ' .
- preg_replace('/\s+/', ' ', var_export($mime, true)) . ' given'
- );
- }
-
- if (!isset($value['error']) || UPLOAD_ERR_NO_FILE == $value['error']) {
- return true;
- }
- return is_array($mime)? in_array($value['type'], $mime):
- $value['type'] == $mime;
- }
-
-
- /**
- * Sets the element that will be validated by this rule
- *
- * @param HTML_QuickForm2_Element_InputFile File upload field to validate
- * @throws HTML_QuickForm2_InvalidArgumentException if trying to use
- * this Rule on something that isn't a file upload field
- */
- public function setOwner(HTML_QuickForm2_Node $owner)
- {
- if (!$owner instanceof HTML_QuickForm2_Element_InputFile) {
- throw new HTML_QuickForm2_InvalidArgumentException(
- 'MimeType Rule can only validate file upload fields, '.
- get_class($owner) . ' given'
- );
- }
- parent::setOwner($owner);
- }
-}
-?>
+++ /dev/null
-<?php
-/**
- * Rule checking that the field is not empty
- *
- * PHP version 5
- *
- * LICENSE:
- *
- * Copyright (c) 2006, 2007, Alexey Borzov <avb@php.net>,
- * Bertrand Mansion <golgote@mamasam.com>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * The names of the authors may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: Nonempty.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_QuickForm2
- */
-
-/**
- * Base class for HTML_QuickForm2 rules
- */
-require_once 'HTML/QuickForm2/Rule.php';
-
-/**
- * Rule checking that the field is not empty
- *
- * Handles both simple form fields and file uploads
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @version Release: 0.2.0
- */
-class HTML_QuickForm2_Rule_Nonempty extends HTML_QuickForm2_Rule
-{
- protected function checkValue($value)
- {
- if (!$this->owner instanceof HTML_QuickForm2_Element_InputFile) {
- return (bool)strlen($value);
- } else {
- return isset($value['error']) && (UPLOAD_ERR_OK == $value['error']);
- }
- }
-}
-
-?>
+++ /dev/null
-<?php
-/**
- * Validates values using regular expressions
- *
- * PHP version 5
- *
- * LICENSE:
- *
- * Copyright (c) 2006, 2007, Alexey Borzov <avb@php.net>,
- * Bertrand Mansion <golgote@mamasam.com>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * The names of the authors may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: Regex.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_QuickForm2
- */
-
-/**
- * Base class for HTML_QuickForm2 rules
- */
-require_once 'HTML/QuickForm2/Rule.php';
-
-/**
- * Validates values using regular expressions
- *
- * The Rule needs one configuration parameter for its work: a Perl-compatible
- * regular expression. This expression can be passed either to
- * {@link HTML_QuickForm2_Rule::setOptions() setOptions()} or to
- * {@link HTML_QuickForm2_Factory::registerRule()}. Regular expression
- * registered with the Factory overrides one set for the particular Rule
- * instance via setOptions().
- *
- * The Rule can also validate file uploads, in this case the regular expression
- * is applied to upload's 'name' field.
- *
- * The Rule considers empty fields (file upload fields with UPLOAD_ERR_NO_FILE)
- * as valid and doesn't try to test them with the regular expression.
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @version Release: 0.2.0
- */
-class HTML_QuickForm2_Rule_Regex extends HTML_QuickForm2_Rule
-{
- /**
- * Validates the element's value
- *
- * @return bool whether element's value matches given regular expression
- * @throws HTML_QuickForm2_InvalidArgumentException if a bogus $registeredType
- * was passed to constructor
- * @throws HTML_QuickForm2_Exception if regular expression is missing
- */
- protected function checkValue($value)
- {
- if (!empty($this->registeredType)) {
- $regex = HTML_QuickForm2_Factory::getRuleConfig($this->registeredType);
- } else {
- $regex = null;
- }
- if (null === $regex) {
- $regex = $this->getOptions();
- }
- if (!is_string($regex)) {
- throw new HTML_QuickForm2_Exception(
- 'Regex Rule requires a regular expression, ' .
- preg_replace('/\s+/', ' ', var_export($regex, true)) . ' given'
- );
- }
-
- if ($this->owner instanceof HTML_QuickForm2_Element_InputFile) {
- if (!isset($value['error']) || UPLOAD_ERR_NO_FILE == $value['error']) {
- return true;
- }
- $value = $value['name'];
- } elseif (!strlen($value)) {
- return true;
- }
- return preg_match($regex . 'D', $value);
- }
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/**
- * Rule for required elements
- *
- * PHP version 5
- *
- * LICENSE:
- *
- * Copyright (c) 2006, 2007, Alexey Borzov <avb@php.net>,
- * Bertrand Mansion <golgote@mamasam.com>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * The names of the authors may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: Required.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_QuickForm2
- */
-
-/**
- * Rule checking that the form field is not empty
- */
-require_once 'HTML/QuickForm2/Rule/Nonempty.php';
-
-/**
- * Rule for required elements
- *
- * The main difference from "nonempty" Rule is that
- * - elements to which this Rule is attached will be considered required
- * ({@link HTML_QuickForm2_Node::isRequired()} will return true for them) and
- * marked accordingly when outputting the form
- * - this Rule can only be added directly to the element and other Rules can
- * only be added to it via and_() method
- *
- * @category HTML
- * @package HTML_QuickForm2
- * @author Alexey Borzov <avb@php.net>
- * @author Bertrand Mansion <golgote@mamasam.com>
- * @version Release: 0.2.0
- */
-class HTML_QuickForm2_Rule_Required extends HTML_QuickForm2_Rule_Nonempty
-{
- /**
- * Disallows adding a rule to the chain with an "or" operator
- *
- * Required rules are different from all others because they affect the
- * visual representation of an element ("* denotes required field").
- * Therefore we cannot allow chaining other rules to these via or_(), since
- * this will effectively mean that the field is not required anymore and the
- * visual difference is bogus.
- *
- * @param HTML_QuickForm2_Rule
- * @throws HTML_QuickForm2_Exception
- */
- public function or_(HTML_QuickForm2_Rule $next)
- {
- throw new HTML_QuickForm2_Exception(
- 'or_(): Cannot add a rule to "required" rule'
- );
- }
-}
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * PEAR::HTML_Table makes the design of HTML tables easy, flexible, reusable and
- * efficient.
- *
- * The PEAR::HTML_Table package provides methods for easy and efficient design
- * of HTML tables.
- * - Lots of customization options.
- * - Tables can be modified at any time.
- * - The logic is the same as standard HTML editors.
- * - Handles col and rowspans.
- * - PHP code is shorter, easier to read and to maintain.
- * - Tables options can be reused.
- *
- * For auto filling of data and such then check out
- * http://pear.php.net/package/HTML_Table_Matrix
- *
- * PHP versions 4 and 5
- *
- * LICENSE:
- *
- * Copyright (c) 2005-2007, Adam Daniel <adaniel1@eesus.jnj.com>,
- * Bertrand Mansion <bmansion@mamasam.com>,
- * Mark Wiesemann <wiesemann@php.net>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * The names of the authors may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- *
- * @category HTML
- * @package HTML_Table
- * @author Adam Daniel <adaniel1@eesus.jnj.com>
- * @author Bertrand Mansion <bmansion@mamasam.com>
- * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: Table.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_Table
- */
-
-
-/**
-* Requires PEAR, HTML_Common and HTML_Table_Storage
-*/
-require_once 'PEAR.php';
-require_once 'HTML/Common.php';
-require_once 'HTML/Table/Storage.php';
-
-/**
- * PEAR::HTML_Table makes the design of HTML tables easy, flexible, reusable and efficient.
- *
- * The PEAR::HTML_Table package provides methods for easy and efficient design
- * of HTML tables.
- * - Lots of customization options.
- * - Tables can be modified at any time.
- * - The logic is the same as standard HTML editors.
- * - Handles col and rowspans.
- * - PHP code is shorter, easier to read and to maintain.
- * - Tables options can be reused.
- *
- * For auto filling of data and such then check out
- * http://pear.php.net/package/HTML_Table_Matrix
- *
- * @category HTML
- * @package HTML_Table
- * @author Adam Daniel <adaniel1@eesus.jnj.com>
- * @author Bertrand Mansion <bmansion@mamasam.com>
- * @copyright 2005-2006 The PHP Group
- * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
- * @version Release: @package_version@
- * @link http://pear.php.net/package/HTML_Table
- */
-class HTML_Table extends HTML_Common {
-
- /**
- * Value to insert into empty cells. This is used as a default for
- * newly-created tbodies.
- * @var string
- * @access private
- */
- var $_autoFill = ' ';
-
- /**
- * Automatically adds a new row, column, or body if a given row, column, or
- * body index does not exist.
- * This is used as a default for newly-created tbodies.
- * @var bool
- * @access private
- */
- var $_autoGrow = true;
-
- /**
- * Array containing the table caption
- * @var array
- * @access private
- */
- var $_caption = array();
-
- /**
- * Array containing the table column group specifications
- *
- * @var array
- * @author Laurent Laville (pear at laurent-laville dot org)
- * @access private
- */
- var $_colgroup = array();
-
- /**
- * HTML_Table_Storage object for the (t)head of the table
- * @var object
- * @access private
- */
- var $_thead = null;
-
- /**
- * HTML_Table_Storage object for the (t)foot of the table
- * @var object
- * @access private
- */
- var $_tfoot = null;
-
- /**
- * HTML_Table_Storage object for the (t)body of the table
- * @var object
- * @access private
- */
- var $_tbodies = array();
-
- /**
- * Number of bodies in the table
- * @var int
- * @access private
- */
- var $_tbodyCount = 0;
-
- /**
- * Whether to use <thead>, <tfoot> and <tbody> or not
- * @var bool
- * @access private
- */
- var $_useTGroups = false;
-
- /**
- * Class constructor
- * @param array $attributes Associative array of table tag
- * attributes
- * @param int $tabOffset Tab offset of the table
- * @param bool $useTGroups Whether to use <thead>, <tfoot> and
- * <tbody> or not
- * @access public
- */
- function HTML_Table($attributes = null, $tabOffset = 0, $useTGroups = false)
- {
- HTML_Common::HTML_Common($attributes, (int)$tabOffset);
- $this->_useTGroups = (boolean)$useTGroups;
- $this->addBody();
- if ($this->_useTGroups) {
- $this->_thead =& new HTML_Table_Storage($tabOffset, $this->_useTGroups);
- $this->_tfoot =& new HTML_Table_Storage($tabOffset, $this->_useTGroups);
- }
- }
-
- /**
- * Returns the API version
- * @access public
- * @return double
- * @deprecated
- */
- function apiVersion()
- {
- return 1.7;
- }
-
- /**
- * Returns the HTML_Table_Storage object for <thead>
- * @access public
- * @return object
- */
- function &getHeader()
- {
- if (is_null($this->_thead)) {
- $this->_useTGroups = true;
- $this->_thead =& new HTML_Table_Storage($this->_tabOffset,
- $this->_useTGroups);
- for ($i = 0; $i < $this->_tbodyCount; $i++) {
- $this->_tbodies[$i]->setUseTGroups(true);
- }
- }
- return $this->_thead;
- }
-
- /**
- * Returns the HTML_Table_Storage object for <tfoot>
- * @access public
- * @return object
- */
- function &getFooter()
- {
- if (is_null($this->_tfoot)) {
- $this->_useTGroups = true;
- $this->_tfoot =& new HTML_Table_Storage($this->_tabOffset,
- $this->_useTGroups);
- for ($i = 0; $i < $this->_tbodyCount; $i++) {
- $this->_tbodies[$i]->setUseTGroups(true);
- }
- }
- return $this->_tfoot;
- }
-
- /**
- * Returns the HTML_Table_Storage object for the specified <tbody>
- * (or the whole table if <t{head|foot|body}> is not used)
- * @param int $body (optional) The index of the body to
- * return.
- * @access public
- * @return object
- * @throws PEAR_Error
- */
- function &getBody($body = 0)
- {
- $ret = $this->_adjustTbodyCount($body, 'getBody');
- if (PEAR::isError($ret)) {
- return $ret;
- }
- return $this->_tbodies[$body];
- }
-
- /**
- * Adds a table body and returns the body identifier
- * @param mixed $attributes (optional) Associative array or
- * string of table body attributes
- * @access public
- * @return int
- */
- function addBody($attributes = null)
- {
- if (!$this->_useTGroups && $this->_tbodyCount > 0) {
- for ($i = 0; $i < $this->_tbodyCount; $i++) {
- $this->_tbodies[$i]->setUseTGroups(true);
- }
- $this->_useTGroups = true;
- }
-
- $body = $this->_tbodyCount++;
- $this->_tbodies[$body] =& new HTML_Table_Storage($this->_tabOffset,
- $this->_useTGroups);
- $this->_tbodies[$body]->setAutoFill($this->_autoFill);
- $this->_tbodies[$body]->setAttributes($attributes);
- return $body;
- }
-
- /**
- * Adjusts the number of bodies
- * @param int $body Body index
- * @param string $method Name of calling method
- * @access private
- * @throws PEAR_Error
- */
- function _adjustTbodyCount($body, $method)
- {
- if ($this->_autoGrow) {
- while ($this->_tbodyCount <= (int)$body) {
- $this->addBody();
- }
- } else {
- return PEAR::raiseError('Invalid body reference[' .
- $body . '] in HTML_Table::' . $method);
- }
- }
-
- /**
- * Sets the table caption
- * @param string $caption
- * @param mixed $attributes Associative array or string of
- * table row attributes
- * @access public
- */
- function setCaption($caption, $attributes = null)
- {
- $attributes = $this->_parseAttributes($attributes);
- $this->_caption = array('attr' => $attributes, 'contents' => $caption);
- }
-
- /**
- * Sets the table columns group specifications, or removes existing ones.
- *
- * @param mixed $colgroup (optional) Columns attributes
- * @param mixed $attributes (optional) Associative array or string
- * of table row attributes
- * @author Laurent Laville (pear at laurent-laville dot org)
- * @access public
- */
- function setColGroup($colgroup = null, $attributes = null)
- {
- if (isset($colgroup)) {
- $attributes = $this->_parseAttributes($attributes);
- $this->_colgroup[] = array('attr' => $attributes,
- 'contents' => $colgroup);
- } else {
- $this->_colgroup = array();
- }
- }
-
- /**
- * Sets the autoFill value
- * @param mixed $fill Whether autoFill should be enabled or not
- * @param int $body (optional) The index of the body to set.
- * Pass null to set for all bodies.
- * @access public
- * @throws PEAR_Error
- */
- function setAutoFill($fill, $body = null)
- {
- if (!is_null($body)) {
- $ret = $this->_adjustTbodyCount($body, 'setAutoFill');
- if (PEAR::isError($ret)) {
- return $ret;
- }
- $this->_tbodies[$body]->setAutoFill($fill);
- } else {
- $this->_autoFill = $fill;
- for ($i = 0; $i < $this->_tbodyCount; $i++) {
- $this->_tbodies[$i]->setAutoFill($fill);
- }
- }
- }
-
- /**
- * Returns the autoFill value
- * @param int $body (optional) The index of the body to get.
- * Pass null to get the default for new bodies.
- * @access public
- * @return mixed
- * @throws PEAR_Error
- */
- function getAutoFill($body = null)
- {
- if (!is_null($body)) {
- $ret = $this->_adjustTbodyCount($body, 'getAutoFill');
- if (PEAR::isError($ret)) {
- return $ret;
- }
- return $this->_tbodies[$body]->getAutoFill();
- } else {
- return $this->_autoFill;
- }
- }
-
- /**
- * Sets the autoGrow value
- * @param bool $grow Whether autoGrow should be enabled or not
- * @param int $body (optional) The index of the body to set.
- * Pass null to set for all bodies.
- * @access public
- * @throws PEAR_Error
- */
- function setAutoGrow($grow, $body = null)
- {
- if (!is_null($body)) {
- $ret = $this->_adjustTbodyCount($body, 'setAutoGrow');
- if (PEAR::isError($ret)) {
- return $ret;
- }
- $this->_tbodies[$body]->setAutoGrow($grow);
- } else {
- $this->_autoGrow = $grow;
- for ($i = 0; $i < $this->_tbodyCount; $i++) {
- $this->_tbodies[$i]->setAutoGrow($grow);
- }
- }
- }
-
- /**
- * Returns the autoGrow value
- * @param int $body (optional) The index of the body to get.
- * Pass null to get the default for new bodies.
- * @access public
- * @return mixed
- * @throws PEAR_Error
- */
- function getAutoGrow($body = null)
- {
- if (!is_null($body)) {
- $ret = $this->_adjustTbodyCount($body, 'getAutoGrow');
- if (PEAR::isError($ret)) {
- return $ret;
- }
- return $this->_tbodies[$body]->getAutoGrow();
- } else {
- return $this->_autoGrow;
- }
- }
-
- /**
- * Sets the number of rows in the table body
- * @param int $rows The number of rows
- * @param int $body (optional) The index of the body to set.
- * @access public
- * @throws PEAR_Error
- */
- function setRowCount($rows, $body = 0)
- {
- $ret = $this->_adjustTbodyCount($body, 'setRowCount');
- if (PEAR::isError($ret)) {
- return $ret;
- }
- $this->_tbodies[$body]->setRowCount($rows);
- }
-
- /**
- * Sets the number of columns in the table
- * @param int $cols The number of columns
- * @param int $body (optional) The index of the body to set.
- * @access public
- * @throws PEAR_Error
- */
- function setColCount($cols, $body = 0)
- {
- $ret = $this->_adjustTbodyCount($body, 'setColCount');
- if (PEAR::isError($ret)) {
- return $ret;
- }
- $this->_tbodies[$body]->setColCount($cols);
- }
-
- /**
- * Returns the number of rows in the table
- * @param int $body (optional) The index of the body to get.
- * Pass null to get the total number of
- * rows in all bodies.
- * @access public
- * @return int
- * @throws PEAR_Error
- */
- function getRowCount($body = null)
- {
- if (!is_null($body)) {
- $ret = $this->_adjustTbodyCount($body, 'getRowCount');
- if (PEAR::isError($ret)) {
- return $ret;
- }
- return $this->_tbodies[$body]->getRowCount();
- } else {
- $rowCount = 0;
- for ($i = 0; $i < $this->_tbodyCount; $i++) {
- $rowCount += $this->_tbodies[$i]->getRowCount();
- }
- return $rowCount;
- }
- }
-
- /**
- * Gets the number of columns in the table
- *
- * If a row index is specified, the count will not take
- * the spanned cells into account in the return value.
- *
- * @param int $row Row index to serve for cols count
- * @param int $body (optional) The index of the body to get.
- * @access public
- * @return int
- * @throws PEAR_Error
- */
- function getColCount($row = null, $body = 0)
- {
- $ret = $this->_adjustTbodyCount($body, 'getColCount');
- if (PEAR::isError($ret)) {
- return $ret;
- }
- return $this->_tbodies[$body]->getColCount($row);
- }
-
- /**
- * Sets a rows type 'TH' or 'TD'
- * @param int $row Row index
- * @param string $type 'TH' or 'TD'
- * @param int $body (optional) The index of the body to set.
- * @access public
- * @throws PEAR_Error
- */
- function setRowType($row, $type, $body = 0)
- {
- $ret = $this->_adjustTbodyCount($body, 'setRowType');
- if (PEAR::isError($ret)) {
- return $ret;
- }
- $this->_tbodies[$body]->setRowType($row, $type);
- }
-
- /**
- * Sets a columns type 'TH' or 'TD'
- * @param int $col Column index
- * @param string $type 'TH' or 'TD'
- * @param int $body (optional) The index of the body to set.
- * Pass null to set for all bodies.
- * @access public
- * @throws PEAR_Error
- */
- function setColType($col, $type, $body = null)
- {
- if (!is_null($body)) {
- $ret = $this->_adjustTbodyCount($body, 'setColType');
- if (PEAR::isError($ret)) {
- return $ret;
- }
- $this->_tbodies[$body]->setColType($col, $type);
- } else {
- for ($i = 0; $i < $this->_tbodyCount; $i++) {
- $this->_tbodies[$i]->setColType($col, $type);
- }
- }
- }
-
- /**
- * Sets the cell attributes for an existing cell.
- *
- * If the given indices do not exist and autoGrow is true then the given
- * row and/or col is automatically added. If autoGrow is false then an
- * error is returned.
- * @param int $row Row index
- * @param int $col Column index
- * @param mixed $attributes Associative array or string of
- * table row attributes
- * @param int $body (optional) The index of the body to set.
- * @access public
- * @throws PEAR_Error
- */
- function setCellAttributes($row, $col, $attributes, $body = 0)
- {
- $ret = $this->_adjustTbodyCount($body, 'setCellAttributes');
- if (PEAR::isError($ret)) {
- return $ret;
- }
- $ret = $this->_tbodies[$body]->setCellAttributes($row, $col, $attributes);
- if (PEAR::isError($ret)) {
- return $ret;
- }
- }
-
- /**
- * Updates the cell attributes passed but leaves other existing attributes
- * intact
- * @param int $row Row index
- * @param int $col Column index
- * @param mixed $attributes Associative array or string of table row
- * attributes
- * @param int $body (optional) The index of the body to set.
- * @access public
- * @throws PEAR_Error
- */
- function updateCellAttributes($row, $col, $attributes, $body = 0)
- {
- $ret = $this->_adjustTbodyCount($body, 'updateCellAttributes');
- if (PEAR::isError($ret)) {
- return $ret;
- }
- $ret = $this->_tbodies[$body]->updateCellAttributes($row, $col, $attributes);
- if (PEAR::isError($ret)) {
- return $ret;
- }
- }
-
- /**
- * Returns the attributes for a given cell
- * @param int $row Row index
- * @param int $col Column index
- * @param int $body (optional) The index of the body to get.
- * @return array
- * @access public
- * @throws PEAR_Error
- */
- function getCellAttributes($row, $col, $body = 0)
- {
- $ret = $this->_adjustTbodyCount($body, 'getCellAttributes');
- if (PEAR::isError($ret)) {
- return $ret;
- }
- return $this->_tbodies[$body]->getCellAttributes($row, $col);
- }
-
- /**
- * Sets the cell contents for an existing cell
- *
- * If the given indices do not exist and autoGrow is true then the given
- * row and/or col is automatically added. If autoGrow is false then an
- * error is returned.
- * @param int $row Row index
- * @param int $col Column index
- * @param mixed $contents May contain html or any object with a
- * toHTML() method; it is an array (with
- * strings and/or objects), $col will be
- * used as start offset and the array
- * elements will be set to this and the
- * following columns in $row
- * @param string $type (optional) Cell type either 'TH' or 'TD'
- * @param int $body (optional) The index of the body to set.
- * @access public
- * @throws PEAR_Error
- */
- function setCellContents($row, $col, $contents, $type = 'TD', $body = 0)
- {
- $ret = $this->_adjustTbodyCount($body, 'setCellContents');
- if (PEAR::isError($ret)) {
- return $ret;
- }
- $ret = $this->_tbodies[$body]->setCellContents($row, $col, $contents, $type);
- if (PEAR::isError($ret)) {
- return $ret;
- }
- }
-
- /**
- * Returns the cell contents for an existing cell
- * @param int $row Row index
- * @param int $col Column index
- * @param int $body (optional) The index of the body to get.
- * @access public
- * @return mixed
- * @throws PEAR_Error
- */
- function getCellContents($row, $col, $body = 0)
- {
- $ret = $this->_adjustTbodyCount($body, 'getCellContents');
- if (PEAR::isError($ret)) {
- return $ret;
- }
- return $this->_tbodies[$body]->getCellContents($row, $col);
- }
-
- /**
- * Sets the contents of a header cell
- * @param int $row
- * @param int $col
- * @param mixed $contents
- * @param mixed $attributes Associative array or string of
- * table row attributes
- * @param int $body (optional) The index of the body to set.
- * @access public
- * @throws PEAR_Error
- */
- function setHeaderContents($row, $col, $contents, $attributes = null,
- $body = 0)
- {
- $ret = $this->_adjustTbodyCount($body, 'setHeaderContents');
- if (PEAR::isError($ret)) {
- return $ret;
- }
- $this->_tbodies[$body]->setHeaderContents($row, $col, $contents, $attributes);
- }
-
- /**
- * Adds a table row and returns the row identifier
- * @param array $contents (optional) Must be a indexed array of
- * valid cell contents
- * @param mixed $attributes (optional) Associative array or string
- * of table row attributes. This can also
- * be an array of attributes, in which
- * case the attributes will be repeated
- * in a loop.
- * @param string $type (optional) Cell type either 'th' or 'td'
- * @param bool $inTR false if attributes are to be applied
- * in TD tags; true if attributes are to
- * ´be applied in TR tag
- * @param int $body (optional) The index of the body to use.
- * @return int
- * @access public
- * @throws PEAR_Error
- */
- function addRow($contents = null, $attributes = null, $type = 'td',
- $inTR = false, $body = 0)
- {
- $ret = $this->_adjustTbodyCount($body, 'addRow');
- if (PEAR::isError($ret)) {
- return $ret;
- }
- $ret = $this->_tbodies[$body]->addRow($contents, $attributes, $type, $inTR);
- return $ret;
- }
-
- /**
- * Sets the row attributes for an existing row
- * @param int $row Row index
- * @param mixed $attributes Associative array or string of table row
- * attributes. This can also be an array of
- * attributes, in which case the attributes
- * will be repeated in a loop.
- * @param bool $inTR false if attributes are to be applied in
- * TD tags; true if attributes are to be
- * applied in TR tag
- * @param int $body (optional) The index of the body to set.
- * @access public
- * @throws PEAR_Error
- */
- function setRowAttributes($row, $attributes, $inTR = false, $body = 0)
- {
- $ret = $this->_adjustTbodyCount($body, 'setRowAttributes');
- if (PEAR::isError($ret)) {
- return $ret;
- }
- $ret = $this->_tbodies[$body]->setRowAttributes($row, $attributes, $inTR);
- if (PEAR::isError($ret)) {
- return $ret;
- }
- }
-
- /**
- * Updates the row attributes for an existing row
- * @param int $row Row index
- * @param mixed $attributes Associative array or string of table row
- * attributes
- * @param bool $inTR false if attributes are to be applied in
- * TD tags; true if attributes are to be
- * applied in TR tag
- * @param int $body (optional) The index of the body to set.
- * @access public
- * @throws PEAR_Error
- */
- function updateRowAttributes($row, $attributes = null, $inTR = false,
- $body = 0)
- {
- $ret = $this->_adjustTbodyCount($body, 'updateRowAttributes');
- if (PEAR::isError($ret)) {
- return $ret;
- }
- $ret = $this->_tbodies[$body]->updateRowAttributes($row, $attributes, $inTR);
- if (PEAR::isError($ret)) {
- return $ret;
- }
- }
-
- /**
- * Returns the attributes for a given row as contained in the TR tag
- * @param int $row Row index
- * @param int $body (optional) The index of the body to get.
- * @return array
- * @access public
- * @throws PEAR_Error
- */
- function getRowAttributes($row, $body = 0)
- {
- $ret = $this->_adjustTbodyCount($body, 'getRowAttributes');
- if (PEAR::isError($ret)) {
- return $ret;
- }
- return $this->_tbodies[$body]->getRowAttributes($row);
- }
-
- /**
- * Alternates the row attributes starting at $start
- * @param int $start Row index of row in which alternating
- * begins
- * @param mixed $attributes1 Associative array or string of table
- * row attributes
- * @param mixed $attributes2 Associative array or string of table
- * row attributes
- * @param bool $inTR false if attributes are to be applied
- * in TD tags; true if attributes are to
- * be applied in TR tag
- * @param int $firstAttributes (optional) Which attributes should be
- * applied to the first row, 1 or 2.
- * @param int $body (optional) The index of the body to set.
- * Pass null to set for all bodies.
- * @access public
- * @throws PEAR_Error
- */
- function altRowAttributes($start, $attributes1, $attributes2, $inTR = false,
- $firstAttributes = 1, $body = null)
- {
- if (!is_null($body)) {
- $ret = $this->_adjustTbodyCount($body, 'altRowAttributes');
- if (PEAR::isError($ret)) {
- return $ret;
- }
- $this->_tbodies[$body]->altRowAttributes($start, $attributes1,
- $attributes2, $inTR, $firstAttributes);
- } else {
- for ($i = 0; $i < $this->_tbodyCount; $i++) {
- $this->_tbodies[$i]->altRowAttributes($start, $attributes1,
- $attributes2, $inTR, $firstAttributes);
- // if the tbody's row count is odd, toggle $firstAttributes to
- // prevent the next tbody's first row from having the same
- // attributes as this tbody's last row.
- if ($this->_tbodies[$i]->getRowCount() % 2) {
- $firstAttributes ^= 3;
- }
- }
- }
- }
-
- /**
- * Adds a table column and returns the column identifier
- * @param array $contents (optional) Must be a indexed array of
- * valid cell contents
- * @param mixed $attributes (optional) Associative array or string
- * of table row attributes
- * @param string $type (optional) Cell type either 'th' or 'td'
- * @param int $body (optional) The index of the body to use.
- * @return int
- * @access public
- * @throws PEAR_Error
- */
- function addCol($contents = null, $attributes = null, $type = 'td', $body = 0)
- {
- $ret = $this->_adjustTbodyCount($body, 'addCol');
- if (PEAR::isError($ret)) {
- return $ret;
- }
- return $this->_tbodies[$body]->addCol($contents, $attributes, $type);
- }
-
- /**
- * Sets the column attributes for an existing column
- * @param int $col Column index
- * @param mixed $attributes (optional) Associative array or string
- * of table row attributes
- * @param int $body (optional) The index of the body to set.
- * Pass null to set for all bodies.
- * @access public
- * @throws PEAR_Error
- */
- function setColAttributes($col, $attributes = null, $body = null)
- {
- if (!is_null($body)) {
- $ret = $this->_adjustTbodyCount($body, 'setColAttributes');
- if (PEAR::isError($ret)) {
- return $ret;
- }
- $this->_tbodies[$body]->setColAttributes($col, $attributes);
- } else {
- for ($i = 0; $i < $this->_tbodyCount; $i++) {
- $this->_tbodies[$i]->setColAttributes($col, $attributes);
- }
- }
- }
-
- /**
- * Updates the column attributes for an existing column
- * @param int $col Column index
- * @param mixed $attributes (optional) Associative array or
- * string of table row attributes
- * @param int $body (optional) The index of the body to set.
- * Pass null to set for all bodies.
- * @access public
- * @throws PEAR_Error
- */
- function updateColAttributes($col, $attributes = null, $body = null)
- {
- if (!is_null($body)) {
- $ret = $this->_adjustTbodyCount($body, 'updateColAttributes');
- if (PEAR::isError($ret)) {
- return $ret;
- }
- $this->_tbodies[$body]->updateColAttributes($col, $attributes);
- } else {
- for ($i = 0; $i < $this->_tbodyCount; $i++) {
- $this->_tbodies[$i]->updateColAttributes($col, $attributes);
- }
- }
- }
-
- /**
- * Sets the attributes for all cells
- * @param mixed $attributes (optional) Associative array or
- * string of table row attributes
- * @param int $body (optional) The index of the body to set.
- * Pass null to set for all bodies.
- * @access public
- * @throws PEAR_Error
- */
- function setAllAttributes($attributes = null, $body = null)
- {
- if (!is_null($body)) {
- $ret = $this->_adjustTbodyCount($body, 'setAllAttributes');
- if (PEAR::isError($ret)) {
- return $ret;
- }
- $this->_tbodies[$body]->setAllAttributes($attributes);
- } else {
- for ($i = 0; $i < $this->_tbodyCount; $i++) {
- $this->_tbodies[$i]->setAllAttributes($attributes);
- }
- }
- }
-
- /**
- * Updates the attributes for all cells
- * @param mixed $attributes (optional) Associative array or string
- * of table row attributes
- * @param int $body (optional) The index of the body to set.
- * Pass null to set for all bodies.
- * @access public
- * @throws PEAR_Error
- */
- function updateAllAttributes($attributes = null, $body = null)
- {
- if (!is_null($body)) {
- $ret = $this->_adjustTbodyCount($body, 'updateAllAttributes');
- if (PEAR::isError($ret)) {
- return $ret;
- }
- $this->_tbodies[$body]->updateAllAttributes($attributes);
- } else {
- for ($i = 0; $i < $this->_tbodyCount; $i++) {
- $this->_tbodies[$i]->updateAllAttributes($attributes);
- }
- }
- }
-
- /**
- * Returns the table structure as HTML
- * @access public
- * @return string
- */
- function toHtml()
- {
- $strHtml = '';
- $tabs = $this->_getTabs();
- $tab = $this->_getTab();
- $lnEnd = $this->_getLineEnd();
- $tBodyColCounts = array();
- for ($i = 0; $i < $this->_tbodyCount; $i++) {
- $tBodyColCounts[] = $this->_tbodies[$i]->getColCount();
- }
- $tBodyMaxColCount = 0;
- if (count($tBodyColCounts) > 0) {
- $tBodyMaxColCount = max($tBodyColCounts);
- }
- if ($this->_comment) {
- $strHtml .= $tabs . "<!-- $this->_comment -->" . $lnEnd;
- }
- if ($this->getRowCount() > 0 && $tBodyMaxColCount > 0) {
- $strHtml .=
- $tabs . '<table' . $this->_getAttrString($this->_attributes) . '>' . $lnEnd;
- if (!empty($this->_caption)) {
- $attr = $this->_caption['attr'];
- $contents = $this->_caption['contents'];
- $strHtml .= $tabs . $tab . '<caption' . $this->_getAttrString($attr) . '>';
- if (is_array($contents)) {
- $contents = implode(', ', $contents);
- }
- $strHtml .= $contents;
- $strHtml .= '</caption>' . $lnEnd;
- }
- if (!empty($this->_colgroup)) {
- foreach ($this->_colgroup as $g => $col) {
- $attr = $this->_colgroup[$g]['attr'];
- $contents = $this->_colgroup[$g]['contents'];
- $strHtml .= $tabs . $tab . '<colgroup' . $this->_getAttrString($attr) . '>';
- if (!empty($contents)) {
- $strHtml .= $lnEnd;
- if (!is_array($contents)) {
- $contents = array($contents);
- }
- foreach ($contents as $a => $colAttr) {
- $attr = $this->_parseAttributes($colAttr);
- $strHtml .= $tabs . $tab . $tab . '<col' . $this->_getAttrString($attr) . ' />' . $lnEnd;
- }
- $strHtml .= $tabs . $tab;
- }
- $strHtml .= '</colgroup>' . $lnEnd;
- }
- }
- if ($this->_useTGroups) {
- $tHeadColCount = 0;
- if ($this->_thead !== null) {
- $tHeadColCount = $this->_thead->getColCount();
- }
- $tFootColCount = 0;
- if ($this->_tfoot !== null) {
- $tFootColCount = $this->_tfoot->getColCount();
- }
- $maxColCount = max($tHeadColCount, $tFootColCount, $tBodyMaxColCount);
- if ($this->_thead !== null) {
- $this->_thead->setColCount($maxColCount);
- if ($this->_thead->getRowCount() > 0) {
- $strHtml .= $tabs . $tab . '<thead' .
- $this->_getAttrString($this->_thead->_attributes) .
- '>' . $lnEnd;
- $strHtml .= $this->_thead->toHtml($tabs, $tab);
- $strHtml .= $tabs . $tab . '</thead>' . $lnEnd;
- }
- }
- if ($this->_tfoot !== null) {
- $this->_tfoot->setColCount($maxColCount);
- if ($this->_tfoot->getRowCount() > 0) {
- $strHtml .= $tabs . $tab . '<tfoot' .
- $this->_getAttrString($this->_tfoot->_attributes) .
- '>' . $lnEnd;
- $strHtml .= $this->_tfoot->toHtml($tabs, $tab);
- $strHtml .= $tabs . $tab . '</tfoot>' . $lnEnd;
- }
- }
- for ($i = 0; $i < $this->_tbodyCount; $i++) {
- $this->_tbodies[$i]->setColCount($maxColCount);
- if ($this->_tbodies[$i]->getRowCount() > 0) {
- $strHtml .= $tabs . $tab . '<tbody' .
- $this->_getAttrString($this->_tbodies[$i]->_attributes) .
- '>' . $lnEnd;
- $strHtml .= $this->_tbodies[$i]->toHtml($tabs, $tab);
- $strHtml .= $tabs . $tab . '</tbody>' . $lnEnd;
- }
- }
- } else {
- for ($i = 0; $i < $this->_tbodyCount; $i++) {
- $strHtml .= $this->_tbodies[$i]->toHtml($tabs, $tab);
- }
- }
- $strHtml .= $tabs . '</table>' . $lnEnd;
- }
- return $strHtml;
- }
-
-}
-
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * Storage class for HTML::Table data
- *
- * This class stores data for tables built with HTML_Table. When having
- * more than one instance, it can be used for grouping the table into the
- * parts <thead>...</thead>, <tfoot>...</tfoot> and <tbody>...</tbody>.
- *
- * PHP versions 4 and 5
- *
- * LICENSE:
- *
- * Copyright (c) 2005-2007, Adam Daniel <adaniel1@eesus.jnj.com>,
- * Bertrand Mansion <bmansion@mamasam.com>,
- * Mark Wiesemann <wiesemann@php.net>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * The names of the authors may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * @category HTML
- * @package HTML_Table
- * @author Adam Daniel <adaniel1@eesus.jnj.com>
- * @author Bertrand Mansion <bmansion@mamasam.com>
- * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: Storage.php,v 1.1.1.1 2008/04/28 15:20:50 jamie Exp $
- * @link http://pear.php.net/package/HTML_Table
- */
-
-/**
- * Storage class for HTML::Table data
- *
- * This class stores data for tables built with HTML_Table. When having
- * more than one instance, it can be used for grouping the table into the
- * parts <thead>...</thead>, <tfoot>...</tfoot> and <tbody>...</tbody>.
- *
- * @category HTML
- * @package HTML_Table
- * @author Adam Daniel <adaniel1@eesus.jnj.com>
- * @author Bertrand Mansion <bmansion@mamasam.com>
- * @author Mark Wiesemann <wiesemann@php.net>
- * @copyright 2005-2006 The PHP Group
- * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
- * @version Release: @package_version@
- * @link http://pear.php.net/package/HTML_Table
- */
-class HTML_Table_Storage extends HTML_Common {
-
- /**
- * Value to insert into empty cells
- * @var string
- * @access private
- */
- var $_autoFill = ' ';
-
- /**
- * Automatically adds a new row or column if a given row or column index
- * does not exist
- * @var bool
- * @access private
- */
- var $_autoGrow = true;
-
- /**
- * Array containing the table structure
- * @var array
- * @access private
- */
- var $_structure = array();
-
- /**
- * Number of rows composing in the table
- * @var int
- * @access private
- */
- var $_rows = 0;
-
- /**
- * Number of column composing the table
- * @var int
- * @access private
- */
- var $_cols = 0;
-
- /**
- * Tracks the level of nested tables
- * @var int
- * @access private
- */
- var $_nestLevel = 0;
-
- /**
- * Whether to use <thead>, <tfoot> and <tbody> or not
- * @var bool
- * @access private
- */
- var $_useTGroups = false;
-
- /**
- * Class constructor
- * @param int $tabOffset
- * @param bool $useTGroups Whether to use <thead>, <tfoot> and
- * <tbody> or not
- * @access public
- */
- function HTML_Table_Storage($tabOffset = 0, $useTGroups = false)
- {
- HTML_Common::HTML_Common(null, (int)$tabOffset);
- $this->_useTGroups = (boolean)$useTGroups;
- }
-
- /**
- * Sets the useTGroups value
- * @param boolean $useTGroups
- * @access public
- */
- function setUseTGroups($useTGroups)
- {
- $this->_useTGroups = $useTGroups;
- }
-
- /**
- * Returns the useTGroups value
- * @access public
- * @return boolean
- */
- function getUseTGroups()
- {
- return $this->_useTGroups;
- }
-
- /**
- * Sets the autoFill value
- * @param mixed $fill
- * @access public
- */
- function setAutoFill($fill)
- {
- $this->_autoFill = $fill;
- }
-
- /**
- * Returns the autoFill value
- * @access public
- * @return mixed
- */
- function getAutoFill()
- {
- return $this->_autoFill;
- }
-
- /**
- * Sets the autoGrow value
- * @param bool $fill
- * @access public
- */
- function setAutoGrow($grow)
- {
- $this->_autoGrow = $grow;
- }
-
- /**
- * Returns the autoGrow value
- * @access public
- * @return mixed
- */
- function getAutoGrow()
- {
- return $this->_autoGrow;
- }
-
- /**
- * Sets the number of rows in the table
- * @param int $rows
- * @access public
- */
- function setRowCount($rows)
- {
- $this->_rows = $rows;
- }
-
- /**
- * Sets the number of columns in the table
- * @param int $cols
- * @access public
- */
- function setColCount($cols)
- {
- $this->_cols = $cols;
- }
-
- /**
- * Returns the number of rows in the table
- * @access public
- * @return int
- */
- function getRowCount()
- {
- return $this->_rows;
- }
-
- /**
- * Gets the number of columns in the table
- *
- * If a row index is specified, the count will not take
- * the spanned cells into account in the return value.
- *
- * @param int Row index to serve for cols count
- * @access public
- * @return int
- */
- function getColCount($row = null)
- {
- if (!is_null($row)) {
- $count = 0;
- foreach ($this->_structure[$row] as $cell) {
- if (is_array($cell)) {
- $count++;
- }
- }
- return $count;
- }
- return $this->_cols;
- }
-
- /**
- * Sets a rows type 'TH' or 'TD'
- * @param int $row Row index
- * @param string $type 'TH' or 'TD'
- * @access public
- */
-
- function setRowType($row, $type)
- {
- for ($counter = 0; $counter < $this->_cols; $counter++) {
- $this->_structure[$row][$counter]['type'] = $type;
- }
- }
-
- /**
- * Sets a columns type 'TH' or 'TD'
- * @param int $col Column index
- * @param string $type 'TH' or 'TD'
- * @access public
- */
- function setColType($col, $type)
- {
- for ($counter = 0; $counter < $this->_rows; $counter++) {
- $this->_structure[$counter][$col]['type'] = $type;
- }
- }
-
- /**
- * Sets the cell attributes for an existing cell.
- *
- * If the given indices do not exist and autoGrow is true then the given
- * row and/or col is automatically added. If autoGrow is false then an
- * error is returned.
- * @param int $row Row index
- * @param int $col Column index
- * @param mixed $attributes Associative array or string of table
- * row attributes
- * @access public
- * @throws PEAR_Error
- */
- function setCellAttributes($row, $col, $attributes)
- {
- if ( isset($this->_structure[$row][$col])
- && $this->_structure[$row][$col] == '__SPANNED__'
- ) {
- return;
- }
- $attributes = $this->_parseAttributes($attributes);
- $err = $this->_adjustEnds($row, $col, 'setCellAttributes', $attributes);
- if (PEAR::isError($err)) {
- return $err;
- }
- $this->_structure[$row][$col]['attr'] = $attributes;
- $this->_updateSpanGrid($row, $col);
- }
-
- /**
- * Updates the cell attributes passed but leaves other existing attributes
- * intact
- * @param int $row Row index
- * @param int $col Column index
- * @param mixed $attributes Associative array or string of table row
- * attributes
- * @access public
- */
- function updateCellAttributes($row, $col, $attributes)
- {
- if ( isset($this->_structure[$row][$col])
- && $this->_structure[$row][$col] == '__SPANNED__'
- ) {
- return;
- }
- $attributes = $this->_parseAttributes($attributes);
- $err = $this->_adjustEnds($row, $col, 'updateCellAttributes', $attributes);
- if (PEAR::isError($err)) {
- return $err;
- }
- $this->_updateAttrArray($this->_structure[$row][$col]['attr'], $attributes);
- $this->_updateSpanGrid($row, $col);
- }
-
- /**
- * Returns the attributes for a given cell
- * @param int $row Row index
- * @param int $col Column index
- * @return array
- * @access public
- */
- function getCellAttributes($row, $col)
- {
- if ( isset($this->_structure[$row][$col])
- && $this->_structure[$row][$col] != '__SPANNED__'
- ) {
- return $this->_structure[$row][$col]['attr'];
- } elseif (!isset($this->_structure[$row][$col])) {
- return PEAR::raiseError('Invalid table cell reference[' .
- $row . '][' . $col . '] in HTML_Table::getCellAttributes');
- }
- return;
- }
-
- /**
- * Sets the cell contents for an existing cell
- *
- * If the given indices do not exist and autoGrow is true then the given
- * row and/or col is automatically added. If autoGrow is false then an
- * error is returned.
- * @param int $row Row index
- * @param int $col Column index
- * @param mixed $contents May contain html or any object with a
- * toHTML() method; if it is an array (with
- * strings and/or objects), $col will be used
- * as start offset and the array elements will
- * be set to this and the following columns
- * in $row
- * @param string $type (optional) Cell type either 'TH' or 'TD'
- * @access public
- * @throws PEAR_Error
- */
- function setCellContents($row, $col, $contents, $type = 'TD')
- {
- if (is_array($contents)) {
- foreach ($contents as $singleContent) {
- $ret = $this->_setSingleCellContents($row, $col, $singleContent,
- $type);
- if (PEAR::isError($ret)) {
- return $ret;
- }
- $col++;
- }
- } else {
- $ret = $this->_setSingleCellContents($row, $col, $contents, $type);
- if (PEAR::isError($ret)) {
- return $ret;
- }
- }
- }
-
- /**
- * Sets the cell contents for a single existing cell
- *
- * If the given indices do not exist and autoGrow is true then the given
- * row and/or col is automatically added. If autoGrow is false then an
- * error is returned.
- * @param int $row Row index
- * @param int $col Column index
- * @param mixed $contents May contain html or any object with a
- * toHTML() method; if it is an array (with
- * strings and/or objects), $col will be used
- * as start offset and the array elements will
- * be set to this and the following columns
- * in $row
- * @param string $type (optional) Cell type either 'TH' or 'TD'
- * @access private
- * @throws PEAR_Error
- */
- function _setSingleCellContents($row, $col, $contents, $type = 'TD')
- {
- if ( isset($this->_structure[$row][$col])
- && $this->_structure[$row][$col] == '__SPANNED__'
- ) {
- return;
- }
- $err = $this->_adjustEnds($row, $col, 'setCellContents');
- if (PEAR::isError($err)) {
- return $err;
- }
- $this->_structure[$row][$col]['contents'] = $contents;
- $this->_structure[$row][$col]['type'] = $type;
- }
-
- /**
- * Returns the cell contents for an existing cell
- * @param int $row Row index
- * @param int $col Column index
- * @access public
- * @return mixed
- */
- function getCellContents($row, $col)
- {
- if ( isset($this->_structure[$row][$col])
- && $this->_structure[$row][$col] == '__SPANNED__'
- ) {
- return;
- }
- if (!isset($this->_structure[$row][$col])) {
- return PEAR::raiseError('Invalid table cell reference[' .
- $row . '][' . $col . '] in HTML_Table::getCellContents');
- }
- return $this->_structure[$row][$col]['contents'];
- }
-
- /**
- * Sets the contents of a header cell
- * @param int $row
- * @param int $col
- * @param mixed $contents
- * @param mixed $attributes Associative array or string of table row
- * attributes
- * @access public
- */
- function setHeaderContents($row, $col, $contents, $attributes = null)
- {
- $this->setCellContents($row, $col, $contents, 'TH');
- if (!is_null($attributes)) {
- $this->updateCellAttributes($row, $col, $attributes);
- }
- }
-
- /**
- * Adds a table row and returns the row identifier
- * @param array $contents (optional) Must be a indexed array of valid
- * cell contents
- * @param mixed $attributes (optional) Associative array or string of
- * table row attributes. This can
- * also be an array of attributes,
- * in which case the attributes
- * will be repeated in a loop.
- * @param string $type (optional) Cell type either 'th' or 'td'
- * @param bool $inTR false if attributes are to be
- * applied in TD tags; true if
- * attributes are to be applied in
- * TR tag
- * @return int
- * @access public
- */
- function addRow($contents = null, $attributes = null, $type = 'td',
- $inTR = false)
- {
- if (isset($contents) && !is_array($contents)) {
- return PEAR::raiseError('First parameter to HTML_Table::addRow ' .
- 'must be an array');
- }
- if (is_null($contents)) {
- $contents = array();
- }
-
- $type = strtolower($type);
- $row = $this->_rows++;
- foreach ($contents as $col => $content) {
- if ($type == 'td') {
- $this->setCellContents($row, $col, $content);
- } elseif ($type == 'th') {
- $this->setHeaderContents($row, $col, $content);
- }
- }
- $this->setRowAttributes($row, $attributes, $inTR);
- return $row;
- }
-
- /**
- * Sets the row attributes for an existing row
- * @param int $row Row index
- * @param mixed $attributes Associative array or string of table
- * row attributes. This can also be an
- * array of attributes, in which case the
- * attributes will be repeated in a loop.
- * @param bool $inTR false if attributes are to be applied
- * in TD tags; true if attributes are to
- * be applied in TR tag
- * @access public
- * @throws PEAR_Error
- */
- function setRowAttributes($row, $attributes, $inTR = false)
- {
- if (!$inTR) {
- $multiAttr = $this->_isAttributesArray($attributes);
- for ($i = 0; $i < $this->_cols; $i++) {
- if ($multiAttr) {
- $this->setCellAttributes($row, $i,
- $attributes[$i - ((ceil(($i + 1) / count($attributes))) - 1) * count($attributes)]);
- } else {
- $this->setCellAttributes($row, $i, $attributes);
- }
- }
- } else {
- $attributes = $this->_parseAttributes($attributes);
- $err = $this->_adjustEnds($row, 0, 'setRowAttributes', $attributes);
- if (PEAR::isError($err)) {
- return $err;
- }
- $this->_structure[$row]['attr'] = $attributes;
- }
- }
-
- /**
- * Updates the row attributes for an existing row
- * @param int $row Row index
- * @param mixed $attributes Associative array or string of table
- * row attributes
- * @param bool $inTR false if attributes are to be applied
- * in TD tags; true if attributes are to
- * be applied in TR tag
- * @access public
- * @throws PEAR_Error
- */
- function updateRowAttributes($row, $attributes = null, $inTR = false)
- {
- if (!$inTR) {
- $multiAttr = $this->_isAttributesArray($attributes);
- for ($i = 0; $i < $this->_cols; $i++) {
- if ($multiAttr) {
- $this->updateCellAttributes($row, $i,
- $attributes[$i - ((ceil(($i + 1) / count($attributes))) - 1) * count($attributes)]);
- } else {
- $this->updateCellAttributes($row, $i, $attributes);
- }
- }
- } else {
- $attributes = $this->_parseAttributes($attributes);
- $err = $this->_adjustEnds($row, 0, 'updateRowAttributes', $attributes);
- if (PEAR::isError($err)) {
- return $err;
- }
- $this->_updateAttrArray($this->_structure[$row]['attr'], $attributes);
- }
- }
-
- /**
- * Returns the attributes for a given row as contained in the TR tag
- * @param int $row Row index
- * @return array
- * @access public
- */
- function getRowAttributes($row)
- {
- if (isset($this->_structure[$row]['attr'])) {
- return $this->_structure[$row]['attr'];
- }
- return;
- }
-
- /**
- * Alternates the row attributes starting at $start
- * @param int $start Row index of row in which alternating
- * begins
- * @param mixed $attributes1 Associative array or string of table
- * row attributes
- * @param mixed $attributes2 Associative array or string of table
- * row attributes
- * @param bool $inTR false if attributes are to be applied
- * in TD tags; true if attributes are to
- * be applied in TR tag
- * @param int $firstAttributes (optional) Which attributes should be
- * applied to the first row, 1 or 2.
- * @access public
- */
- function altRowAttributes($start, $attributes1, $attributes2, $inTR = false,
- $firstAttributes = 1)
- {
- for ($row = $start; $row < $this->_rows; $row++) {
- if (($row + $start + ($firstAttributes - 1)) % 2 == 0) {
- $attributes = $attributes1;
- } else {
- $attributes = $attributes2;
- }
- $this->updateRowAttributes($row, $attributes, $inTR);
- }
- }
-
- /**
- * Adds a table column and returns the column identifier
- * @param array $contents (optional) Must be a indexed array of valid
- * cell contents
- * @param mixed $attributes (optional) Associative array or string of
- * table row attributes
- * @param string $type (optional) Cell type either 'th' or 'td'
- * @return int
- * @access public
- */
- function addCol($contents = null, $attributes = null, $type = 'td')
- {
- if (isset($contents) && !is_array($contents)) {
- return PEAR::raiseError('First parameter to HTML_Table::addCol ' .
- 'must be an array');
- }
- if (is_null($contents)) {
- $contents = array();
- }
-
- $type = strtolower($type);
- $col = $this->_cols++;
- foreach ($contents as $row => $content) {
- if ($type == 'td') {
- $this->setCellContents($row, $col, $content);
- } elseif ($type == 'th') {
- $this->setHeaderContents($row, $col, $content);
- }
- }
- $this->setColAttributes($col, $attributes);
- return $col;
- }
-
- /**
- * Sets the column attributes for an existing column
- * @param int $col Column index
- * @param mixed $attributes (optional) Associative array or string
- * of table row attributes
- * @access public
- */
- function setColAttributes($col, $attributes = null)
- {
- $multiAttr = $this->_isAttributesArray($attributes);
- for ($i = 0; $i < $this->_rows; $i++) {
- if ($multiAttr) {
- $this->setCellAttributes($i, $col,
- $attributes[$i - ((ceil(($i + 1) / count($attributes))) - 1) * count($attributes)]);
- } else {
- $this->setCellAttributes($i, $col, $attributes);
- }
- }
- }
-
- /**
- * Updates the column attributes for an existing column
- * @param int $col Column index
- * @param mixed $attributes (optional) Associative array or string
- * of table row attributes
- * @access public
- */
- function updateColAttributes($col, $attributes = null)
- {
- $multiAttr = $this->_isAttributesArray($attributes);
- for ($i = 0; $i < $this->_rows; $i++) {
- if ($multiAttr) {
- $this->updateCellAttributes($i, $col,
- $attributes[$i - ((ceil(($i + 1) / count($attributes))) - 1) * count($attributes)]);
- } else {
- $this->updateCellAttributes($i, $col, $attributes);
- }
- }
- }
-
- /**
- * Sets the attributes for all cells
- * @param mixed $attributes (optional) Associative array or
- * string of table row attributes
- * @access public
- */
- function setAllAttributes($attributes = null)
- {
- for ($i = 0; $i < $this->_rows; $i++) {
- $this->setRowAttributes($i, $attributes);
- }
- }
-
- /**
- * Updates the attributes for all cells
- * @param mixed $attributes (optional) Associative array or
- * string of table row attributes
- * @access public
- */
- function updateAllAttributes($attributes = null)
- {
- for ($i = 0; $i < $this->_rows; $i++) {
- $this->updateRowAttributes($i, $attributes);
- }
- }
-
- /**
- * Returns the table rows as HTML
- * @access public
- * @return string
- */
- function toHtml($tabs = null, $tab = null)
- {
- $strHtml = '';
- if (is_null($tabs)) {
- $tabs = $this->_getTabs();
- }
- if (is_null($tab)) {
- $tab = $this->_getTab();
- }
- $lnEnd = $this->_getLineEnd();
- if ($this->_useTGroups) {
- $extraTab = $tab;
- } else {
- $extraTab = '';
- }
- if ($this->_cols > 0) {
- for ($i = 0 ; $i < $this->_rows ; $i++) {
- $attr = '';
- if (isset($this->_structure[$i]['attr'])) {
- $attr = $this->_getAttrString($this->_structure[$i]['attr']);
- }
- $strHtml .= $tabs .$tab . $extraTab . '<tr'.$attr.'>' . $lnEnd;
- for ($j = 0 ; $j < $this->_cols ; $j++) {
- $attr = '';
- $contents = '';
- $type = 'td';
- if (isset($this->_structure[$i][$j]) && $this->_structure[$i][$j] == '__SPANNED__') {
- continue;
- }
- if (isset($this->_structure[$i][$j]['type'])) {
- $type = (strtolower($this->_structure[$i][$j]['type']) == 'th' ? 'th' : 'td');
- }
- if (isset($this->_structure[$i][$j]['attr'])) {
- $attr = $this->_structure[$i][$j]['attr'];
- }
- if (isset($this->_structure[$i][$j]['contents'])) {
- $contents = $this->_structure[$i][$j]['contents'];
- }
- $strHtml .= $tabs . $tab . $tab . $extraTab . "<$type" . $this->_getAttrString($attr) . '>';
- if (is_object($contents)) {
- // changes indent and line end settings on nested tables
- if (is_subclass_of($contents, 'html_common')) {
- $contents->setTab($tab . $extraTab);
- $contents->setTabOffset($this->_tabOffset + 3);
- $contents->_nestLevel = $this->_nestLevel + 1;
- $contents->setLineEnd($this->_getLineEnd());
- }
- if (method_exists($contents, 'toHtml')) {
- $contents = $contents->toHtml();
- } elseif (method_exists($contents, 'toString')) {
- $contents = $contents->toString();
- }
- }
- if (is_array($contents)) {
- $contents = implode(', ', $contents);
- }
- if (isset($this->_autoFill) && $contents === '') {
- $contents = $this->_autoFill;
- }
- $strHtml .= $contents;
- $strHtml .= "</$type>" . $lnEnd;
- }
- $strHtml .= $tabs . $tab . $extraTab . '</tr>' . $lnEnd;
- }
- }
- return $strHtml;
- }
-
- /**
- * Checks if rows or columns are spanned
- * @param int $row Row index
- * @param int $col Column index
- * @access private
- */
- function _updateSpanGrid($row, $col)
- {
- if (isset($this->_structure[$row][$col]['attr']['colspan'])) {
- $colspan = $this->_structure[$row][$col]['attr']['colspan'];
- }
-
- if (isset($this->_structure[$row][$col]['attr']['rowspan'])) {
- $rowspan = $this->_structure[$row][$col]['attr']['rowspan'];
- }
-
- if (isset($colspan)) {
- for ($j = $col + 1; (($j < $this->_cols) && ($j <= ($col + $colspan - 1))); $j++) {
- $this->_structure[$row][$j] = '__SPANNED__';
- }
- }
-
- if (isset($rowspan)) {
- for ($i = $row + 1; (($i < $this->_rows) && ($i <= ($row + $rowspan - 1))); $i++) {
- $this->_structure[$i][$col] = '__SPANNED__';
- }
- }
-
- if (isset($colspan) && isset($rowspan)) {
- for ($i = $row + 1; (($i < $this->_rows) && ($i <= ($row + $rowspan - 1))); $i++) {
- for ($j = $col + 1; (($j <= $this->_cols) && ($j <= ($col + $colspan - 1))); $j++) {
- $this->_structure[$i][$j] = '__SPANNED__';
- }
- }
- }
- }
-
- /**
- * Adjusts ends (total number of rows and columns)
- * @param int $row Row index
- * @param int $col Column index
- * @param string $method Method name of caller
- * Used to populate PEAR_Error if thrown.
- * @param array $attributes Assoc array of attributes
- * Default is an empty array.
- * @access private
- * @throws PEAR_Error
- */
- function _adjustEnds($row, $col, $method, $attributes = array())
- {
- $colspan = isset($attributes['colspan']) ? $attributes['colspan'] : 1;
- $rowspan = isset($attributes['rowspan']) ? $attributes['rowspan'] : 1;
- if (($row + $rowspan - 1) >= $this->_rows) {
- if ($this->_autoGrow) {
- $this->_rows = $row + $rowspan;
- } else {
- return PEAR::raiseError('Invalid table row reference[' .
- $row . '] in HTML_Table::' . $method);
- }
- }
-
- if (($col + $colspan - 1) >= $this->_cols) {
- if ($this->_autoGrow) {
- $this->_cols = $col + $colspan;
- } else {
- return PEAR::raiseError('Invalid table column reference[' .
- $col . '] in HTML_Table::' . $method);
- }
- }
- }
-
- /**
- * Tells if the parameter is an array of attribute arrays/strings
- * @param mixed $attributes Variable to test
- * @access private
- * @return bool
- */
- function _isAttributesArray($attributes)
- {
- if (is_array($attributes) && isset($attributes[0])) {
- if (is_array($attributes[0]) || (is_string($attributes[0]) && count($attributes) > 1)) {
- return true;
- }
- }
- return false;
- }
-
-}
-?>
+++ /dev/null
-<?php
-
-/**
- * TagCloud.php
- *
- * TagCloud.php contains class HTML_TagCloud.
- *
- * PHP version 5
- *
- * LICENSE: This source file is subject to version 3.01 of the PHP license
- * that is available through the world-wide-web at the following URI:
- * http://www.php.net/license/3_01.txt. If you did not receive a copy of
- * the PHP License and are unable to obtain it through the web, please
- * send a note to license@php.net so we can mail you a copy immediately.
- *
- * @category HTML
- * @package HTML_TagCloud
- * @author Shoma Suzuki <shoma@catbot.net>
- * @author Bastian Onken <bastian.onken@gmx.net>
- * @copyright 2008 Bastian Onken
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version CVS: $Id: TagCloud.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_TagCloud
- * @since File available since Release 0.1.0
- */
-
-// {{{ class HTML_TagCloud
-
-/**
- * HTML Tag Cloud
- *
- * HTML_TagCloud enables you to generate a "tag cloud" in HTML.
- *
- * @category HTML
- * @package HTML_TagCloud
- * @author Shoma Suzuki <shoma@catbot.net>
- * @author Bastian Onken <bastian.onken@gmx.net>
- * @copyright 2008 Bastian Onken
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version Release: 0.2.2
- * @link http://pear.php.net/package/HTML_TagCloud
- * @link http://search.cpan.org/~lyokato/HTML-TagCloud-Extended-0.10/lib/HTML/TagCloud/Extended.pm
- * @since Class available since Release 0.1.0
- */
-class HTML_TagCloud
-{
- // {{{ properties
-
- /**
- * @var int
- * @access protected
- */
- protected $baseFontSize = 24;
-
- /**
- * @var int
- * @access protected
- */
- protected $fontSizeRange = 12;
-
- /**
- * @var string
- * @access protected
- */
- protected $cssClass = 'tagcloud';
-
- /**
- * @var string
- * @access protected
- * mm,cm,in,pt,pc,px,em
- */
- protected $sizeSuffix = 'px';
-
- /**
- * @var array
- * @access protected
- */
- protected $epocLevel = array(
- array(
- 'earliest' => array(
- 'link' => 'cccccc',
- 'visited' => 'cccccc',
- 'hover' => 'cccccc',
- 'active' => 'cccccc',
- ),
- ),
- array(
- 'earlier' => array(
- 'link' => '9999cc',
- 'visited' => '9999cc',
- 'hover' => '9999cc',
- 'active' => '9999cc',
- ),
- ),
- array(
- 'later' => array(
- 'link' => '9999ff',
- 'visited' => '9999ff',
- 'hover' => '9999ff',
- 'active' => '9999ff',
- ),
- ),
- array(
- 'latest' => array(
- 'link' => '0000ff',
- 'visited' => '0000ff',
- 'hover' => '0000ff',
- 'active' => '0000ff',
- ),
- ),
- );
-
- /**
- * @var array
- * @access private
- */
- private $_elements = array();
-
- /**
- * @var int
- * @access private
- */
- private $_max = 0;
-
- /**
- * @var int
- * @access private
- */
- private $_min = 0;
-
- /**
- * @var int
- * @access private
- */
- private $_maxEpoc;
-
- /**
- * @var int
- * @access private
- */
- private $_minEpoc;
-
- /**
- * @var float
- * @access private
- */
- private $_factor = 1;
-
- /**
- * @var float
- * @access private
- */
- private $_epocFactor = 1;
-
- /**
- * @var int
- * @access protected
- */
- private $_minFontSize;
-
- /**
- * @var int
- * @access protected
- */
- private $_maxFontSize;
-
- /**
- * @var string
- * @access public
- */
- private $_uid;
-
- // }}}
- // {{{ public function __construct()
-
- /**
- * Class constructor
- *
- * @param int $baseFontSize base font size of output tag (option)
- * @param int $fontSizeRange font size range
- * @param string $latestColor color of latest tag (usually dark)
- * @param string $earliestColor color of earliest tag (usually light)
- * @param int $thresholds number of timelines to set up
- *
- * @access public
- * @since Method available since Release 0.1.0
- */
- public function __construct($baseFontSize = null, $fontSizeRange = null,
- $latestColor = null, $earliestColor = null,
- $thresholds = 4)
- {
- // to be able to set up multiple tag clouds in one page we need to set
- // up a unique id that will prefix the css names later
- $this->_uid = 'tagcloud'.uniqid();
- // if $baseFontSize was given, set to value, otherwise keep the original
- // value of HTML_TagCloud::baseFontSize
- if (!is_null($baseFontSize)) {
- $this->baseFontSize = $baseFontSize;
- }
- // if $fontSizeRange was given, set to value, otherwise keep the
- // original value of HTML_TagCloud::fontSizeRange
- if (!is_null($fontSizeRange)) {
- $this->fontSizeRange = $fontSizeRange;
- }
- // make sure that we are in a positive font range
- if ($this->baseFontSize - $this->fontSizeRange > 0) {
- $this->_minFontSize = $this->baseFontSize - $this->fontSizeRange;
- } else {
- $this->_minFontSize = 0;
- }
- $this->_maxFontSize = $this->baseFontSize + $this->fontSizeRange;
- // override default epocLevel settings
- if (!is_null($latestColor) && !is_null($earliestColor) && $thresholds > 0) {
- $this->epocLevel = $this->_generateEpocLevel($latestColor,
- $earliestColor,
- $thresholds);
- }
- }
-
- // }}}
- // {{{ public function getUid()
-
- /**
- * returns the unique id of the tag cloud
- *
- * @return string unique id
- *
- * @access public
- * @since Method available since Release 0.2.0
- */
- public function getUid()
- {
- return $this->_uid;
- }
-
- // }}}
- // {{{ public function getElementCount()
-
- /**
- * returns the number of elements in the tag cloud
- *
- * @return integer number of elements in the tag cloud
- *
- * @access public
- * @since Method available since Release 0.2.2
- */
- public function getElementCount()
- {
- return count($this->_elements);
- }
-
- // }}}
- // {{{ public function addElement()
-
- /**
- * add a Tag Element to build Tag Cloud
- *
- * @param string $name tagname
- * @param string $url URL to which the tag leads to
- * @param int $count number of occurrences of this tag
- * @param int $timestamp unixtimestamp
- *
- * @return void
- *
- * @access public
- * @since Method available since Release 0.1.0
- */
- public function addElement($name, $url = '', $count = 0, $timestamp = null)
- {
- $i = count($this->_elements);
- $this->_elements[$i]['name'] = $name;
- $this->_elements[$i]['url'] = $url;
- $this->_elements[$i]['count'] = $count;
- $this->_elements[$i]['timestamp'] = $timestamp == null ? time() : $timestamp;
- }
-
- // }}}
- // {{{ public function addElements()
-
- /**
- * add a Tag Element to build Tag Cloud
- *
- * @param array $tags Associative array to $this->_elements
- *
- * @return void
- *
- * @access public
- * @since Method available since Release 0.1.0
- */
- public function addElements($tags)
- {
- $this->_elements = array_merge($this->_elements, $tags);
- }
-
- // }}}
- // {{{ public function clearElements()
-
- /**
- * clear Tag Elements
- *
- * @return void
- *
- * @access public
- * @since Method available since Release 0.1.0
- */
- public function clearElements()
- {
- $this->_elements = array();
- }
-
- // }}}
- // {{{ public function buildAll()
-
- /**
- * build HTML and CSS at once.
- *
- * @param array $param parameters that influence the HTML output
- *
- * @return string HTML and CSS
- *
- * @access public
- * @since Method available since Release 0.1.0
- */
- public function buildAll($param = array())
- {
- $html = '<style type="text/css">'."\n";
- $html .= $this->buildCSS().'</style>'."\n";
- $html .= $this->buildHTML($param);
- return $html;
- }
-
- // }}}
- // {{{ public function html_and_css()
-
- /**
- * Alias to buildAll. Compatibilities for Perl Module.
- *
- * @param array $param 'limit' => int limit of generation tag num.
- *
- * @return string HTML and CSS
- *
- * @access public
- * @see HTML_TagCloud::_buildAll
- * @since Method available since Release 0.1.0
- * @deprecated Method deprecated in Release 0.1.3
- * @legacy
- */
- public function html_and_css($param = array())
- {
- return $this->buildAll($param);
- }
-
- // }}}
- // {{{ public function buildHTML()
-
- /**
- * build HTML part
- *
- * @param array $param 'limit' => int limit of generation tag num.
- *
- * @return string HTML
- *
- * @access public
- * @since Method available since Release 0.1.0
- */
- public function buildHTML($param = array())
- {
- $htmltags = $this->_buidHTMLTags($param);
- return $this->_wrapDiv($htmltags);
- }
-
- // }}}
- // {{{ public function buildCSS()
-
- /**
- * build CSS part
- *
- * @return string base CSS
- *
- * @access public
- * @since Method available since Release 0.1.0
- */
- public function buildCSS()
- {
- $css = '';
- foreach ($this->epocLevel as $item) {
- foreach ($item as $epocName => $colors) {
- foreach ($colors as $attr => $color) {
- $css .= 'a.'.$this->_uid.'_'.$epocName.':'.$attr.' {'
- .'text-decoration: none; color: #'.$color.';}'."\n";
- }
- }
- }
- return $css;
- }
-
- // }}}
- // {{{ private function _buidHTMLTags()
-
- /**
- * calc Tag level and create whole HTML of each Tags
- *
- * @param array $param limit of Tag Number
- *
- * @return string HTML
- *
- * @access private
- * @since Method available since Release 0.1.0
- */
- private function _buidHTMLTags($param)
- {
- // get total number of tags
- $total = count($this->_elements);
- if ($total == 0) {
- // no tag elements, return with "not enough data"
- return '<p>not enough data</p>'."\n";
- } elseif ($total == 1) {
- // only 1 element was set, no need to process sizes or colors, so
- // just create html with standard setup and return
- $tag = $this->_elements[0];
- $type = $this->_uid.'_'
- .key($this->epocLevel[count($this->epocLevel) - 1]);
- return $this->createHTMLTag($tag, $type, $this->baseFontSize);
- }
- // okay, there are more elements, let's calculate their environment
- // at first, check if there is a limit of returned elements set up
- $limit = array_key_exists('limit', $param) ? $param['limit'] : 0;
- // sort elements, consider limit if available ("0" will disable limit)
- $this->_sortTags($limit);
- // get maximum and minimum count values
- // (values will be stored in $this->_min and $this->_max
- $this->_calcMumCount();
- // get maximum and minimum timestamp values
- // (values will be stored in $this->_minEpoc and $this->_maxEpoc
- $this->_calcMumEpoc();
- // get font size delta
- $range = $this->_maxFontSize - $this->_minFontSize;
- // calculate the factor for building the font size deltas
- if ($this->_max != $this->_min) {
- $this->_factor = $range / (sqrt($this->_max) - sqrt($this->_min));
- } else {
- $this->_factor = 1;
- }
- // calculate the factor for building the color deltas
- if ($this->_maxEpoc != $this->_minEpoc) {
- $this->_epocFactor = count($this->epocLevel) /
- (sqrt($this->_maxEpoc) - sqrt($this->_minEpoc));
- } else {
- $this->_epocFactor = 1;
- }
- // build html
- $rtn = array();
- foreach ($this->_elements as $tag) {
- $count = isset($tag['count']) ? $tag['count'] : 0;
- $countLv = $this->_getCountLevel($count);
- if (!isset($tag['timestamp']) || empty($tag['timestamp'])) {
- $epocLv = count($this->epocLevel) - 1;
- } else {
- $epocLv = $this->_getEpocLevel($tag['timestamp']);
- }
- $colorType = $this->epocLevel[$epocLv];
- $type = $this->_uid.'_'.key($colorType);
- $fontSize = $this->_minFontSize + $countLv;
- $rtn[] = $this->createHTMLTag($tag, $type, $fontSize);
- }
- return implode('', $rtn);
- }
-
- // }}}
- // {{{ protected function _createHTMLTag()
-
- /**
- * create a Element of HTML part
- *
- * deprecated due to wrong function naming: one leading underscore must only
- * be used in private context.
- *
- * @param array $tag tagname
- * @param string $type css class of time line param
- * @param float $fontSize size of the font for this tag
- *
- * @return string a Element of Tag HTML
- *
- * @access protected
- * @see HTML_TagCloud::createHTMLTag()
- * @since Method available since Release 0.1.0
- * @deprecated Method deprecated in Release 0.1.3
- * @legacy
- */
- protected function _createHTMLTag($tag, $type, $fontSize)
- {
- return $this->createHTMLTag($tag, $type, $fontSize);
- }
-
- // }}}
- // {{{ protected function createHTMLTag()
-
- /**
- * create a Element of HTML part
- *
- * @param array $tag tagname
- * @param string $type css class of time line param
- * @param float $fontSize size of the font for this tag
- *
- * @return string a Element of Tag HTML
- *
- * @access protected
- * @since Method available since Release 0.1.3
- */
- protected function createHTMLTag($tag, $type, $fontSize)
- {
- return '<a href="'.(!empty($tag['url']) ? $tag['url'] : '').'"'
- .' style="font-size:'.$fontSize.$this->sizeSuffix.';"'
- .' class="tagcloudElement '.$type.'">'
- .htmlspecialchars($tag['name'])
- .'</a> '."\n";
- }
-
- // }}}
- // {{{ protected function generateEpocLevel()
-
- /**
- * build the epocLevel Array automatically by calculating an array of colors
- *
- * @param string $latestColor color of latest epocLevel (usually dark)
- * @param string $earliestColor color of earliest epocLevel (usually light)
- * @param int $thresholds number of levels to generate colors for
- *
- * @return array epocLevel
- *
- * @access private
- * @since Method available since Release 0.2.0
- */
- private function _generateEpocLevel($latestColor, $earliestColor, $thresholds)
- {
- include_once 'Image/Color.php';
- $imageColor = new Image_Color();
- $imageColor->setWebSafe(false);
- $imageColor->setColors('000090', 'FFFFFF');
- $epocLevel = array();
- foreach ($imageColor->getRange($thresholds) as $key => $color) {
- $epocLevel[]['epocLevel'.$key] = array(
- 'link' => $color,
- 'visited' => $color
- );
- }
- return array_reverse($epocLevel);
- }
-
- // }}}
- // {{{ private function _sortTags()
-
- /**
- * sort tags by name
- *
- * @param int $limit limit element number of create TagCloud
- *
- * @return array
- *
- * @access private
- * @since Method available since Release 0.1.0
- */
- private function _sortTags($limit = 0)
- {
- if ($limit != 0) {
- usort($this->_elements, array($this, "_cmpElementsCountTimestamp"));
- $this->_elements = array_splice($this->_elements, 0, $limit);
- usort($this->_elements, array($this, "_cmpElementsName"));
- } else {
- usort($this->_elements, array($this, "_cmpElementsName"));
- }
- }
-
- // }}}
- // {{{ private function _cmpElementsName()
-
- /**
- * callback for usort(), considers string value "name" of a tag element
- *
- * @param array $a first element to compare
- * @param array $b second element to compare
- *
- * @return int (bool)
- *
- * @access public
- * @since Method available since Release 0.1.0
- */
- private function _cmpElementsName($a, $b)
- {
- if ($a['name'] == $b['name']) {
- return 0;
- }
- return ($a['name'] < $b['name']) ? -1 : 1;
- }
-
- // }}}
- // {{{ private function _cmpElementsCountTimestamp($a, $b)
-
- /**
- * callback for usort(), considers count and if count values are equal it
- * considers timestamp as well.
- *
- * @param array $a first element to compare
- * @param array $b second element to compare
- *
- * @return int (bool)
- *
- * @access public
- * @since Method available since Release 0.2.1
- */
- private function _cmpElementsCountTimestamp($a, $b)
- {
- if ($a['count'] == $b['count']) {
- if ($a['timestamp'] == $b['timestamp']) {
- return 0;
- } else {
- return ($a['timestamp'] > $b['timestamp']) ? -1 : 1;
- }
- }
- return ($a['count'] > $b['count']) ? -1 : 1;
- }
-
- // }}}
- // {{{ private function _calcMumCount()
-
- /**
- * calc max and min tag count values
- *
- * @return void
- *
- * @access private
- * @since Method available since Release 0.1.0
- */
- private function _calcMumCount()
- {
- $array = array();
- foreach ($this->_elements as $item) {
- if (isset($item['count'])) {
- $array[] = (int)$item['count'];
- } else {
- $array[] = 0;
- }
- }
- $this->_min = min($array);
- $this->_max = max($array);
- }
-
- // }}}
- // {{{ private function _calcMumEpoc()
-
- /**
- * calc max and min timestamp
- *
- * @return void
- *
- * @access private
- * @since Method available since Release 0.1.0
- */
- private function _calcMumEpoc()
- {
- $array = array();
- foreach ($this->_elements as $item) {
- if (isset($item['timestamp'])) {
- $array[] = (int)$item['timestamp'];
- } else {
- $array[] = time();
- }
- }
- $this->_minEpoc = min($array);
- $this->_maxEpoc = max($array);
- }
-
- // }}}
- // {{{ private function _getCountLevel()
-
- /**
- * calc Tag Level of size
- *
- * @param int $count number of occurrences of tag to analyze
- *
- * @return int level
- *
- * @access private
- * @since Method available since Release 0.1.0
- */
- private function _getCountLevel($count = 0)
- {
- return (int)(sqrt($count) - sqrt($this->_min) ) * $this->_factor;
- }
-
- // }}}
- // {{{ private function _getEpocLevel()
-
- /**
- * calc timeline level of Tag
- *
- * @param int $timestamp timestamp of tag to analyze
- *
- * @return int level of timeline
- *
- * @access private
- * @since Method available since Release 0.1.0
- */
- private function _getEpocLevel($timestamp = 0)
- {
- return (int)(sqrt($timestamp) - sqrt($this->_minEpoc)) * $this->_epocFactor;
- }
-
- // }}}
- // {{{ private function _wrapDiv()
-
- /**
- * wrap div tag
- *
- * @param string $html HTML to wrap into a div element
- *
- * @return string HTML wrapped into a div set up with $this::cssClass
- *
- * @access private
- * @since Method available since Release 0.1.0
- */
- private function _wrapDiv($html)
- {
- return $html == '' ? '' : '<div class="'.$this->cssClass.' '.$this->_uid.'">'
- ."\n".$html.'</div>'."\n";
- }
-
- // }}}
-}
-
-// }}}
-
-/*
- * vim: set expandtab tabstop=4 shiftwidth=4
- * vim600: foldmethod=marker
- * Local variables:
- * tab-width: 4
- * c-basic-offset: 4
- * End:
- */
-?>
+++ /dev/null
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Alan Knowles <alan@akbkhome.com>
-// | Original Author: Wolfram Kriesing <wolfram@kriesing.de> |
-// +----------------------------------------------------------------------+
-//
-
-/**
-* @package HTML_Template_Flexy
-*/
-// prevent disaster when used with xdebug!
-@ini_set('xdebug.max_nesting_level', 1000);
-
-/*
-* Global variable - used to store active options when compiling a template.
-*/
-$GLOBALS['_HTML_TEMPLATE_FLEXY'] = array();
-
-// ERRORS:
-
-/**
- * Workaround for stupid depreciation of is_a...
- */
-function HTML_Template_Flexy_is_a($obj, $class) // which f***wit depreciated is_a....
-{
- if (version_compare(phpversion(),"5","<")) {
- return is_a($obj, $class);
-
- }
- $test=false;
- @eval("\$test = \$obj instanceof ".$class.";");
- return $test;
-
-}
-
-
-
-define('HTML_TEMPLATE_FLEXY_ERROR_SYNTAX',-1); // syntax error in template.
-define('HTML_TEMPLATE_FLEXY_ERROR_INVALIDARGS',-2); // bad arguments to methods.
-define('HTML_TEMPLATE_FLEXY_ERROR_FILE',-2); // file access problem
-
-define('HTML_TEMPLATE_FLEXY_ERROR_RETURN',1); // RETURN ERRORS
-define('HTML_TEMPLATE_FLEXY_ERROR_DIE',8); // FATAL DEATH
-/**
-* A Flexible Template engine - based on simpletemplate
-*
-* @abstract Long Description
-* Have a look at the package description for details.
-*
-* usage:
-* $template = new HTML_Template_Flexy($options);
-* $template->compiler('/name/of/template.html');
-* $data =new StdClass
-* $data->text = 'xxxx';
-* $template->outputObject($data,$elements)
-*
-* Notes:
-* $options can be blank if so, it is read from
-* PEAR::getStaticProperty('HTML_Template_Flexy','options');
-*
-* the first argument to outputObject is an object (which could even be an
-* associateve array cast to an object) - I normally send it the controller class.
-* the seconde argument '$elements' is an array of HTML_Template_Flexy_Elements
-* eg. array('name'=> new HTML_Template_Flexy_Element('',array('value'=>'fred blogs'));
-*
-*
-*
-*
-* @version $Id: Flexy.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-*/
-
-
-
-class HTML_Template_Flexy
-{
-
- /*
- * @var array $options the options for initializing the template class
- */
- var $options = array(
- 'compileDir' => '', // where do you want to write to.. (defaults to session.save_path)
- 'templateDir' => '', // where are your templates
-
- // where the template comes from. ------------------------------------------
- 'multiSource' => false, // Allow same template to exist in multiple places
- // So you can have user themes....
- 'templateDirOrder' => '', // set to 'reverse' to assume that first template
-
-
- 'debug' => false, // prints a few messages
-
-
- // compiling conditions ------------------------------------------
- 'compiler' => 'Flexy', // which compiler to use. (Flexy,Regex, Raw,Xipe)
- 'forceCompile' => false, // only suggested for debugging
-
- // regex Compiler ------------------------------------------
- 'filters' => array(), // used by regex compiler.
-
- // standard Compiler ------------------------------------------
- 'nonHTML' => false, // dont parse HTML tags (eg. email templates)
- 'allowPHP' => false, // allow PHP in template (use true=allow, 'delete' = remove it.)
-
- 'flexyIgnore' => 0, // turn on/off the tag to element code
- 'numberFormat' => ",2,'.',','", // default number format {xxx:n} format = eg. 1,200.00
-
- 'url_rewrite' => '', // url rewriting ability:
- // eg. "images/:test1/images/,js/:test1/js"
- // changes href="images/xxx" to href="test1/images/xxx"
- // and src="js/xxx.js" to src="test1/js/xxx.js"
-
- 'compileToString' => false, // should the compiler return a string
- // rather than writing to a file.
- 'privates' => false, // allow access to _variables (eg. suido privates
- 'globals' => false, // allow access to _GET/_POST/_REQUEST/GLOBALS/_COOKIES/_SESSION
-
- 'globalfunctions' => false, // allow GLOBALS.date(#d/m/Y#) to have access to all PHP's methods
- // warning dont use unless you trust the template authors
- // exec() becomes exposed.
-
- // get text/transalation suppport ------------------------------------------
- // (flexy compiler only)
- 'locale' => 'en', // works with gettext or File_Gettext
- 'textdomain' => '', // for gettext emulation with File_Gettext
- // eg. 'messages' (or you can use the template name.
- 'textdomainDir' => '', // eg. /var/www/site.com/locale
- // so the french po file is:
- // /var/www/site.com/local/fr/LC_MESSAGE/{textdomain}.po
-
- 'Translation2' => false, // to make Translation2 a provider.
- // rather than gettext.
- // set to:
- // 'Translation2' => array(
- // 'driver' => 'dataobjectsimple',
- // 'options' => array()
- // );
- // or the slower way..
- // = as it requires loading the code..
- //
- // 'Translation2' => new Translation2('dataobjectsimple','')
-
-
- 'charset' => 'ISO-8859-1', // charset used with htmlspecialchars to render data.
- // experimental
-
- // output options ------------------------------------------
- 'strict' => false, // All elements in the template must be defined -
- // makes php E_NOTICE warnings appear when outputing template.
-
- 'fatalError' => HTML_TEMPLATE_FLEXY_ERROR_DIE, // default behavior is to die on errors in template.
-
- 'plugins' => array(), // load classes to be made available via the plugin method
- // eg. = array('Savant') - loads the Savant methods.
- // = array('MyClass_Plugins' => 'MyClass/Plugins.php')
- // Class, and where to include it from..
- );
- /**
- * The compiled template filename (Full path)
- *
- * @var string
- * @access public
- */
- var $compiledTemplate;
- /**
- * The source template filename (Full path)
- *
- * @var string
- * @access public
- */
-
-
- var $currentTemplate;
-
- /**
- * The getTextStrings Filename
- *
- * @var string
- * @access public
- */
- var $getTextStringsFile;
- /**
- * The serialized elements array file.
- *
- * @var string
- * @access public
- */
- var $elementsFile;
-
-
- /**
- * Array of HTML_elements which is displayed on the template
- *
- * Technically it's private (eg. only the template uses it..)
- *
- *
- * @var array of HTML_Template_Flexy_Elements
- * @access private
- */
- var $elements = array();
- /**
- * Constructor
- *
- * Initializes the Template engine, for each instance, accepts options or
- * reads from PEAR::getStaticProperty('HTML_Template_Flexy','options');
- *
- * @access public
- * @param array $options (Optional)
- */
-
- function HTML_Template_Flexy( $options=array() )
- {
-
- $baseoptions = array();
- if (class_exists('PEAR')) {
- $baseoptions = &PEAR::getStaticProperty('HTML_Template_Flexy','options');
- }
- if ($baseoptions ) {
- foreach( $baseoptions as $key=>$aOption) {
- $this->options[$key] = $aOption;
- }
- }
-
- foreach( $options as $key=>$aOption) {
- $this->options[$key] = $aOption;
- }
-
- $filters = $this->options['filters'];
- if (is_string($filters)) {
- $this->options['filters']= explode(',',$filters);
- }
-
- if (is_string($this->options['templateDir'])) {
- $this->options['templateDir'] = explode(PATH_SEPARATOR,$this->options['templateDir'] );
- }
-
-
- }
-
-
-
-
-
- /**
- * compile the template
- *
- * @access public
- * @version 01/12/03
- * @author Wolfram Kriesing <wolfram@kriesing.de>
- * @param string $file relative to the 'templateDir' which you set when calling the constructor
- * @return boolean true on success. (or string, if compileToString) PEAR_Error on failure..
- */
- function compile( $file )
- {
- if (!$file) {
- return $this->raiseError('HTML_Template_Flexy::compile no file selected',
- HTML_TEMPLATE_FLEXY_ERROR_INVALIDARGS,HTML_TEMPLATE_FLEXY_ERROR_DIE);
- }
-
- if (!@$this->options['locale']) {
- $this->options['locale']='en';
- }
-
-
- //Remove the slash if there is one in front, just to be safe.
- $file = ltrim($file,DIRECTORY_SEPARATOR);
-
-
- if (strpos($file,'#')) {
- list($file,$this->options['output.block']) = explode('#', $file);
- }
-
- $parts = array();
- $tmplDirUsed = false;
-
- // PART A mulitlanguage support: ( part B is gettext support in the engine..)
- // - user created language version of template.
- // - compile('abcdef.html') will check for compile('abcdef.en.html')
- // (eg. when locale=en)
-
- $this->currentTemplate = false;
-
- if (preg_match('/(.*)(\.[a-z]+)$/i',$file,$parts)) {
- $newfile = $parts[1].'.'.$this->options['locale'] .$parts[2];
- foreach ($this->options['templateDir'] as $tmplDir) {
- if (@!file_exists($tmplDir . DIRECTORY_SEPARATOR .$newfile)) {
- continue;
- }
- $file = $newfile;
- $this->currentTemplate = $tmplDir . DIRECTORY_SEPARATOR .$newfile;
- $tmplDirUsed = $tmplDir;
- }
- }
-
- // look in all the posible locations for the template directory..
- if ($this->currentTemplate === false) {
- $dirs = array_unique($this->options['templateDir']);
- if ($this->options['templateDirOrder'] == 'reverse') {
- $dirs = array_reverse($dirs);
- }
- foreach ($dirs as $tmplDir) {
- if (!@file_exists($tmplDir . DIRECTORY_SEPARATOR . $file)) {
- continue;
- }
-
-
- if (!$this->options['multiSource'] && ($this->currentTemplate !== false)) {
- return $this->raiseError("You have more than one template Named {$file} in your paths, found in both".
- "<BR>{$this->currentTemplate }<BR>{$tmplDir}" . DIRECTORY_SEPARATOR . $file,
- HTML_TEMPLATE_FLEXY_ERROR_INVALIDARGS , HTML_TEMPLATE_FLEXY_ERROR_DIE);
-
- }
-
- $this->currentTemplate = $tmplDir . DIRECTORY_SEPARATOR . $file;
- $tmplDirUsed = $tmplDir;
- }
- }
- if ($this->currentTemplate === false) {
- // check if the compile dir has been created
- return $this->raiseError("Could not find Template {$file} in any of the directories<br>" .
- implode("<BR>",$this->options['templateDir']) ,
- HTML_TEMPLATE_FLEXY_ERROR_INVALIDARGS, HTML_TEMPLATE_FLEXY_ERROR_DIE);
- }
-
-
- // Savant compatible compiler
-
- if ( is_string( $this->options['compiler'] ) && ($this->options['compiler'] == 'Raw')) {
- $this->compiledTemplate = $this->currentTemplate;
- $this->debug("Using Raw Compiler");
- return true;
- }
-
-
-
-
- // now for the compile target
-
- //If you are working with mulitple source folders and $options['multiSource'] is set
- //the template folder will be:
- // compiled_tempaltes/{templatedir_basename}_{md5_of_dir}/
-
-
- $compileSuffix = ((count($this->options['templateDir']) > 1) && $this->options['multiSource']) ?
- DIRECTORY_SEPARATOR .basename($tmplDirUsed) . '_' .md5($tmplDirUsed) : '';
-
-
- $compileDest = @$this->options['compileDir'];
-
- $isTmp = false;
- // Use a default compile directory if one has not been set.
- if (!@$compileDest) {
- // Use session.save_path + 'compiled_templates_' + md5(of sourcedir)
- $compileDest = ini_get('session.save_path') . DIRECTORY_SEPARATOR . 'flexy_compiled_templates';
- if (!file_exists($compileDest)) {
- require_once 'System.php';
- System::mkdir(array('-p',$compileDest));
- }
- $isTmp = true;
-
- }
-
-
-
- // we generally just keep the directory structure as the application uses it,
- // so we dont get into conflict with names
- // if we have multi sources we do md5 the basedir..
-
-
- $base = $compileDest . $compileSuffix . DIRECTORY_SEPARATOR .$file;
- $fullFile = $this->compiledTemplate = $base .'.'.$this->options['locale'].'.php';
- $this->getTextStringsFile = $base .'.gettext.serial';
- $this->elementsFile = $base .'.elements.serial';
- if (isset($this->options['output.block'])) {
- $this->compiledTemplate .= '#'.$this->options['output.block'];
- }
-
- $recompile = false;
-
- $isuptodate = file_exists($this->compiledTemplate) ?
- (filemtime($this->currentTemplate) == filemtime( $this->compiledTemplate)) : 0;
-
- if( @$this->options['forceCompile'] || !$isuptodate ) {
- $recompile = true;
- } else {
- $this->debug("File looks like it is uptodate.");
- return true;
- }
-
-
-
-
- if( !@is_dir($compileDest) || !is_writeable($compileDest)) {
- require_once 'System.php';
-
- System::mkdir(array('-p',$compileDest));
- }
- if( !@is_dir($compileDest) || !is_writeable($compileDest)) {
- return $this->raiseError( "can not write to 'compileDir', which is <b>'$compileDest'</b><br>".
- "Please give write and enter-rights to it",
- HTML_TEMPLATE_FLEXY_ERROR_FILE, HTML_TEMPLATE_FLEXY_ERROR_DIE);
- }
-
- if (!file_exists(dirname($this->compiledTemplate))) {
- require_once 'System.php';
- System::mkdir(array('-p','-m', 0770, dirname($this->compiledTemplate)));
- }
-
- // Compile the template in $file.
-
- require_once 'HTML/Template/Flexy/Compiler.php';
- $compiler = HTML_Template_Flexy_Compiler::factory($this->options);
- $ret = $compiler->compile($this);
- if (HTML_Template_Flexy_is_a($ret,'PEAR_Error')) {
- return $this->raiseError('HTML_Template_Flexy fatal error:' .$ret->message,
- $ret->code, HTML_TEMPLATE_FLEXY_ERROR_DIE);
- }
- return $ret;
-
- //return $this->$method();
-
- }
-
- /**
- * compiles all templates
- * Used for offline batch compilation (eg. if your server doesn't have write access to the filesystem).
- *
- * @access public
- * @author Alan Knowles <alan@akbkhome.com>
- *
- */
- function compileAll($dir = '',$regex='/.html$/')
- {
-
- require_once 'HTML/Template/Flexy/Compiler.php';
- $c = new HTML_Template_Flexy_Compiler;
- $c->compileAll($this,$dir,$regex);
- }
-
- /**
- * Outputs an object as $t
- *
- * for example the using simpletags the object's variable $t->test
- * would map to {test}
- *
- * @version 01/12/14
- * @access public
- * @author Alan Knowles
- * @param object to output
- * @param array HTML_Template_Flexy_Elements (or any object that implements toHtml())
- * @return none
- */
-
-
- function outputObject(&$t,$elements=array())
- {
- if (!is_array($elements)) {
- return $this->raiseError(
- 'second Argument to HTML_Template_Flexy::outputObject() was an '.gettype($elements) . ', not an array',
- HTML_TEMPLATE_FLEXY_ERROR_INVALIDARGS ,HTML_TEMPLATE_FLEXY_ERROR_DIE);
- }
- if (@$this->options['debug']) {
- echo "output $this->compiledTemplate<BR>";
- }
-
- // this may disappear later it's a Backwards Compatibility fudge to try
- // and deal with the first stupid design decision to not use a second argument
- // to the method.
-
- if (count($this->elements) && !count($elements)) {
- $elements = $this->elements;
- }
- // end depreciated code
-
-
- $this->elements = $this->getElements();
-
- // Overlay values from $elements to $this->elements (which is created from the template)
- // Remove keys with no corresponding value.
- foreach($elements as $k=>$v) {
- // Remove key-value pair from $this->elements if hasn't a value in $elements.
- if (!$v) {
- unset($this->elements[$k]);
- }
- // Add key-value pair to $this->$elements if it's not there already.
- if (!isset($this->elements[$k])) {
- $this->elements[$k] = $v;
- continue;
- }
- // Call the clever element merger - that understands form values and
- // how to display them...
- $this->elements[$k] = $this->mergeElement($this->elements[$k] ,$v);
- }
- //echo '<PRE>'; print_r(array($elements,$this->elements));
-
-
- // we use PHP's error handler to hide errors in the template.
- // use $options['strict'] - if you want to force declaration of
- // all variables in the template
-
-
- $_error_reporting = false;
- if (!$this->options['strict']) {
- $_error_reporting = error_reporting(E_ALL ^ E_NOTICE);
- }
- if (!is_readable($this->compiledTemplate)) {
- return $this->raiseError( "Could not open the template: <b>'{$this->compiledTemplate}'</b><BR>".
- "Please check the file permissions on the directory and file ",
- HTML_TEMPLATE_FLEXY_ERROR_FILE, HTML_TEMPLATE_FLEXY_ERROR_DIE);
- }
-
- // are we using the assign api!
-
- if (isset($this->assign)) {
- if (!$t) {
- $t = (object) $this->assign->variables;
- }
- extract($this->assign->variables);
- foreach(array_keys($this->assign->references) as $_k) {
- $$_k = &$this->assign->references[$_k];
- }
- }
- // used by Flexy Elements etc..
- $GLOBALS['_HTML_TEMPLATE_FLEXY']['options'] = $this->options;
-
- include($this->compiledTemplate);
-
- // Return the error handler to its previous state.
-
- if ($_error_reporting !== false) {
- error_reporting($_error_reporting);
- }
- }
- /**
- * Outputs an object as $t, buffers the result and returns it.
- *
- * See outputObject($t) for more details.
- *
- * @version 01/12/14
- * @access public
- * @author Alan Knowles
- * @param object object to output as $t
- * @return string - result
- */
- function bufferedOutputObject(&$t,$elements=array())
- {
- ob_start();
- $this->outputObject($t,$elements);
- $data = ob_get_contents();
- ob_end_clean();
- return $data;
- }
- /**
- * static version which does new, compile and output all in one go.
- *
- * See outputObject($t) for more details.
- *
- * @version 01/12/14
- * @access public
- * @author Alan Knowles
- * @param object object to output as $t
- * @param filename of template
- * @return string - result
- */
- function &staticQuickTemplate($file,&$t)
- {
- $template = new HTML_Template_Flexy;
- $template->compile($file);
- $template->outputObject($t);
- }
-
- /**
- * if debugging is on, print the debug info to the screen
- *
- * @access public
- * @author Alan Knowles <alan@akbkhome.com>
- * @param string $string output to display
- * @return none
- */
- function debug($string)
- {
-
-
- if (HTML_Template_Flexy_is_a($this,'HTML_Template_Flexy')) {
- if (!$this->options['debug']) {
- return;
- }
- } else if (empty($GLOBALS['_HTML_TEMPLATE_FLEXY']['debug'])) {
- return;
- }
-
- echo "<PRE><B>FLEXY DEBUG:</B> $string</PRE>";
-
- }
-
-
-
-
- /**
- * A general Utility method that merges HTML_Template_Flexy_Elements
- * Static method - no native debug avaiable..
- *
- * @param HTML_Template_Flexy_Element $original (eg. from getElements())
- * @param HTML_Template_Flexy_Element $new (with data to replace/merge)
- * @return HTML_Template_Flexy_Element the combined/merged data.
- * @static
- * @access public
- */
-
- function mergeElement($original,$new)
- {
-
- // no original - return new
- if (!$original) {
- return $new;
- }
- // no new - return original
- if (!$new) {
- return $original;
- }
- // If the properties of $original differ from those of $new and
- // they are set on $new, set them to $new's. Otherwise leave them
- // as they are.
-
- if ($new->tag && ($new->tag != $original->tag)) {
- $original->tag = $new->tag;
- }
-
- if ($new->override !== false) {
- $original->override = $new->override;
- }
-
- if (count($new->children)) {
- //echo "<PRE> COPY CHILDREN"; print_r($from->children);
- $original->children = $new->children;
- }
-
- if (is_array($new->attributes)) {
-
- foreach ($new->attributes as $key => $value) {
- $original->attributes[$key] = $value;
- }
- }
- // originals never have prefixes or suffixes..
- $original->prefix = $new->prefix;
- $original->suffix = $new->suffix;
-
- if ($new->value !== null) {
- $original->setValue($new->value);
- }
-
- return $original;
-
- }
-
-
- /**
- * Get an array of elements from the template
- *
- * All <form> elements (eg. <input><textarea) etc.) and anything marked as
- * dynamic (eg. flexy:dynamic="yes") are converted in to elements
- * (simliar to XML_Tree_Node)
- * you can use this to build the default $elements array that is used by
- * outputObject() - or just create them and they will be overlayed when you
- * run outputObject()
- *
- *
- * @return array of HTML_Template_Flexy_Element sDescription
- * @access public
- */
-
- function getElements() {
-
- if ($this->elementsFile && file_exists($this->elementsFile)) {
- require_once 'HTML/Template/Flexy/Element.php';
- return unserialize(file_get_contents($this->elementsFile));
- }
- return array();
- }
-
-
- /**
- * Lazy loading of PEAR, and the error handler..
- * This should load HTML_Template_Flexy_Error really..
- *
- * @param string message
- * @param int error type.
- * @param int an equivalant to pear error return|die etc.
- *
- * @return object pear error.
- * @access public
- */
-
-
- function raiseError($message, $type = null, $fatal = HTML_TEMPLATE_FLEXY_ERROR_RETURN )
- {
- HTML_Template_Flexy::debug("<B>HTML_Template_Flexy::raiseError</B>$message");
- require_once 'PEAR.php';
- if (HTML_Template_Flexy_is_a($this,'HTML_Template_Flexy') && ($fatal == HTML_TEMPLATE_FLEXY_ERROR_DIE)) {
- // rewrite DIE!
- return PEAR::raiseError($message, $type, $this->options['fatalError']);
- }
- if (isset($GLOBALS['_HTML_TEMPLATE_FLEXY']['fatalError']) && ($fatal == HTML_TEMPLATE_FLEXY_ERROR_DIE)) {
-
- return PEAR::raiseError($message, $type,$GLOBALS['_HTML_TEMPLATE_FLEXY']['fatalError']);
- }
- return PEAR::raiseError($message, $type, $fatal);
- }
-
-
- /**
- *
- * Assign API -
- *
- * read the docs on HTML_Template_Flexy_Assign::assign()
- *
- * @param varargs ....
- *
- *
- * @return mixed PEAR_Error or true?
- * @access public
- * @see HTML_Template_Flexy_Assign::assign()
- * @status alpha
- */
-
- function setData() {
- require_once 'HTML/Template/Flexy/Assign.php';
- // load assigner..
- if (!isset($this->assign)) {
- $this->assign = new HTML_Template_Flexy_Assign;
- }
- return $this->assign->assign(func_get_args());
- }
- /**
- *
- * Assign API - by Reference
- *
- * read the docs on HTML_Template_Flexy_Assign::assign()
- *
- * @param key string
- * @param value mixed
- *
- * @return mixed PEAR_Error or true?
- * @access public
- * @see HTML_Template_Flexy_Assign::assign()
- * @status alpha
- */
-
- function setDataByRef($k,&$v) {
- require_once 'HTML/Template/Flexy/Assign.php';
- // load assigner..
- if (!isset($this->assign)) {
- $this->assign = new HTML_Template_Flexy_Assign;
- }
- $this->assign->assignRef($k,$v);
- }
- /**
- *
- * Plugin (used by templates as $this->plugin(...) or {this.plugin(#...#,#....#)}
- *
- * read the docs on HTML_Template_Flexy_Plugin()
- *
- * @param varargs ....
- *
- * @return mixed PEAR_Error or true?
- * @access public
- * @see HTML_Template_Flexy_Plugin
- * @status alpha
- */
- function plugin() {
- require_once 'HTML/Template/Flexy/Plugin.php';
- // load pluginManager.
- if (!isset($this->plugin)) {
- $this->plugin = new HTML_Template_Flexy_Plugin;
- $this->plugin->flexy = &$this;
- }
- return $this->plugin->call(func_get_args());
- }
- /**
- *
- * output / display ? - outputs an object, without copy by references..
- *
- * @param optional mixed object to output
- *
- * @return mixed PEAR_Error or true?
- * @access public
- * @see HTML_Template_Flexy::ouptutObject
- * @status alpha
- */
- function output($object = false)
- {
- return $this->outputObject($object);
- }
-
- /**
- *
- * render the template with data..
- *
- * @param optional mixed object to output
- *
- * @return mixed PEAR_Error or true?
- * @access public
- * @see HTML_Template_Flexy::ouptutObject
- * @status alpha
- */
- function toString($object = false)
- {
- return $this->bufferedOutputObject($object);
- }
-
-}
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: nobody <nobody@localhost> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Assign.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-//
-// Provider for Assign API ( Eg. $flexy->assign(...) )
-//
-
-define('HTML_TEMPLATE_FLEXY_ASSIGN_ERROR_INVALIDARGS', -100);
-
-class HTML_Template_Flexy_Assign {
-
- /**
- * The variables stored in the Assigner
- *
- * @var array
- * @access public
- */
- var $variables = array();
- /**
- * The references stored in the Assigner
- *
- * @var array
- * @access public
- */
- var $references = array();
-
-
- /**
- *
- * Assigns a token-name and value to $this->_token_vars for use in a
- * template.
- *
- * There are three valid ways to assign values to a template.
- *
- * Form 1: $args[0] is a string and $args[1] is mixed. This means
- * $args[0] is a token name and $args[1] is the token value (which
- * allows objects, arrays, strings, numbers, or anything else).
- * $args[1] can be null, which means the corresponding token value in
- * the template will also be null.
- *
- * Form 2: $args[0] is an array and $args[1] is not set. Assign a
- * series of tokens where the key is the token name, and the value is
- * token value.
- *
- * Form 3: $args[0] is an object and $args[1] is not set. Assigns
- * copies of all object variables (properties) to tokens; the token
- * name and value is a copy of each object property and value.
- *
- * @access public
- *
- * @param string|array|object $args[0] This param can be a string, an
- * array, or an object. If $args[0] is a string, it is the name of a
- * variable in the template. If $args[0] is an array, it must be an
- * associative array of key-value pairs where the key is a variable
- * name in the template and the value is the value for that variable
- * in the template. If $args[0] is an object, copies of its
- * properties will be assigned to the template.
- *
- * @param mixed $args[1] If $args[0] is an array or object, $args[1]
- * should not be set. Otherwise, a copy of $args[1] is assigned to a
- * template variable named after $args[0].
- *
- * @return bool|PEAR_Error Boolean true if all assignments were
- * committed, or a PEAR_Error object if there was an error.
- *
- * @throws SAVANT_ERROR_ASSIGN Unknown reason for error, probably
- * because you passed $args[1] when $args[0] is an array or object.
- *
- * @author Paul M. Jones <pmjones@ciaweb.net>
- * @see assignRef()
- *
- * @see assignObject()
- *
- */
-
- function assign($args)
- {
- // in Form 1, $args[0] is a string name and $args[1] is mixed.
- // in Form 2, $args[0] is an associative array.
- // in Form 3, $args[0] is an object.
-
- $count = count($args);
-
- // -------------------------------------------------------------
- //
- // Now we assign variable copies.
- //
-
- // form 1 (string name and mixed value)
- // don't check isset() on $args[1] becuase a 'null' is not set,
- // and we might want to pass a null.
- if (is_string($args[0]) && $count > 1) {
- if (isset($this->references[$args[0]])) {
- unset($this->references[$args[0]]);
- }
- // keep a copy in the token vars array
- $this->variables[$args[0]] = $args[1];
-
- // done!
- return true;
- }
-
- // form 2 (assoc array)
- if (is_array($args[0]) && $count == 1) {
-
- foreach ($args[0] as $key=>$val) {
- $this->assign(array($key, $val));
- }
-
- // done!
- return true;
- }
-
- // form 3 (object props)
- if (is_object($args[0]) && $count == 1) {
-
- // get the object properties
- $data = get_object_vars($args[0]);
- foreach ($data as $key=>$val) {
- $this->assign(array($key, $val));
- }
-
- // done!
- return true;
- }
-
-
- // -------------------------------------------------------------
- //
- // Final error catch. We should not have gotten to this point.
- //
-
- return HTML_Template_Flexy::raiseError(
- "invalid type sent to assign, ". print_r($args,true),
- HTML_TEMPLATE_FLEXY_ASSIGN_ERROR_INVALIDARGS
- );
- }
-
-
- /**
- *
- * Assign a token by reference. This allows you change variable
- * values within the template and have those changes reflected back
- * at the calling logic script. Works as with form 2 of assign().
- *
- * @access public
- *
- * @param string $name The template token-name for the reference.
- *
- * @param mixed &$ref The variable passed by-reference.
- *
- * @return bool|PEAR_Error Boolean true on success, or a PEAR_Error
- * on failure.
- *
- * @throws SAVANT_ERROR_ASSIGN_REF Unknown reason for error.
- *
- * @see assign()
- * @author Paul M. Jones <pmjones@ciaweb.net>
- * @see assignObject()
- *
- */
-
- function assignRef($name, &$ref)
- {
- // look for the proper case: name and variable
- if (is_string($name) && isset($ref)) {
- if (isset($this->variables[$name])) {
- unset($this->variables[$name]);
- }
- //
- // assign the token as a reference
- $this->references[$name] =& $ref;
-
- // done!
- return true;
- }
-
- // final error catch
- return HTML_Template_Flexy::raiseError(
- "invalid type sent to assignRef, ". print_r($name,true),
- HTML_TEMPLATE_FLEXY_ASSIGN_ERROR_INVALIDARGS
-
- );
- }
-
-
-}
-
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Alan Knowles <alan@akbkhome.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Compiler.php,v 1.1.1.1 2008/04/28 15:20:50 jamie Exp $
-//
-// Base Compiler Class (Interface)
-//
-
-/**
-* Compiler Globals go here..
-* public (to it's children)
-*
-* @var array
-* @access public (to it's children)
-*/
-
-$GLOBAL['_HTML_TEMPLATE_FLEXY_COMPILER'] = array();
-
-
-class HTML_Template_Flexy_Compiler {
-
-
- /**
- * Options
- *
- * @var array
- * @access public
- */
- var $options;
-
- /**
- * Factory constructor
- *
- * @param array options only ['compiler'] is used directly
- *
- * @return object The Compiler Object
- * @access public
- */
- function factory($options)
- {
- if (empty($options['compiler'])) {
- $options['compiler'] = 'Flexy';
- }
- if ( is_object($options['compiler']) && $this->is_a($options['compiler'], 'HTML_Template_Flexy_Compiler')) {
- $options['compiler']->options = $options;
- return $options['compiler'];
- }
-
- require_once 'HTML/Template/Flexy/Compiler/'.ucfirst( $options['compiler'] ) .'.php';
- $class = 'HTML_Template_Flexy_Compiler_'.$options['compiler'];
- $ret = new $class;
- $ret->options = $options;
- return $ret;
- }
- /**
- * Php4 is_a compat !
- */
- function is_a($obj, $class) // which f***wit depreciated is_a....
- {
- if (version_compare(phpversion(),"5","<")) {
- return is_a($obj, $class);
-
- }
- $test=false;
- @eval("\$test = \$obj instanceof ".$class.";");
- return $test;
-
- }
-
- /**
- * The compile method.
- *
- * @param object HTML_Template_Flexy that is requesting the compile
- * @return object HTML_Template_Flexy
- * @return string to compile (if not using a file as the source)
- * @access public
- */
- function compile(&$flexy,$string = false)
- {
- echo "No compiler implemented!";
- }
-
- /**
- * Append HTML to compiled ouput
- * These are hooks for passing data to other processes
- *
- * @param string to append to compiled
- *
- * @return string to be output
- * @access public
- */
- function appendHtml($string)
- {
-
- return $string;
- }
- /**
- * Append PHP Code to compiled ouput
- * These are hooks for passing data to other processes
- *
- * @param string PHP code to append to compiled
- *
- * @return string to be output
- * @access public
- */
-
- function appendPhp($string)
- {
-
- return '<?php '.$string.'?>';
- }
- /**
- * Compile All templates in the
- * These are hooks for passing data to other processes
- *
- * @param string PHP code to append to compiled
- *
- * @return string to be output
- * @access public
- */
-
- function compileAll(&$flexy, $dir = '',$regex='/.html$/')
- {
- $this->flexy = &$flexy;
- $this->compileDir($dir,$regex);
- }
-
-
- function compileDir($dir = '',$regex='/.html$/')
- {
-
-
- foreach ($this->flexy->options['templateDir'] as $base) {
- if (!file_exists($base . DIRECTORY_SEPARATOR . $dir)) {
- continue;
- }
- $dh = opendir($base . DIRECTORY_SEPARATOR . $dir);
- while (($name = readdir($dh)) !== false) {
- if (!$name) { // empty!?
- continue;
- }
- if ($name{0} == '.') {
- continue;
- }
-
- if (is_dir($base . DIRECTORY_SEPARATOR . $dir . DIRECTORY_SEPARATOR . $name)) {
- $this->compileDir($dir . DIRECTORY_SEPARATOR . $name,$regex);
- continue;
- }
-
- if (!preg_match($regex,$name)) {
- continue;
- }
- //echo "Compiling $dir". DIRECTORY_SEPARATOR . "$name \n";
- $this->flexy->compile($dir . DIRECTORY_SEPARATOR . $name);
- }
- }
-
- }
-
-
-}
-
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Alan Knowles <alan@akbkhome.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Flexy.php,v 1.1.1.1 2008/04/28 15:20:50 jamie Exp $
-//
-// Base Compiler Class
-// Standard 'Original Flavour' Flexy compiler
-
-// this does the main conversion, (eg. for {vars and methods})
-// it relays into Compiler/Tag & Compiler/Flexy for tags and namespace handling.
-
-
-
-
-require_once 'HTML/Template/Flexy/Tokenizer.php';
-require_once 'HTML/Template/Flexy/Token.php';
-
-class HTML_Template_Flexy_Compiler_Flexy extends HTML_Template_Flexy_Compiler {
-
-
-
- /**
- * The current template (Full path)
- *
- * @var string
- * @access public
- */
- var $currentTemplate;
- /**
- * The compile method.
- *
- * @params object HTML_Template_Flexy
- * @params string|false string to compile of false to use a file.
- * @return string filename of template
- * @access public
- */
- function compile(&$flexy, $string=false)
- {
- // read the entire file into one variable
-
- // note this should be moved to new HTML_Template_Flexy_Token
- // and that can then manage all the tokens in one place..
- global $_HTML_TEMPLATE_FLEXY_COMPILER;
-
- $this->currentTemplate = $flexy->currentTemplate;
-
-
- $gettextStrings = &$_HTML_TEMPLATE_FLEXY_COMPILER['gettextStrings'];
- $gettextStrings = array(); // reset it.
-
- if (@$this->options['debug']) {
- echo "compiling template $flexy->currentTemplate<BR>";
-
- }
-
- // reset the elements.
- $flexy->_elements = array();
-
- // replace this with a singleton??
-
- $GLOBALS['_HTML_TEMPLATE_FLEXY']['currentOptions'] = $this->options;
- $GLOBALS['_HTML_TEMPLATE_FLEXY']['elements'] = array();
- $GLOBALS['_HTML_TEMPLATE_FLEXY']['filename'] = $flexy->currentTemplate;
- $GLOBALS['_HTML_TEMPLATE_FLEXY']['prefixOutput'] = '';
- $GLOBALS['_HTML_TEMPLATE_FLEXY']['compiledTemplate']= $flexy->compiledTemplate;
-
-
- // initialize Translation 2, and
- $this->initializeTranslator();
-
-
- // load the template!
- $data = $string;
- $res = false;
- if ($string === false) {
- $data = file_get_contents($flexy->currentTemplate);
- }
-
- // PRE PROCESS {_(.....)} translation markers.
- if (strpos($data, '{_(') !== false) {
- $data = $this->preProcessTranslation($data);
- }
-
- // Tree generation!!!
-
-
-
- if (!$this->options['forceCompile'] && isset($_HTML_TEMPLATE_FLEXY_COMPILER['cache'][md5($data)])) {
- $res = $_HTML_TEMPLATE_FLEXY_COMPILER['cache'][md5($data)];
- } else {
-
-
- $tokenizer = new HTML_Template_Flexy_Tokenizer($data);
- $tokenizer->fileName = $flexy->currentTemplate;
-
-
-
- //$tokenizer->debug=1;
- $tokenizer->options['ignore_html'] = $this->options['nonHTML'];
-
-
- require_once 'HTML/Template/Flexy/Token.php';
- $res = HTML_Template_Flexy_Token::buildTokens($tokenizer);
- if (is_a($res, 'PEAR_Error')) {
- return $res;
- }
- $_HTML_TEMPLATE_FLEXY_COMPILER['cache'][md5($data)] = $res;
-
- }
-
-
- // technically we shouldnt get here as we dont cache errors..
- if (is_a($res, 'PEAR_Error')) {
- return $res;
- }
-
- // turn tokens into Template..
-
- $data = $res->compile($this);
-
- if (is_a($data, 'PEAR_Error')) {
- return $data;
- }
-
- $data = $GLOBALS['_HTML_TEMPLATE_FLEXY']['prefixOutput'] . $data;
-
- if ( $flexy->options['debug'] > 1) {
- echo "<B>Result: </B><PRE>".htmlspecialchars($data)."</PRE><BR>\n";
- }
-
- if ($this->options['nonHTML']) {
- $data = str_replace("?>\n", "?>\n\n", $data);
- }
-
-
-
-
- // at this point we are into writing stuff...
- if ($flexy->options['compileToString']) {
- if ( $flexy->options['debug']) {
- echo "<B>Returning string:<BR>\n";
- }
-
- $flexy->elements = $GLOBALS['_HTML_TEMPLATE_FLEXY']['elements'];
- return $data;
- }
-
-
-
-
- // error checking?
- $file = $flexy->compiledTemplate;
- if (isset($flexy->options['output.block'])) {
- list($file, $part) = explode('#', $file);
- }
-
- if( ($cfp = fopen($file, 'w')) ) {
- if ($flexy->options['debug']) {
- echo "<B>Writing: </B>$file<BR>\n";
- }
- fwrite($cfp, $data);
- fclose($cfp);
-
- chmod($file, 0775);
- // make the timestamp of the two items match.
- clearstatcache();
- touch($file, filemtime($flexy->currentTemplate));
- if ($file != $flexy->compiledTemplate) {
- chmod($flexy->compiledTemplate, 0775);
- // make the timestamp of the two items match.
- clearstatcache();
- touch($flexy->compiledTemplate, filemtime($flexy->currentTemplate));
- }
-
-
- } else {
- return HTML_Template_Flexy::raiseError('HTML_Template_Flexy::failed to write to '.$flexy->compiledTemplate,
- HTML_TEMPLATE_FLEXY_ERROR_FILE, HTML_TEMPLATE_FLEXY_ERROR_RETURN);
- }
- // gettext strings
-
- if (file_exists($flexy->getTextStringsFile)) {
- unlink($flexy->getTextStringsFile);
- }
-
- if($gettextStrings && ($cfp = fopen( $flexy->getTextStringsFile, 'w') ) ) {
-
- fwrite($cfp, serialize(array_unique($gettextStrings)));
- fclose($cfp);
- chmod($flexy->getTextStringsFile, 0664);
- }
-
- // elements
- if (file_exists($flexy->elementsFile)) {
- unlink($flexy->elementsFile);
- }
-
- if( $GLOBALS['_HTML_TEMPLATE_FLEXY']['elements'] &&
- ($cfp = fopen( $flexy->elementsFile, 'w') ) ) {
- fwrite($cfp, serialize( $GLOBALS['_HTML_TEMPLATE_FLEXY']['elements']));
- fclose($cfp);
- chmod($flexy->elementsFile, 0664);
- // now clear it.
-
- }
-
- return true;
- }
-
-
- /**
- * Initilalize the translation methods.
- *
- * Loads Translation2 if required.
- *
- *
- * @return none
- * @access public
- */
- function initializeTranslator() {
-
- if (is_array($this->options['Translation2'])) {
- require_once 'Translation2.php';
- $this->options['Translation2'] = &Translation2::factory(
- $this->options['Translation2']['driver'],
- isset($this->options['Translation2']['options']) ? $this->options['Translation2']['options'] : array(),
- isset($this->options['Translation2']['params']) ? $this->options['Translation2']['params'] : array()
- );
- }
-
- if (is_a($this->options['Translation2'], 'Translation2')) {
- $this->options['Translation2']->setLang($this->options['locale']);
- // fixme - needs to be more specific to which template to use..
- foreach ($this->options['templateDir'] as $tt) {
- $n = basename($this->currentTemplate);
- if (substr($this->currentTemplate, 0, strlen($tt)) == $tt) {
- $n = substr($this->currentTemplate, strlen($tt)+1);
- }
- //echo $n;
- }
- $this->options['Translation2']->setPageID($n);
- } else {
- setlocale(LC_MESSAGES, $this->options['locale']);
- }
-
- }
-
-
-
- /**
- * do the early tranlsation of {_(......)_} text
- *
- *
- * @param input string
- * @return output string
- * @access public
- */
- function preProcessTranslation($data) {
- global $_HTML_TEMPLATE_FLEXY_COMPILER;
- $matches = array();
- $lmatches = explode ('{_(', $data);
- array_shift($lmatches);
- // shift the first..
- foreach ($lmatches as $k) {
- if (false === strpos($k, ')_}')) {
- continue;
- }
- $x = explode(')_}', $k);
- $matches[] = $x[0];
- }
-
-
- //echo '<PRE>';print_r($matches);
- // we may need to do some house cleaning here...
- $_HTML_TEMPLATE_FLEXY_COMPILER['gettextStrings'] = $matches;
-
-
- // replace them now..
- // ** leaving in the tag (which should be ignored by the parser..
- // we then get rid of the tags during the toString method in this class.
- foreach($matches as $v) {
- $data = str_replace('{_('.$v.')_}', '{_('.$this->translateString($v).')_}', $data);
- }
- return $data;
- }
-
-
-
-
-
- /**
- * Flag indicating compiler is inside {_( .... )_} block, and should not
- * add to the gettextstrings array.
- *
- * @var boolean
- * @access public
- */
- var $inGetTextBlock = false;
-
- /**
- * This is the base toString Method, it relays into toString{TokenName}
- *
- * @param object HTML_Template_Flexy_Token_*
- *
- * @return string string to build a template
- * @access public
- * @see toString*
- */
-
-
- function toString($element)
- {
- static $len = 26; // strlen('HTML_Template_Flexy_Token_');
- if ($this->options['debug'] > 1) {
- $x = $element;
- unset($x->children);
- //echo htmlspecialchars(print_r($x,true))."<BR>\n";
- }
- if ($element->token == 'GetTextStart') {
- $this->inGetTextBlock = true;
- return '';
- }
- if ($element->token == 'GetTextEnd') {
- $this->inGetTextBlock = false;
- return '';
- }
-
-
- $class = get_class($element);
- if (strlen($class) >= $len) {
- $type = substr($class, $len);
- return $this->{'toString'.$type}($element);
- }
-
- $ret = $element->value;
- $add = $element->compileChildren($this);
- if (is_a($add, 'PEAR_Error')) {
- return $add;
- }
- $ret .= $add;
-
- if ($element->close) {
- $add = $element->close->compile($this);
- if (is_a($add, 'PEAR_Error')) {
- return $add;
- }
- $ret .= $add;
- }
-
- return $ret;
- }
-
-
- /**
- * HTML_Template_Flexy_Token_Else toString
- *
- * @param object HTML_Template_Flexy_Token_Else
- *
- * @return string string to build a template
- * @access public
- * @see toString*
- */
-
-
- function toStringElse($element)
- {
- // pushpull states to make sure we are in an area.. - should really check to see
- // if the state it is pulling is a if...
- if ($element->pullState() === false) {
- return $this->appendHTML(
- "<font color=\"red\">Unmatched {else:} on line: {$element->line}</font>"
- );
- }
- $element->pushState();
- return $this->appendPhp("} else {");
- }
-
- /**
- * HTML_Template_Flexy_Token_End toString
- *
- * @param object HTML_Template_Flexy_Token_Else
- *
- * @return string string to build a template
- * @access public
- * @see toString*
- */
-
- function toStringEnd($element)
- {
- // pushpull states to make sure we are in an area.. - should really check to see
- // if the state it is pulling is a if...
- if ($element->pullState() === false) {
- return $this->appendHTML(
- "<font color=\"red\">Unmatched {end:} on line: {$element->line}</font>"
- );
- }
-
- return $this->appendPhp("}");
- }
-
- /**
- * HTML_Template_Flexy_Token_EndTag toString
- *
- * @param object HTML_Template_Flexy_Token_EndTag
- *
- * @return string string to build a template
- * @access public
- * @see toString*
- */
-
-
-
- function toStringEndTag($element)
- {
- return $this->toStringTag($element);
- }
-
-
-
- /**
- * HTML_Template_Flexy_Token_Foreach toString
- *
- * @param object HTML_Template_Flexy_Token_Foreach
- *
- * @return string string to build a template
- * @access public
- * @see toString*
- */
-
-
- function toStringForeach($element)
- {
-
- $loopon = $element->toVar($element->loopOn);
- if (is_a($loopon, 'PEAR_Error')) {
- return $loopon;
- }
-
- $ret = 'if ($this->options[\'strict\'] || ('.
- 'is_array('. $loopon. ') || ' .
- 'is_object(' . $loopon . '))) ' .
- 'foreach(' . $loopon . " ";
-
- $ret .= "as \${$element->key}";
-
- if ($element->value) {
- $ret .= " => \${$element->value}";
- }
- $ret .= ") {";
-
- $element->pushState();
- $element->pushVar($element->key);
- $element->pushVar($element->value);
- return $this->appendPhp($ret);
- }
- /**
- * HTML_Template_Flexy_Token_If toString
- *
- * @param object HTML_Template_Flexy_Token_If
- *
- * @return string string to build a template
- * @access public
- * @see toString*
- */
-
- function toStringIf($element)
- {
-
- $var = $element->toVar($element->condition);
- if (is_a($var, 'PEAR_Error')) {
- return $var;
- }
-
- $ret = "if (".$element->isNegative . $var .") {";
- $element->pushState();
- return $this->appendPhp($ret);
- }
-
- /**
- * get Modifier Wrapper
- *
- * converts :h, :u, :r , .....
- * @param object HTML_Template_Flexy_Token_Method|Var
- *
- * @return array prefix,suffix
- * @access public
- * @see toString*
- */
-
- function getModifierWrapper($element)
- {
- $prefix = 'echo ';
-
- $suffix = '';
- $modifier = strlen(trim($element->modifier)) ? $element->modifier : ' ';
-
- switch ($modifier) {
- case 'h':
- break;
- case 'u':
- $prefix = 'echo urlencode(';
- $suffix = ')';
- break;
- case 'r':
- $prefix = 'echo \'<pre>\'; echo htmlspecialchars(print_r(';
- $suffix = ',true)); echo \'</pre>\';';
- break;
- case 'n':
- // blank or value..
- $numberformat = @$GLOBALS['_HTML_TEMPLATE_FLEXY']['currentOptions']['numberFormat'];
- $prefix = 'echo number_format(';
- $suffix = $GLOBALS['_HTML_TEMPLATE_FLEXY']['currentOptions']['numberFormat'] . ')';
- break;
- case 'b': // nl2br + htmlspecialchars
- $prefix = 'echo nl2br(htmlspecialchars(';
-
- // add language ?
- $suffix = '))';
- break;
- case 'e':
- $prefix = 'echo htmlentities(';
- // add language ?
- $suffix = ')';
- break;
- case ' ':
- $prefix = 'echo htmlspecialchars(';
- // add language ?
- $suffix = ')';
- break;
- default:
- $prefix = 'echo $this->plugin("'.trim($element->modifier) .'",';
- $suffix = ')';
-
-
- }
-
- return array($prefix, $suffix);
- }
-
-
-
- /**
- * HTML_Template_Flexy_Token_Var toString
- *
- * @param object HTML_Template_Flexy_Token_Method
- *
- * @return string string to build a template
- * @access public
- * @see toString*
- */
-
- function toStringVar($element)
- {
- // ignore modifier at present!!
-
- $var = $element->toVar($element->value);
- if (is_a($var, 'PEAR_Error')) {
- return $var;
- }
- list($prefix, $suffix) = $this->getModifierWrapper($element);
- return $this->appendPhp( $prefix . $var . $suffix .';');
- }
- /**
- * HTML_Template_Flexy_Token_Method toString
- *
- * @param object HTML_Template_Flexy_Token_Method
- *
- * @return string string to build a template
- * @access public
- * @see toString*
- */
-
- function toStringMethod($element)
- {
-
-
- // set up the modifier at present!!
-
- list($prefix, $suffix) = $this->getModifierWrapper($element);
-
- // add the '!' to if
-
- if ($element->isConditional) {
- $prefix = 'if ('.$element->isNegative;
- $element->pushState();
- $suffix = ')';
- }
-
-
- // check that method exists..
- // if (method_exists($object,'method');
- $bits = explode('.', $element->method);
- $method = array_pop($bits);
-
- $object = implode('.', $bits);
-
- $var = $element->toVar($object);
- if (is_a($var, 'PEAR_Error')) {
- return $var;
- }
-
- if (($object == 'GLOBALS') &&
- $GLOBALS['_HTML_TEMPLATE_FLEXY']['currentOptions']['globalfunctions']) {
- // we should check if they something weird like: GLOBALS.xxxx[sdf](....)
- $var = $method;
- } else {
- $prefix = 'if ($this->options[\'strict\'] || (isset('.$var.
- ') && method_exists('.$var .", '{$method}'))) " . $prefix;
- $var = $element->toVar($element->method);
- }
-
-
- if (is_a($var, 'PEAR_Error')) {
- return $var;
- }
-
- $ret = $prefix;
- $ret .= $var . "(";
- $s =0;
-
-
-
- foreach($element->args as $a) {
-
- if ($s) {
- $ret .= ",";
- }
- $s =1;
- if ($a{0} == '#') {
- if (is_numeric(substr($a, 1, -1))) {
- $ret .= substr($a, 1, -1);
- } else {
- $ret .= '"'. addslashes(substr($a, 1, -1)) . '"';
- }
- continue;
- }
-
- $var = $element->toVar($a);
- if (is_a($var, 'PEAR_Error')) {
- return $var;
- }
- $ret .= $var;
-
- }
- $ret .= ")" . $suffix;
-
- if ($element->isConditional) {
- $ret .= ' { ';
- } else {
- $ret .= ";";
- }
-
-
-
- return $this->appendPhp($ret);
-
-
-
- }
- /**
- * HTML_Template_Flexy_Token_Processing toString
- *
- * @param object HTML_Template_Flexy_Token_Processing
- *
- * @return string string to build a template
- * @access public
- * @see toString*
- */
-
-
- function toStringProcessing($element)
- {
- // if it's XML then quote it..
- if (strtoupper(substr($element->value, 2, 3)) == 'XML') {
- return $this->appendPhp("echo '" . str_replace("'", "\\"."'", $element->value) . "';");
- }
- // otherwise it's PHP code - so echo it..
- return $element->value;
- }
-
- /**
- * HTML_Template_Flexy_Token_Text toString
- *
- * @param object HTML_Template_Flexy_Token_Text
- *
- * @return string string to build a template
- * @access public
- * @see toString*
- */
-
-
-
- function toStringText($element)
- {
-
- // first get rid of stuff thats not translated etc.
- // empty strings => output.
- // comments -> just output
- // our special tags -> output..
-
- if (!strlen(trim($element->value) )) {
- return $this->appendHtml($element->value);
- }
- // dont add comments to translation lists.
-
- if (substr($element->value, 0, 4) == '<!--') {
- return $this->appendHtml($element->value);
- }
- // ignore anything wrapped with {_( .... )_}
- if ($this->inGetTextBlock) {
- return $this->appendHtml($element->value);
- }
-
-
- if (!$element->isWord()) {
- return $this->appendHtml($element->value);
- }
-
- // grab the white space at start and end (and keep it!
-
- $value = ltrim($element->value);
- $front = substr($element->value, 0, -strlen($value));
- $value = rtrim($element->value);
- $rear = substr($element->value, strlen($value));
- $value = trim($element->value);
-
-
- // convert to escaped chars.. (limited..)
- //$value = strtr($value,$cleanArray);
-
- $this->addStringToGettext($value);
- $value = $this->translateString($value);
- // its a simple word!
- return $this->appendHtml($front . $value . $rear);
-
- }
-
-
-
- /**
- * HTML_Template_Flexy_Token_Cdata toString
- *
- * @param object HTML_Template_Flexy_Token_Cdata ?
- *
- * @return string string to build a template
- * @access public
- * @see toString*
- */
-
-
-
- function toStringCdata($element)
- {
- return $this->appendHtml($element->value);
- }
-
-
-
-
-
-
-
-
-
-
- /**
- * addStringToGettext
- *
- * Adds a string to the gettext array.
- *
- * @param mixed preferably.. string to store
- *
- * @return none
- * @access public
- */
-
- function addStringToGettext($string)
- {
-
-
-
-
- if (!is_string($string)) {
- return;
- }
-
- if (!preg_match('/\w+/i', $string)) {
- return;
- }
- $string = trim($string);
-
- if (substr($string, 0, 4) == '<!--') {
- return;
- }
-
- $GLOBALS['_HTML_TEMPLATE_FLEXY_COMPILER']['gettextStrings'][] = $string;
- }
-
-
- /**
- * translateString - a gettextWrapper
- *
- * tries to do gettext or falls back on File_Gettext
- * This has !!!NO!!! error handling - if it fails you just get english..
- * no questions asked!!!
- *
- * @param string string to translate
- *
- * @return string translated string..
- * @access public
- */
-
- function translateString($string)
- {
-
-
-
- if (is_a($this->options['Translation2'], 'Translation2')) {
- $result = $this->options['Translation2']->get($string);
- if (!empty($result)) {
- return $result;
- }
- return $string;
- }
-
- // note this stuff may have been broken by removing the \n replacement code
- // since i dont have a test for it... it may remain broken..
- // use Translation2 - it has gettext backend support
- // and should sort out the mess that \n etc. entail.
-
-
- $prefix = basename($GLOBALS['_HTML_TEMPLATE_FLEXY']['filename']).':';
- if (@$this->options['debug']) {
- echo __CLASS__.":TRANSLATING $string<BR>\n";
- }
-
- if (function_exists('gettext') && !$this->options['textdomain']) {
- if (@$this->options['debug']) {
- echo __CLASS__.":USING GETTEXT?<BR>";
- }
- $t = gettext($string);
-
- if ($t != $string) {
- return $t;
- }
- $tt = gettext($prefix.$string);
- if ($tt != $prefix.$string) {
- return $tt;
- }
- // give up it's not translated anywhere...
- return $string;
-
- }
- if (!$this->options['textdomain'] || !$this->options['textdomainDir']) {
- // text domain is not set..
- if (@$this->options['debug']) {
- echo __CLASS__.":MISSING textdomain settings<BR>";
- }
- return $string;
- }
- $pofile = $this->options['textdomainDir'] .
- '/' . $this->options['locale'] .
- '/LC_MESSAGES/' . $this->options['textdomain'] . '.po';
-
-
- // did we try to load it already..
- if (@$GLOBALS['_'.__CLASS__]['PO'][$pofile] === false) {
- if (@$this->options['debug']) {
- echo __CLASS__.":LOAD failed (Cached):<BR>";
- }
- return $string;
- }
- if (!@$GLOBALS['_'.__CLASS__]['PO'][$pofile]) {
- // default - cant load it..
- $GLOBALS['_'.__CLASS__]['PO'][$pofile] = false;
- if (!file_exists($pofile)) {
- if (@$this->options['debug']) {
- echo __CLASS__.":LOAD failed: {$pofile}<BR>";
- }
- return $string;
- }
-
- if (!@include_once 'File/Gettext.php') {
- if (@$this->options['debug']) {
- echo __CLASS__.":LOAD no File_gettext:<BR>";
- }
- return $string;
- }
-
- $GLOBALS['_'.__CLASS__]['PO'][$pofile] = File_Gettext::factory('PO', $pofile);
- $GLOBALS['_'.__CLASS__]['PO'][$pofile]->load();
- //echo '<PRE>'.htmlspecialchars(print_r($GLOBALS['_'.__CLASS__]['PO'][$pofile]->strings,true));
-
- }
- $po = &$GLOBALS['_'.__CLASS__]['PO'][$pofile];
- // we should have it loaded now...
- // this is odd - data is a bit messed up with CR's
- $string = str_replace('\n', "\n", $string);
-
- if (isset($po->strings[$prefix.$string])) {
- return $po->strings[$prefix.$string];
- }
-
- if (!isset($po->strings[$string])) {
- if (@$this->options['debug']) {
- echo __CLASS__.":no match:<BR>";
- }
- return $string;
- }
- if (@$this->options['debug']) {
- echo __CLASS__.":MATCHED: {$po->strings[$string]}<BR>";
- }
-
- // finally we have a match!!!
- return $po->strings[$string];
-
- }
- /**
- * HTML_Template_Flexy_Token_Tag toString
- *
- * @param object HTML_Template_Flexy_Token_Tag
- *
- * @return string string to build a template
- * @access public
- * @see toString*
- */
-
- function toStringTag($element) {
-
- $original = $element->getAttribute('ALT');
- // techncially only input type=(submit|button|input) alt=.. applies, but we may
- // as well translate any occurance...
- if ( (($element->tag == 'IMG') || ($element->tag == 'INPUT'))
- && is_string($original) && strlen($original)) {
- $this->addStringToGettext($original);
- $quote = $element->ucAttributes['ALT']{0};
- $element->ucAttributes['ALT'] = $quote . $this->translateString($original). $quote;
- }
- $original = $element->getAttribute('TITLE');
- if (is_string($original) && strlen($original)) {
- $this->addStringToGettext($original);
- $quote = $element->ucAttributes['TITLE']{0};
- $element->ucAttributes['TITLE'] = $quote . $this->translateString($original). $quote;
- }
-
-
- if (strpos($element->tag, ':') === false) {
- $namespace = 'Tag';
- } else {
- $bits = explode(':', $element->tag);
- $namespace = $bits[0];
- }
- if ($namespace{0} == '/') {
- $namespace = substr($namespace, 1);
- }
- if (empty($this->tagHandlers[$namespace])) {
-
- require_once 'HTML/Template/Flexy/Compiler/Flexy/Tag.php';
- $this->tagHandlers[$namespace] = &HTML_Template_Flexy_Compiler_Flexy_Tag::factory($namespace, $this);
- if (!$this->tagHandlers[$namespace] ) {
- return HTML_Template_Flexy::raiseError('HTML_Template_Flexy::failed to create Namespace Handler '.$namespace .
- ' in file ' . $GLOBALS['_HTML_TEMPLATE_FLEXY']['filename'],
- HTML_TEMPLATE_FLEXY_ERROR_SYNTAX, HTML_TEMPLATE_FLEXY_ERROR_RETURN);
- }
-
- }
- return $this->tagHandlers[$namespace]->toString($element);
-
-
- }
-
-
-}
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Rick < reick at coalescentdesign dot com > |
-// +----------------------------------------------------------------------+
-//
-/** Class called from HTML_Template_Flexy_Compiler_Flexy_Tag's toString() method.
-* For handling new custom flexy namespaced attributes.
-*/
-class HTML_Template_Flexy_Compiler_Flexy_CustomFlexyAttributes
-{
-
- /**
- * doCustomAttributes
- * - for every flexy namespaced attribute found in the element parameter,
- * if there is a method here to handle it then call the method.
- *
- * @params object HTML_Template_Flexy_Token
- * @return none
- * @access public
- */
- function doCustomAttributes(&$element)
- {
-
- foreach ($element->ucAttributes as $key=>$value) {
-
- list($namespace,$attribute) = (strpos($key, ":") > -1) ? explode(':',$key) : array("", $key);
- $method = strtolower($attribute) . 'Attribute';
- if (strtolower($namespace) != 'flexy') {
- return;
- }
- if ((strlen($attribute)) && (method_exists($this,$method))) {
- $this->{$method}($element, $element->getAttribute($key));
- }
- }
- }
-
- /**
- * flexy:content attribute handler
- *
- * Examples:
- * <anyTag... flexy:content="methodOrVariableOrNothing" .../>
- * <anyTag... flexy:content="methodOrVariableOrNothing" ...></anyTag>
- * <anyTag... flexy:content="methodOrVariableOrNothing" ...>All this <b>CONTENT</b> will be <i>replaced<i> by
- * the result of methodOrVariableOrNothing</anyTag>
- *
- * Replaces element content with the result of the variable or method call or empty string.
- * Useful for replacing example content/html from the compiled template, while keeping it in the source
- * template for viewing when not running php. The example content/html will be replaced by dynamic content at run-time.
- *
- * Substitute for <anyTag...>{methodOrVariable}</anyTag>
- *
- * @params object HTML_Template_Flexy_Token
- * @params string attribute value
- * @return none
- * @access private
- */
- function contentAttribute(&$element,$val)
- {
- // assign method or variable $val as the child token of this element, potentially replacing any existing children
- // default: special case if $val is empty - simply set children to null
- $element->children = null;
- if (! empty($val)) {
- $this->replaceChildren($element,$val);
- }
-
- // do we have to add a seperate closing tag token to surround the content within...
- if ($element->close) {
- return;
- }
- if ($element->getAttribute('/') !== false) {
- // valid xhtml (eg. <tag />)
- // remove the '/' since we must add a seperate closing tag token to surround the content within
- unset($element->attributes['/']);
- unset($element->ucAttributes['/']);
- } else {
- // FIXME: error not valid xhtml
- }
-
- // add a seperate closing tag token to surround the content within
- $element->close = $element->factory("EndTag",array('/'.$element->oTag), $element->line);
- }
-
- /**
- * flexy:replace attribute handler
- *
- * Examples:
- * <anyTag... flexy:replace="methodOrVariableOrNothing" .../>
- * <anyTag... flexy:replace="methodOrVariableOrNothing" ...></anyTag>
- * <anyTag... flexy:replace="methodOrVariableOrNothing" ...>Entire <b>element</b> including tag <i>replaced<i> by
- * the result of methodOrVariableOrNothing</anyTag>
- *
- * Replaces entire element with the result of the variable or method call or empty string.
- * Useful for removing example html from the compiled template, while keeping it in the source template for viewing
- * when not running php. The example html will be replaced by dynamic content at run-time.
- *
- * Substitute for {methodOrVariable}
- *
- * @params object HTML_Template_Flexy_Token
- * @params string attribute value
- * @return none
- * @access private
- */
- function replaceAttribute(&$element,$val)
- {
- // Setting tag to empty will prevent the opening and closing tags from beinging displayed
- $element->tag = null;
- $element->oTag = null;
-
- // assign method or variable $val as the child token of this element, potentially replacing any existing children
- // special case if $val is empty - simply set children to null
- $element->children = null;
- if (! empty($val)) {
- //echo '<br/>VAL IS: ' . $val;
- $this->replaceChildren($element,$val);
- }
- }
-
- /**
- * flexy:omittag attribute handler
- * <... flexy:omittag ...>
- * <... flexy:omittag="" ...>
- * <... flexy:omittag="anything" ...>
- * Removes the tag but keeps the contents of the element including child elements. This is
- * useful for flexy:if and flexy:foreach when the tag isn't wanted but you would
- * prefer not to use {} placeholders for conditionals and loops.
- *
- * @params object HTML_Template_Flexy_Token
- * @params string attribute value
- * @return none
- * @access private
- */
- function omittagAttribute(&$element,$val)
- {
- // Setting tag to empty will prevent the opening and closing tags from beinging displayed
- $element->tag = null;
- $element->oTag = null;
- }
-
- /**
- * replaceChildren
- * - replaces element children with the method or variable Token generated from the $val parameter
- *
- * @params object HTML_Template_Flexy_Token
- * @params string attribute value
- * @return none
- * @access private
- */
- function replaceChildren(&$element,&$val)
- {
- // Most of the this method is borrowed from parseAttributeIf() in HTML_Template_Flexy_Compiler_Flexy_Tag
-
- // If this is a method, not a variable (last character is ')' )...
- if (substr($val,-1) == ')') {
- // grab args..
- $args = substr($val,strpos($val,'(')+1,-1);
- // simple explode ...
-
- $args = strlen(trim($args)) ? explode(',',$args) : array();
- //print_R($args);
-
- // this is nasty... - we need to check for quotes = eg. # at beg. & end..
- $args_clean = array();
- // clean all method arguments...
- for ($i=0; $i<count($args); $i++) {
- if ($args[$i]{0} != '#') {
- $args_clean[] = $args[$i];
- continue;
- }
- // single # - so , must be inside..
- if ((strlen($args[$i]) > 1) && ($args[$i]{strlen($args[$i])-1}=='#')) {
- $args_clean[] = $args[$i];
- continue;
- }
-
- $args[$i] .=',' . $args[$i+1];
- // remove args+1..
- array_splice($args,$i+1,1);
- $i--;
- // reparse..
- }
-
- //echo('<br/>VAL: ' . $val . ' is seen as method');
-
- $childToken = $element->factory('Method',array(substr($val,0,strpos($val,'(')), $args_clean), $element->line);
- } else {
-
- //echo('<br/>VAL: ' . $val . ' is seen as var');
- $childToken = $element->factory('Var', '{'.$val.'}', $element->line);
- }
-
- $element->children = array($childToken);
-
- }
-}
-
-
-
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Alan Knowles <alan@akkbhome.com> |
-// | Authors: Tobias dot eberle at gmx dot de (include with vars) |
-// +----------------------------------------------------------------------+
-//
-// $Id: Flexy.php,v 1.1.1.1 2008/04/28 15:20:50 jamie Exp $
-//
-// Handler code for the <flexy: namespace
-//
-
-/**
-* the <flexy:XXXX namespace
-*
-*
-* at present it handles
-* <flexy:toJavascript flexy:prefix="Javascript_prefix" javscriptName="PHPvar" .....>
-* <flexy:include src="xxx.htm">
-*
-*
-*
-* @version $Id: Flexy.php,v 1.1.1.1 2008/04/28 15:20:50 jamie Exp $
-*/
-
-class HTML_Template_Flexy_Compiler_Flexy_Flexy {
-
-
- /**
- * Parent Compiler for
- *
- * @var object HTML_Template_Flexy_Compiler
- *
- * @access public
- */
- var $compiler;
-
-
- /**
- * The current element to parse..
- *
- * @var object
- * @access public
- */
- var $element;
-
-
-
-
-
- /**
- * toString - display tag, attributes, postfix and any code in attributes.
- * Relays into namspace::method to get results..
- *
- *
- * @see parent::toString()
- */
- function toString($element)
- {
-
- list($namespace,$method) = explode(':',$element->oTag);
- if (!strlen($method)) {
- return '';
- }
- // things we dont handle...
- if (!method_exists($this,$method.'ToString')) {
- return '';
- }
- return $this->{$method.'ToString'}($element);
-
- }
- /**
- * toJavascript handler
- * <flexy:toJavascript flexy:prefix="some_prefix_" javascriptval="php.val" ....>
- *
- * @see parent::toString()
- */
-
- function toJavascriptToString($element)
- {
- $ret = $this->compiler->appendPhp( "require_once 'HTML/Javascript/Convert.php';");
- $ret .= $this->compiler->appendHTML("\n<script type='text/javascript'>\n");
- $prefix = ''. $element->getAttribute('FLEXY:PREFIX');
-
-
- foreach ($element->attributes as $k=>$v) {
- // skip directives..
- if (strpos($k,':')) {
- continue;
- }
- if ($k == '/') {
- continue;
- }
- $v = substr($v,1,-1);
- $ret .= $this->compiler->appendPhp(
- '$__tmp = HTML_Javascript_Convert::convertVar('.$element->toVar($v) .',\''.$prefix . $k.'\',true);'.
- 'echo (is_a($__tmp,"PEAR_Error")) ? ("<pre>".print_r($__tmp,true)."</pre>") : $__tmp;');
- $ret .= $this->compiler->appendHTML("\n");
- }
- $ret .= $this->compiler->appendHTML("</script>");
- return $ret;
- }
-
- /**
- * toJavascript handler
- * <flexy:toJSON javascriptval="php.val" ....>
- *
- * @see parent::toString()
- */
-
- function toJSONToString($element)
- {
- // maybe should use extnsion_exists....
- $ret = "";
- if (!function_exists('json_encode')) {
- $ret = $this->compiler->appendPhp(
- 'require_once "Services/JSON.php"; $_json = new Services_JSON();'
- );
- }
-
- //$ret = $this->compiler->appendPhp( "require_once 'HTML/Javascript/Convert.php';");
- $ret .= $this->compiler->appendHTML("\n<script type='text/javascript'>\n");
- //$prefix = ''. $element->getAttribute('FLEXY:PREFIX');
-
-
- foreach ($element->attributes as $k=>$v) {
- // skip directives..
- if (strpos($k,':')) {
- continue;
- }
- if ($k == '/') {
- continue;
- }
- $v = substr($v,1,-1);
- if (function_exists('json_encode')) {
- $ret .= $this->compiler->appendPhp(
- 'echo $k . "=" . json_encode('.$element->toVar($v).') . "\n";'
- );
- $ret .= $this->compiler->appendHTML("\n");
- continue;
- }
- $ret .= $this->compiler->appendPhp(
- 'echo "'.$k.'=" . $_json->encode('.$element->toVar($v).') . "\n";'
- );
-
- $ret .= $this->compiler->appendHTML("\n");
- }
- $ret .= $this->compiler->appendHTML("</script>");
- return $ret;
- }
-
- /**
- * include handler
- * <flexy:include src="test.html">
- * <flexy:include src="{test}">
- * <flexy:include src="{test}.html">
- * @see parent::toString()
- */
- function includeToString($element)
- {
- // this is disabled by default...
- // we ignore modifier pre/suffix
-
-
-
-
-
- if (!isset($element->ucAttributes['SRC'])) {
- return $this->compiler->appendHTML("<B>Flexy:Include without a src=filename (Line: {$element->line})</B>");
- }
- $arg = $element->ucAttributes['SRC'];
-
- // it's a string so its easy to handle
- switch (true) {
- case is_string($arg):
- if ($arg == '""') {
- return $this->compiler->appendHTML("<B>Flexy:Include src attribute is empty. (Line: {$element->line})</B>");
- }
- $arg = "'{$element->getAttribute('SRC')}'";
- break;
-
- case is_array($arg): // it's an array -> strings and variables possible
- $string = '"';
- foreach($arg as $item) {
- //it's a string
- if (is_string($item)) {
- if ($item != '' && $item != '"' && $item != '""' &&
- $item != "''") {
- $string .= $item;
- }
- } else {
- //it's a variable
- if (is_a($item, 'HTML_Template_Flexy_Token_Var')) {
- $value = $item->toVar($item->value);
- if (is_a($value, 'PEAR_Error')) {
- return $value;
- }
- $string .= "{{$value}}";
- }
- }
- }
- $arg = $string . '"';
- break;
-
- default:
- //something unexspected
- return HTML_Template_Flexy::raiseError(
- ' Flexy:Include SRC needs a string or variable/method as value. '.
- " Error on Line {$element->line} <{$element->tag}>",
- null, HTML_TEMPLATE_FLEXY_ERROR_DIE);
-
-
-
- }
-
- // ideally it would be nice to embed the results of one template into another.
- // however that would involve some complex test which would have to stat
- // the child templates anyway..
- // compile the child template....
- // output... include $this->options['compiled_templates'] . $arg . $this->options['locale'] . '.php'
- return $this->compiler->appendPHP( "\n".
- "\$x = new HTML_Template_Flexy(\$this->options);\n".
- "\$x->compile({$arg});\n".
- "\$_t = function_exists('clone') ? clone(\$t) : \$t;\n".
- "foreach(get_defined_vars() as \$k=>\$v) {\n" .
- " if (\$k != 't') { \$_t->\$k = \$v; }\n" .
- "}\n" .
- "\$x->outputObject(\$_t, \$this->elements);\n"
- );
-
- }
-
- /**
- * Convert flexy tokens to HTML_Template_Flexy_Elements.
- *
- * @param object token to convert into a element.
- * @return object HTML_Template_Flexy_Element
- * @access public
- */
- function toElement($element)
- {
- return '';
- }
-
-
- /**
- * Handler for User defined functions in templates..
- * <flexy:function name="xxxxx">.... </flexy:block> // equivilant to function xxxxx() {
- * <flexy:function call="{xxxxx}">.... </flexy:block> // equivilant to function {$xxxxx}() {
- * <flexy:function call="xxxxx">.... </flexy:block> // equivilant to function {$xxxxx}() {
- *
- * This will not handle nested blocks initially!! (and may cause even more problems with
- * if /foreach stuff..!!
- *
- * @param object token to convert into a element.
- * @access public
- */
-
-
- function functionToString($element)
- {
-
- if ($arg = $element->getAttribute('NAME')) {
- // this is a really kludgy way of doing this!!!
- // hopefully the new Template Package will have a sweeter method..
- $GLOBALS['_HTML_TEMPLATE_FLEXY']['prefixOutput'] .=
- $this->compiler->appendPHP(
- "\nfunction _html_template_flexy_compiler_flexy_flexy_{$arg}(\$t,\$this) {\n").
- $element->compileChildren($this->compiler) .
- $this->compiler->appendPHP( "\n}\n");
-
- return '';
- }
- if (!isset($element->ucAttributes['CALL'])) {
-
- return HTML_Template_Flexy::raiseError(
- ' tag flexy:function needs an argument call or name'.
- " Error on Line {$element->line} <{$element->tag}>",
- null, HTML_TEMPLATE_FLEXY_ERROR_DIE);
- }
- // call is a stirng : nice and simple..
- if (is_string($element->ucAttributes['CALL'])) {
- $arg = $element->getAttribute('CALL');
- return $this->compiler->appendPHP(
- "if (function_exists('_html_template_flexy_compiler_flexy_flexy_{$arg}')) " .
- " _html_template_flexy_compiler_flexy_flexy_{$arg}(\$t,\$this);");
- }
-
- // we make a big assumption here.. - it should really be error checked..
- // that the {xxx} element is item 1 in the list...
- $e=$element->ucAttributes['CALL'][1];
- $add = $e->toVar($e->value);
- if (is_a($add,'PEAR_Error')) {
- return $add;
- }
- return $this->compiler->appendPHP(
- "if (function_exists('_html_template_flexy_compiler_flexy_flexy_'.{$add})) ".
- "call_user_func_array('_html_template_flexy_compiler_flexy_flexy_'.{$add},array(\$t,\$this));");
-
-
-
- }
-
-
-
-
- /**
- /**
- * - A partial is a subtemplate to which you can pass variables.
- * - You can define variables for the partial as xml attributes
- * - You can provide context for the variables by adhering to the
- * convention 'subtemplateVarName="templateVarName"'
- * - See example below:
- *
- * <flexy:partial src="test.html" subtemplateVar1="var1"
- * subtemplateVar2="object.var2" subtemplateVar3="#literal1#" />
- */
- function partialToString($element)
- {
- $src = $element->getAttribute('SRC');
-
- if (!$src) {
- return $this->compiler->appendHTML("<B>Flexy:Subtemplate without a src=filename</B>");
- }
-
- /**
- * Define parameters for partial (if set)
- */
- $aAttribute = $element->getAttributes();
-
-
- if (!is_array($aAttribute)) {
- $aAttribute = array();
- }
-
- $aOutput = array();
-
- foreach ($aAttribute as $name => $value) {
- if ($name == 'src' || $name == '/') {
- continue;
- }
-
- $varName = trim($name);
- $varVal = trim($value);
- $isLiteral = preg_match('@\#(.*)\#@',$varVal);
-
- /**
- * Provide supplied variables with subtemplate context
- * - Deal with string literals (enclosed in # tags - flexy
- * hack/convention).
- * - Variable binding: Look in output object scope first, then
- * template scope.
- */
- if (!$isLiteral) {
- $varVal = str_replace('.','->',trim($value));
- $varVal = '(isset($t->' . $varVal. ')) ? $t->' . $varVal .' : $'. $varVal;
- } else {
- $varVal = preg_replace('@\#(.*)\#@','"\1"',$varVal);
- }
-
- $aOutput[$varName] = $varVal;
- }
-
- $varsOutput = "\n\$oOutput = clone \$t;\n";
-
- foreach ($aOutput as $key=>$val) {
- $varsOutput .= "\$oOutput->{$key} = {$val};\n";
- }
-
-
-
- /**
- * Pass code to compiler
- */
- return $this->compiler->appendPHP (
- "
- \$x = new HTML_Template_Flexy(\$this->options);
- \$x->compile('{$src}');
- {$varsOutput}
- \$x->outputObject(\$oOutput, \$this->elements);
- "
- );
- }
-
-
-
-
-}
-
-
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Alan Knowles <alan@akbkhome> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Tag.php,v 1.1.1.1 2008/04/28 15:20:50 jamie Exp $
-/* FC/BC compatibility with php5 */
-if ( (substr(phpversion(),0,1) < 5) && !function_exists('clone')) {
- eval('function clone($t) { return $t; }');
-}
-
-/**
-* Compiler That deals with standard HTML Tag output.
-* Since it's pretty complex it has it's own class.
-* I guess this class should deal with the main namespace
-* and the parent (standard compiler can redirect other namespaces to other classes.
-*
-* one instance of these exists for each namespace.
-*
-*
-* @version $Id: Tag.php,v 1.1.1.1 2008/04/28 15:20:50 jamie Exp $
-*/
-
-class HTML_Template_Flexy_Compiler_Flexy_Tag
-{
-
-
- /**
- * Parent Compiler for
- *
- * @var object HTML_Template_Flexy_Compiler
- *
- * @access public
- */
- var $compiler;
-
- /**
- *
- * Factory method to create Tag Handlers
- *
- * $type = namespace eg. <flexy:toJavascript loads Flexy.php
- * the default is this... (eg. Tag)
- *
- *
- * @param string Namespace handler for element.
- * @param object HTML_Template_Flexy_Compiler
- *
- *
- * @return object tag compiler
- * @access public
- */
-
- function &factory($type,&$compiler) {
- if (!$type) {
- $type = 'Tag';
- }
-
- $class = 'HTML_Template_Flexy_Compiler_Flexy_' . $type;
- if (class_exists($class)) {
- $ret = new $class;
- $ret->compiler = &$compiler;
- return $ret;
- }
-
- $filename = 'HTML/Template/Flexy/Compiler/Flexy/' . ucfirst(strtolower($type)) . '.php';
- if (!HTML_Template_Flexy_Compiler_Flexy_Tag::fileExistsInPath($filename)) {
- $ret = HTML_Template_Flexy_Compiler_Flexy_Tag::factory('Tag',$compiler);
- return $ret;
- }
- // if we dont have a handler - just use the basic handler.
- if (!file_exists(dirname(__FILE__) . '/'. ucfirst(strtolower($type)) . '.php')) {
- $type = 'Tag';
- }
-
- include_once 'HTML/Template/Flexy/Compiler/Flexy/' . ucfirst(strtolower($type)) . '.php';
-
- $class = 'HTML_Template_Flexy_Compiler_Flexy_' . $type;
- if (!class_exists($class)) {
- $ret = false;
- return $ret;
- }
- $ret = HTML_Template_Flexy_Compiler_Flexy_Tag::factory($type,$compiler);
- return $ret;
- }
- /**
- *
- * Check that a file exists in the "include_path"
- *
- * @param string Filename
- *
- * @return boolean true if it is in there.
- * @access public
- */
- function fileExistsInPath($filename) {
- if (isset($GLOBALS['_'.__CLASS__]['cache'][$filename])) {
- return $GLOBALS['_'.__CLASS__]['cache'][$filename];
- }
- $bits = explode(PATH_SEPARATOR,ini_get('include_path'));
- foreach($bits as $b) {
- if (file_exists("$b/$filename")) {
- return $GLOBALS['_'.__CLASS__]['cache'][$filename] = true;
- }
- }
- return $GLOBALS['_'.__CLASS__]['cache'][$filename] = false;
- }
-
-
-
- /**
- * The current element to parse..
- *
- * @var object
- * @access public
- */
- var $element;
-
- /**
- * Flag to indicate has attribute flexy:foreach (so you cant mix it with flexy:if!)
- *
- * @var boolean
- * @access public
- */
- var $hasForeach = false;
-
- /**
- * toString - display tag, attributes, postfix and any code in attributes.
- * Note first thing it does is call any parseTag Method that exists..
- *
- *
- * @see parent::toString()
- */
- function toString($element)
- {
-
- global $_HTML_TEMPLATE_FLEXY_TOKEN;
- global $_HTML_TEMPLATE_FLEXY;
-
- // store the element in a variable
- $this->element = $element;
- // echo "toString: Line {$this->element->line} <{$this->element->tag}>\n";
-
- // if the FLEXYSTARTCHILDREN flag was set, only do children
- // normally set in BODY tag.
- // this will probably be superseeded by the Class compiler.
-
- if (isset($element->ucAttributes['FLEXY:STARTCHILDREN'])) {
-
- return $element->compileChildren($this->compiler);
- }
- // look for flexy:ignore..
- $flexyignore = $this->parseAttributeIgnore();
-
- // rewriting should be done with a tag.../flag.
-
- $this->reWriteURL("HREF");
- $this->reWriteURL("SRC");
- $this->reWriteURL("BACKGROUND");
-
- // handle elements
- if (($ret =$this->_parseTags()) !== false) {
- return $ret;
- }
- // these add to the close tag..
-
- $ret = $this->parseAttributeForeach();
- $ret .= $this->parseAttributeIf();
-
- // support Custom Attributes...
- require_once 'HTML/Template/Flexy/Compiler/Flexy/CustomFlexyAttributes.php';
- $customFlexyAttributes = new HTML_Template_Flexy_Compiler_Flexy_CustomFlexyAttributes();
- $customFlexyAttributes->doCustomAttributes($element);
-
-
- $add = $this->toStringOpenTag($element,$ret);
-
- if (is_a($add,'PEAR_Error')) {
- return $add;
- }
-
-
-
-
-
- // post stuff this is probably in the wrong place...
-
- if ($element->postfix) {
- foreach ($element->postfix as $e) {
- $add = $e->compile($this->compiler);
- if (is_a($add,'PEAR_Error')) {
- return $add;
- }
- $ret .= $add;
- }
- } else if ($this->element->postfix) { // if postfixed by self..
- foreach ($this->element->postfix as $e) {
- $add = $e->compile($this->compiler);
- if (is_a($add,'PEAR_Error')) {
- return $add;
- }
-
- $ret .= $add;
- }
- }
-
-
- $tmp = $this->toStringChildren($element,$ret);
- if (is_a($tmp,'PEAR_Error')) {
- return $tmp;
- }
- $tmp = $this->toStringCloseTag($element,$ret);
- if (is_a($tmp,'PEAR_Error')) {
- return $tmp;
- }
-
-
- // reset flexyignore
-
- $_HTML_TEMPLATE_FLEXY_TOKEN['flexyIgnore'] = $flexyignore;
-
- if (isset($_HTML_TEMPLATE_FLEXY['currentOptions']['output.block']) &&
- ($_HTML_TEMPLATE_FLEXY['currentOptions']['output.block'] == $element->getAttribute('ID'))) {
-
- // echo $_HTML_TEMPLATE_FLEXY['compiledTemplate'];
-
- $fh = fopen($_HTML_TEMPLATE_FLEXY['compiledTemplate'],'w');
- fwrite($fh,$ret);
- fclose($fh);
-
- }
-
-
-
- return $ret;
- }
-
- /**
- * convert a tag into compiled version
- * @arg object Element
- * @arg inout output string to template
- * @return none? or pear error.
- *
- */
-
- function toStringOpenTag(&$element,&$ret)
- {
- // START ADDITION...
- if ((empty($element->tag)) || (empty($element->oTag))) {
- return;
- }
- // ...END ADDITION
-
-
- // spit ou the tag and attributes.
-
- if ($element->oTag{0} == '?') {
- $ret .= '<?php echo "<"; ?>';
- } else {
- $ret .= "<";
- }
- $ret .= $element->oTag;
- //echo '<PRE>'.print_r($element->attributes,true);
- foreach ($element->attributes as $k=>$v) {
- // if it's a flexy tag ignore it.
-
-
- if (strtoupper($k) == 'FLEXY:RAW') {
- if (!is_array($v) || !isset($v[1]) || !is_object($v[1])) {
- return HTML_Template_Flexy::raiseError(
- 'flexy:raw only accepts a variable or method call as an argument, eg.'.
- ' flexy:raw="{somevalue}" you provided something else.' .
- " Error on Line {$this->element->line} <{$this->element->tag}>",
- null, HTML_TEMPLATE_FLEXY_ERROR_DIE);
- }
- $add = $v[1]->compile($this->compiler);
- if (is_a($add,'PEAR_Error')) {
- return $add;
- }
- $ret .= ' ' . $add;
- continue;
-
- }
-
- if (strtoupper(substr($k,0,6)) == 'FLEXY:') {
- continue;
- }
- // true == an attribute without a ="xxx"
- if ($v === true) {
- $ret .= " $k";
- continue;
- }
-
- // if it's a string just dump it.
- if (is_string($v)) {
- $v = str_replace(array('{_(',')_}'),array('',''),$v);
- $ret .= " {$k}={$v}";
- continue;
- }
-
- // normally the value is an array of string, however
- // if it is an object - then it's a conditional key.
- // eg. if (something) echo ' SELECTED';
- // the object is responsible for adding it's space..
-
- if (is_object($v)) {
- $add = $v->compile($this->compiler);
- if (is_a($add,'PEAR_Error')) {
- return $add;
- }
-
- $ret .= $add;
- continue;
- }
-
- // otherwise its a key="sometext{andsomevars}"
-
- $ret .= " {$k}=";
-
- foreach($v as $item) {
-
- if (is_string($item)) {
- // skip translation strings in tags.
- $item = str_replace(array('{_(',')_}'),array('',''),$item);
- $ret .= $item;
- continue;
- }
- $add = $item->compile($this->compiler);
- if (is_a($add,'PEAR_Error')) {
- return $add;
- }
- $ret .= $add;
- }
- }
- $ret .= ">";
- }
- /**
- * compile children to string.
- * @arg object Element
- * @arg inout output string to template
- * @return none? or pear error.
- */
-
- function toStringChildren(&$element,&$ret)
- {
- // dump contents of script raw - to prevent gettext additions..
- // print_r($element);
- // make sure tag isn't empty because it wouldn't make sense to output script without script tags
- if (((! empty($element->tag)) && ($element->tag == 'SCRIPT'))
- || ((! empty($element->oTag)) && ($element->oTag == 'SCRIPT'))) {
- foreach($element->children as $c) {
- //print_R($c);
- if (!$c) {
- continue;
- }
- if ($c->token == 'Text') {
- $ret .= $c->value;
- continue;
- }
- // techically we shouldnt have anything else inside of script tags.
- // as the tokeinzer is supposted to ignore it..
- }
- return;
- }
- $add = $element->compileChildren($this->compiler);
- if (is_a($add,'PEAR_Error')) {
- return $add;
- }
- $ret .= $add;
-
- }
- /**
- * compile closing tag to string.
- * @arg object Element
- * @arg inout output string to template
- * @return none? or pear error.
- */
-
- function toStringCloseTag(&$element,&$ret)
- {
- // output the closing tag.
- // If the tag is empty don't output closing tags, just output postfixes if any exist...
- if ( !$element->close) {
- return;
- }
-
- if ((! empty($element->tag)) && (! empty($element->oTag)))
- {
- $add = $element->close->compile($this->compiler);
- if (is_a($add,'PEAR_Error')) {
- return $add;
- }
- $ret .= $add;
- return;
- }
- // RICK - added by me
- // element has a seperate closing tag (eg. </something>) and opening and closing tags should be removed
- // because FLEXY:OMITTAG element attribute is set, but still need postfix stuff like for ending ifs and foreach
- // so this is NOT OPTIONAL if foreach and if are not optional.
- if ($element->close->postfix) {
- foreach ($element->close->postfix as $e) {
- $add = $e->compile($this->compiler);
- if (is_a($add,'PEAR_Error')) {
- return $add;
- }
- $ret .= $add;
- }
- return;
- }
- if ($this->element->close->postfix) { // if postfixed by self..
- foreach ($this->element->close->postfix as $e) {
- $add = $e->compile($this->compiler);
- if (is_a($add,'PEAR_Error')) {
- return $add;
- }
-
- $ret .= $add;
- }
- return;
- }
-
- }
-
-
- /**
- * Reads an flexy:foreach attribute -
- *
- *
- * @return string to add to output.
- * @access public
- */
-
- function parseAttributeIgnore()
- {
-
- global $_HTML_TEMPLATE_FLEXY_TOKEN;
-
- $flexyignore = $_HTML_TEMPLATE_FLEXY_TOKEN['flexyIgnore'];
-
- if ($this->element->getAttribute('FLEXY:IGNORE') !== false) {
- $_HTML_TEMPLATE_FLEXY_TOKEN['flexyIgnore'] = true;
- $this->element->clearAttribute('FLEXY:IGNORE');
- }
- return $flexyignore;
-
- }
-
- /**
- * Reads an flexy:foreach attribute -
- *
- *
- * @return string to add to output.
- * @access public
- */
-
- function parseAttributeForeach()
- {
- global $_HTML_TEMPLATE_FLEXY;
- $foreach = $this->element->getAttribute('FLEXY:FOREACH');
- if ($foreach === false) {
- return '';
- }
- //var_dump($foreach);
-
- $this->element->hasForeach = true;
- // create a foreach element to wrap this with.
-
- $foreachObj = $this->element->factory('Foreach',
- explode(',',$foreach),
- $this->element->line);
- // failed = probably not enough variables..
-
-
- if ($foreachObj === false) {
-
- return HTML_Template_Flexy::raiseError(
- "Missing Arguments: An flexy:foreach attribute was foundon Line {$this->element->line}
- in tag <{$this->element->tag} flexy:foreach="$foreach" .....><BR>
- the syntax is <sometag flexy:foreach="onarray,withvariable[,withanothervar] ><BR>",
- null, HTML_TEMPLATE_FLEXY_ERROR_DIE);
- }
-
-
-
- // does it have a closetag?
- if (!$this->element->close) {
-
- if ($this->element->getAttribute('/') === false) {
-
-
- return HTML_Template_Flexy::raiseError(
- "A flexy:foreach attribute was found in <{$this->element->tag} tag without a corresponding </{$this->element->tag}
- tag on {$_HTML_TEMPLATE_FLEXY['filename']}:{$this->element->line} ",
- null, HTML_TEMPLATE_FLEXY_ERROR_DIE);
- }
- // it's an xhtml tag!
- $this->element->postfix = array($this->element->factory("End", '', $this->element->line));
- } else {
- $this->element->close->postfix = array($this->element->factory("End", '', $this->element->line));
- }
-
- $this->element->clearAttribute('FLEXY:FOREACH');
- return $foreachObj->compile($this->compiler);
- }
- /**
- * Reads an flexy:if attribute -
- *
- *
- * @return string to add to output.
- * @access public
- */
-
- function parseAttributeIf()
- {
- // dont use the together, if is depreciated..
- $if = $this->element->getAttribute('FLEXY:IF');
-
- if ($if === false) {
- return '';
- }
-
- if (isset($this->element->hasForeach)) {
- return HTML_Template_Flexy::raiseError(
- "You may not use FOREACH and IF tags in the same tag on Line {$this->element->line} <{$this->element->tag}>",
- null, HTML_TEMPLATE_FLEXY_ERROR_DIE);
- }
-
- // allow if="!somevar"
- $ifnegative = '';
-
- if ($if{0} == '!') {
- $ifnegative = '!';
- $if = substr($if,1);
- }
- // if="xxxxx"
- // if="xxxx.xxxx()" - should create a method prefixed with 'if:'
- // these checks should really be in the if/method class..!!!
-
-
-
- if (!preg_match('/^[_A-Z][A-Z0-9_]*(\[[0-9]+\])?((\[|%5B)[A-Z0-9_]+(\]|%5D))*'.
- '(\.[_A-Z][A-Z0-9_]*((\[|%5B)[A-Z0-9_]+(\]|%5D))*)*(\\([^)]*\))?$/i',$if)) {
- return HTML_Template_Flexy::raiseError(
- "IF tags only accept simple object.variable or object.method() values on
- Line {$this->element->line} <{$this->element->tag}>
- {$if}",
- null, HTML_TEMPLATE_FLEXY_ERROR_DIE);
- }
-
- if (substr($if,-1) == ')') {
- // grab args..
- $args = substr($if,strpos($if,'(')+1,-1);
- // simple explode ...
-
- $args = strlen(trim($args)) ? explode(',',$args) : array();
- //print_R($args);
-
- // this is nasty... - we need to check for quotes = eg. # at beg. & end..
- $args_clean = array();
- for ($i=0; $i<count($args); $i++) {
- if ($args[$i]{0} != '#') {
- $args_clean[] = $args[$i];
- continue;
- }
- // single # - so , must be inside..
- if ((strlen($args[$i]) > 1) && ($args[$i]{strlen($args[$i])-1}=='#')) {
- $args_clean[] = $args[$i];
- continue;
- }
-
- $args[$i] .=',' . $args[$i+1];
- // remove args+1..
- array_splice($args,$i+1,1);
- $i--;
- // reparse..
- }
-
-
-
- $ifObj = $this->element->factory('Method',
- array('if:'.$ifnegative.substr($if,0,strpos($if,'(')), $args_clean),
- $this->element->line);
- } else {
- $ifObj = $this->element->factory('If', $ifnegative.$if, $this->element->line);
- }
-
- // does it have a closetag? - you must have one - so you will have to hack in <span flexy:if=..><img></span> on tags
- // that do not have close tags - it's done this way to try and avoid mistakes.
-
-
- if (!$this->element->close) {
- //echo "<PRE>";print_R($this->element);
-
- if ($this->element->getAttribute('/') !== false) {
- $this->element->postfix = array($this->element->factory("End",'', $this->element->line));
- } else {
-
- return HTML_Template_Flexy::raiseError(
- "An flexy:if attribute was found in <{$this->element->name} tag without a corresponding </{$this->element->name}
- tag on Line {$this->element->line} <{$this->element->tag}>",
- null, HTML_TEMPLATE_FLEXY_ERROR_DIE);
- }
- } else {
-
- $this->element->close->postfix = array($this->element->factory("End",'', $this->element->line));
- }
- $this->element->clearAttribute('FLEXY:IF');
- return $ifObj->compile($this->compiler);
- }
-
- /**
- * Reads Tags - and relays to parseTagXXXXXXX
- *
- *
- * @return string | false = html output or ignore (just output the tag)
- * @access private
- */
-
-
- function _parseTags()
- {
- global $_HTML_TEMPLATE_FLEXY_TOKEN;
- // doesnt really need strtolower etc. as php functions are not case sensitive!
-
-
- /* always render script correctly */
- if (0 == strcasecmp($this->element->tag,"script")) {
- return $this->parseTagScript();
- }
-
- if ($this->element->getAttribute('FLEXY:DYNAMIC')) {
- return $this->compiler->appendPhp(
- $this->getElementPhp( $this->element->getAttribute('ID') )
- );
-
- }
-
- if ($this->element->getAttribute('FLEXY:IGNOREONLY') !== false) {
- return false;
- }
- if ($_HTML_TEMPLATE_FLEXY_TOKEN['flexyIgnore']) {
- return false;
- }
- $tag = $this->element->tag;
- if (strpos($tag,':') !== false) {
- $bits = explode(':',$tag);
- $tag = $bits[1];
- }
-
- if (in_array(strtolower($tag), array('menulist','textbox','checkbox'))) {
- $method = 'parseXulTag';
- } else {
- $method = 'parseTag'.$tag;
- if (!method_exists($this,$method)) {
- return false;
- }
- }
-
- if (($this->element->getAttribute('NAME') === false) &&
- ($this->element->getAttribute('ID') === false) ) {
- return false;
- }
- // do any of the attributes use flexy data...
- //foreach ($this->element->attributes as $k=>$v) {
- // if (is_array($v)) {
- // return false;
- // }
- //}
-
- //echo "call $method" . serialize($this->element->attributes). "\n";
-
- return $this->$method();
- // allow the parse methods to return output.
-
- }
-
-
-
-
- /**
- * produces the code for dynamic elements
- *
- * @return string | false = html output or ignore (just output the tag)
- * @access public
- */
-
- function getElementPhp($id,$mergeWithName=false,$varsOnly = false) {
-
- global $_HTML_TEMPLATE_FLEXY;
- static $tmpId=0;
-
-
-
- if (!$id) {
-
- return HTML_Template_Flexy::raiseError(
- "Error:{$_HTML_TEMPLATE_FLEXY['filename']} on Line {$this->element->line} <{$this->element->tag}>: " .
- " Dynamic tags require an ID value",
- null, HTML_TEMPLATE_FLEXY_ERROR_DIE);
- }
-
- // dont mix and match..
- if (($this->element->getAttribute('FLEXY:IF') !== false) ||
- ($this->element->getAttribute('FLEXY:FOREACH') !== false) )
- {
- return HTML_Template_Flexy::raiseError(
- "Error:{$_HTML_TEMPLATE_FLEXY['filename']} on Line {$this->element->line} <{$this->element->tag}>: " .
- " You can not mix flexy:if= or flexy:foreach= with dynamic form elements " .
- " (turn off tag to element code with flexyIgnore=0, use flexy:ignore="yes" in the tag" .
- " or put the conditional outside in a span tag",
- null, HTML_TEMPLATE_FLEXY_ERROR_DIE);
- }
-
- if ((strtolower($this->element->getAttribute('TYPE')) == 'checkbox' ) &&
- (substr($this->element->getAttribute('NAME'),-2) == '[]')) {
- if ($this->element->getAttribute('ID') === false) {
- $id = 'tmpId'. (++$tmpId);
- $this->element->attributes['id'] = $id;
- $this->element->ucAttributes['ID'] = $id;
- } else {
- $id = $this->element->getAttribute('ID');
- }
- $mergeWithName = true;
- }
-
-
-
-
-
- if (isset($_HTML_TEMPLATE_FLEXY['elements'][$id])) {
- // echo "<PRE>";print_r($this);print_r($_HTML_TEMPLATE_FLEXY['elements']);echo "</PRE>";
- return HTML_Template_Flexy::raiseError(
- "Error:{$_HTML_TEMPLATE_FLEXY['filename']} on Line {$this->element->line} in Tag <{$this->element->tag}>:<BR> " .
- "The Dynamic tag Name '$id' has already been used previously by tag <{$_HTML_TEMPLATE_FLEXY['elements'][$id]->tag}>",
- null,HTML_TEMPLATE_FLEXY_ERROR_DIE);
- }
-
- $ret = '';
- $unset = '';
-
- //echo '<PRE>';print_r($this->element);echo '</PRE>';
- if (isset($this->element->ucAttributes['FLEXY:USE'])) {
- $ar = $this->element->ucAttributes['FLEXY:USE'];
- $str = '';
-
- for($i =1; $i < count($ar) -1; $i++) {
- switch(true) {
- case is_a($ar[$i], 'HTML_Template_Flexy_Token_Var'):
- $str .= '. ' . $ar[$i]->toVar($ar[$i]->value). ' ';
- break;
- case is_string($ar[$i]):
- $str .= '. ' . $ar[0] . $ar[$i] . $ar[0];
- break;
- default:
- return HTML_Template_Flexy::raiseError(
- "unsupported type found in attribute, use flexy:ignore to prevent parsing or remove it. " .
- print_r($this->element,true),
- null,HTML_TEMPLATE_FLEXY_ERROR_DIE);
- }
- }
- $str = trim(ltrim($str,'.'));
- $_HTML_TEMPLATE_FLEXY['elements'][$id] = $this->toElement($this->element);
-
- return $ret .
- '
- if (!isset($this->elements['.$str.'])) {
- echo "ELEMENT MISSING $str";
- }
- echo $this->elements['.$str.']->toHtml();' .$unset;
- }
-
-
-
- if ($this->elementUsesDynamic($this->element)) {
- $used = array();
- foreach ($this->element->attributes as $attribute => $attributeValue) {
- if (!is_array($attributeValue)) {
- continue;
- }
- if (strtoupper(substr($attribute,0,6)) == 'FLEXY:') {
- continue;
- }
- unset($this->element->attributes[$attribute]);
- // generate code to put data into value..
- $output_avar = '$this->elements[\''.$id.'\']->attributes[\''.$attribute.'\']';
- $used[] = "'{$attribute}'";
- $ret .= "\nif (!isset({$output_avar})) {\n";
- // get the " or ' that encapsulates the element.
- $wrapper = array_shift($attributeValue);
- array_pop($attributeValue);
- $ret .= " {$output_avar} = '';\n";
- //echo '<PRE>';print_r($attributeValue);echo '</PRE>';
- foreach($attributeValue as $item) {
-
- if (is_string($item)) {
- $ret .= " {$output_avar} .= {$wrapper}{$item}{$wrapper};\n";
- continue;
- }
- if (!is_object($item) || !is_a($item, 'HTML_Template_Flexy_Token_Var')) {
- return HTML_Template_Flexy::raiseError(
- "unsupported type found in attribute, use flexy:ignore to prevent parsing or remove it. " .
- print_r($this->element,true),
- null,HTML_TEMPLATE_FLEXY_ERROR_DIE);
- }
-
- $var = $item->toVar($item->value);
- if (is_a($var, 'PEAR_Error')) {
- return $var;
- }
- list($prefix,$suffix) = $this->compiler->getModifierWrapper($item);
- $prefix = substr($prefix,4);
-
- $ret .= " {$output_avar} .= {$prefix}{$var}{$suffix};\n";
- }
-
- $ret .= "}\n";
- }
- $ret .= "\$_attributes_used = array(".implode(',',$used).");\n";
- $unset = "\n".'if (isset($_attributes_used)) { foreach($_attributes_used as $_a) {'."\n".
- ' unset($this->elements[\''. $id .'\']->attributes[$_a]);'."\n" .
- "}}\n";
-
-
- }
-
-
-
-
- // this is for a case where you can use a sprintf as the name, and overlay it with a variable element..
- $_HTML_TEMPLATE_FLEXY['elements'][$id] = $this->toElement($this->element);
-
-
-
- if ($varsOnly) { // used by form tag.
- return array($ret,$unset);
- }
-
- if ($var = $this->element->getAttribute('FLEXY:NAMEUSES')) {
- // force var to use name (as radio buttons pick up id.)
-
- $ename = $this->element->getAttribute('NAME');
- $printfnamevar = $printfvar = 'sprintf(\''.$ename .'\','.$this->element->toVar($var) .')';
- // support id replacement as well ...
- $idreplace = '';
-
-
- if (strtolower($this->element->getAttribute('TYPE')) == 'radio') {
- $ename = $this->element->getAttribute('ID');
- $printfvar = 'sprintf(\''.$ename .'\','.$this->element->toVar($var) .')';
- }
-
-
- if ($this->element->getAttribute('ID')) {
- $idvar = 'sprintf(\''.$this->element->getAttribute('ID') .'\','.$this->element->toVar($var) .')';
- $idreplace = '$this->elements['.$printfvar.']->attributes[\'id\'] = '.$idvar.';';
- }
- return $ret . '
- if (!isset($this->elements['.$printfvar.'])) {
- $this->elements['.$printfvar.']= $this->elements[\''.$id.'\'];
- }
- $this->elements['.$printfvar.'] = $this->mergeElement(
- $this->elements[\''.$id.'\'],
- $this->elements['.$printfnamevar .']
- );
- $this->elements['.$printfvar.']->attributes[\'name\'] = '.$printfnamevar. ';
- ' . $idreplace . '
- echo $this->elements['.$printfvar.']->toHtml();' .$unset;
- }
-
-
- if ($mergeWithName) {
- $name = $this->element->getAttribute('NAME');
- //if ((strtolower($this->element->getAttribute('TYPE')) == 'checkbox') && (substr($name,-2) == '[]')) {
- // $name = substr($name,0,-2);
- //}
- return $ret .
- '
- $element = $this->elements[\''.$id.'\'];
- if (isset($this->elements[\''.$name.'\'])) {
- $element = $this->mergeElement($element,$this->elements[\''.$name.'\']);
- }
- echo $element->toHtml();' . $unset;
-
- }
- return $ret . 'echo $this->elements[\''.$id.'\']->toHtml();'. $unset;
-
- }
-
- /**
- * Reads an Script tag - check if PHP is allowed.
- *
- * @return false|PEAR_Error
- * @access public
- */
- function parseTagScript()
- {
-
-
- $lang = $this->element->getAttribute('LANGUAGE');
- if (!$lang) {
- return false;
- }
- $lang = strtoupper($lang);
- $allow = $GLOBALS['_HTML_TEMPLATE_FLEXY']['currentOptions']['allowPHP'];
-
- if ($allow === true) {
-
- return false;
- }
-
- if ($lang == "PHP") {
- if ($allow == 'delete') {
- return '';
- }
- return HTML_Template_Flexy::raiseError('PHP code found in script (script)',
- HTML_TEMPLATE_FLEXY_ERROR_SYNTAX,HTML_TEMPLATE_FLEXY_ERROR_RETURN
- );
- }
- return false;
-
- }
- /**
- * Reads an Input tag - build a element object for it
- *
- *
- * @return string | false = html output or ignore (just output the tag)
- * @access public
- */
-
-
- function parseTagInput()
- {
- global $_HTML_TEMPLATE_FLEXY;
-
- if (in_array(strtoupper($this->element->getAttribute('TYPE')), array('SUBMIT','BUTTON','INPUT',''))) {
- $this->compiler->addStringToGettext($this->element->getAttribute('VALUE'));
- }
- // form elements : format:
- //value - fill out as PHP CODE
-
- // as a general rule, this uses name, rather than ID except on
- // radio
- $mergeWithName = false;
- $id = $this->element->getAttribute('NAME');
-
-
- if (isset($this->element->ucAttributes['FLEXY:RAW'])) {
- return HTML_Template_Flexy::raiseError(
- "Error:{$_HTML_TEMPLATE_FLEXY['filename']} on Line {$this->element->line} ".
- "in Tag <{$this->element->tag}>:<BR>".
- "Flexy:raw can only be used with flexy:ignore, to prevent conversion of html ".
- "elements to flexy elements",
- null, HTML_TEMPLATE_FLEXY_ERROR_DIE
- );
- }
- // checkboxes need more work.. - at the momemnt assume one with the same value...
- if (!in_array(strtoupper($this->element->getAttribute('TYPE')), array('RADIO'))) {
- if (!$id) {
- return false;
- }
- return $this->compiler->appendPhp($this->getElementPhp( $id,$mergeWithName));
-
- }
- // now we are only dealing with radio buttons.. which are a bit odd...
-
- // we need to create a generic holder for this based on the name..
- // this is only really available for use with setting stuff...
-
- if (!isset($_HTML_TEMPLATE_FLEXY['elements'][$id])) {
- $_HTML_TEMPLATE_FLEXY['elements'][$id] = new HTML_Template_Flexy_Element("input",
- array('type'=>'radio'));
-
- }
- // we dont really care if it is getting reused loads of times.. (expected as each radio button will use it.
- $name = $id;
- $id = $this->element->getAttribute('ID');
- if (!$id) {
- $id = $name . '_' . $this->element->getAttribute('VALUE');
- }
- // this get's tricky as we could end up with elements with the same name... (if value was not set..,
- // or two elements have the same name..
-
- $mergeWithName = true;
-
- return $this->compiler->appendPhp($this->getElementPhp( $id,$mergeWithName));
-
- }
-
- /**
- * Deal with a TextArea tag - build a element object for it
- *
- * @return string | false = html output or ignore (just output the tag)
- * @access public
- */
-
- function parseTagTextArea()
- {
-
- return $this->compiler->appendPhp(
- $this->getElementPhp( $this->element->getAttribute('NAME')));
-
-
-
- }
- /**
- * Deal with Selects - build a element object for it (unless flexyignore is set)
- *
- *
- * @return string | false = html output or ignore (just output the tag)
- * @access public
- */
-
- function parseTagSelect()
- {
- return $this->compiler->appendPhp(
- $this->getElementPhp( $this->element->getAttribute('NAME')));
- }
-
-
-
-
- /**
- * Reads an Form tag - and set up the element object header etc.
- *
- * @return string | false = html output or ignore (just output the tag)
- * @access public
- */
-
- function parseTagForm()
- {
- global $_HTML_TEMPLATE_FLEXY;
- $copy = clone($this->element);
- $copy->children = array();
- $id = $this->element->getAttribute('NAME');
- // dont make forms dynamic if they dont have a name..
- if (!$id) {
- return false;
- }
-
- // this adds the element to the elements array.
- $old = clone($this->element);
- $this->element = $copy;
- list($prefix,$suffix) = $this->getElementPhp($id,false,true);
- $this->element= $old;
-
-
- return
- $this->compiler->appendPhp($prefix .'echo $this->elements[\''.$id.'\']->toHtmlnoClose();'.$suffix) .
- $this->element->compileChildren($this->compiler) .
- $this->compiler->appendHtml( "</{$copy->oTag}>");
-
- }
-
-
-
-
-
- /**
- * reWriteURL - can using the config option 'url_rewrite'
- * format "from:to,from:to"
- * only handle left rewrite.
- * so
- * "/images:/myroot/images"
- * would change
- * /images/xyz.gif to /myroot/images/xyz.gif
- * /images/stylesheet/imagestyles.css to /myroot/images/stylesheet/imagestyles.css
- * note /imagestyles did not get altered.
- * will only work on strings (forget about doing /images/{someimage}
- *
- *
- * @param string attribute to rewrite
- * @return none
- * @access public
- */
- function reWriteURL($which)
- {
- global $_HTML_TEMPLATE_FLEXY;
-
-
- if (!is_string($original = $this->element->getAttribute($which))) {
- return;
- }
-
- if ($original == '') {
- return;
- }
-
- if (empty($_HTML_TEMPLATE_FLEXY['currentOptions']['url_rewrite'])) {
- return;
- }
-
- $bits = explode(",",$_HTML_TEMPLATE_FLEXY['currentOptions']['url_rewrite']);
- $new = $original;
-
- foreach ($bits as $bit) {
- if (!strlen(trim($bit))) {
- continue;
- }
- $parts = explode (':', $bit);
- if (!isset($parts[1])) {
- return HTML_Template_Flexy::raiseError('HTML_Template_Flexy: url_rewrite syntax incorrect'.
- print_r(array($bits,$bits),true),null,HTML_TEMPLATE_FLEXY_ERROR_DIE);
- }
- $new = preg_replace('#^'.$parts[0].'#',$parts[1], $new);
- }
-
-
- if ($original == $new) {
- return;
- }
- $this->element->ucAttributes[$which] = '"'. $new . '"';
- }
-
- /**
- * Convert flexy tokens to HTML_Template_Flexy_Elements.
- *
- * @param object token to convert into a element.
- * @return object HTML_Template_Flexy_Element
- * @access public
- */
- function toElement($element,$stripspaces = false)
- {
- require_once 'HTML/Template/Flexy/Element.php';
- $ret = new HTML_Template_Flexy_Element;
-
-
- if (strtolower(get_class($element)) != 'html_template_flexy_token_tag') {
- $this->compiler->addStringToGettext($element->value);
- return $element->value;
- }
-
-
- $ret->tag = strtolower($element->tag);
-
- if ($ret->tag == 'menulist') { // for XUL menulist, remove the white space between tags..
- $stripspaces = true;
- }
-
- $ats = $element->getAttributes();
-
- if (isset($element->attributes['flexy:xhtml'])) {
- $ats['flexy:xhtml'] = true;
- }
-
- foreach(array_keys($ats) as $a) {
- $ret->attributes[$a] = $this->unHtmlEntities($ats[$a]);
- }
- //print_r($ats);
- if (!$element->children) {
- return $ret;
- }
-
- // children - normally to deal with <element>
-
- //print_r($this->children);
- foreach(array_keys($element->children) as $i) {
- // not quite sure why this happens - but it does.
- if (!is_object($element->children[$i])) {
- continue;
- }
- if ($stripspaces && (strtolower(get_class($element->children[$i])) != 'html_template_flexy_token_tag')) {
- continue;
- }
- $ret->children[] = $this->toElement($element->children[$i],$stripspaces);
- }
- return $ret;
- }
-
- /**
- * do the reverse of htmlspecialchars on an attribute..
- *
- * copied from get-html-translation-table man page
- *
- * @param mixed from attribute values
- *
- * @return string return
- * @access public
- * @see see also methods.....
- */
-
- function unHtmlEntities ($in)
- {
- if (!is_string($in)) {
- return $in;
- }
- $trans_tbl = get_html_translation_table (HTML_ENTITIES);
- $trans_tbl = array_flip ($trans_tbl);
- $ret = strtr ($in, $trans_tbl);
- return preg_replace('/&#(\d+);/me', "chr('\\1')",$ret);
- }
-
-
- /**
- * Deal with XUL tags
- *
- * @return string | false = html output or ignore (just output the tag)
- * @access public
- */
-
- function parseXulTag()
- {
-
- // does it contain any flexy tags??
- if ($this->elementUsesDynamic($this->element)) {
- return false;
- }
-
- return $this->compiler->appendPhp(
- $this->getElementPhp( $this->element->getAttribute('ID')));
- }
-
- /**
- * Recursively search for any flexy:if flexy:foreach or {xxxx} tags inside tags..
- *
- * @param HTML_Template_Flexy_Token element to check.
- * @return boolean true if it finds a dynamic tag.
- * @access public
- */
-
-
- function elementUsesDynamic($e)
- {
- if (is_a($e,'HTML_Template_Flexy_Token_Var')) {
- return true;
- }
- if (is_a($e,'HTML_Template_Flexy_Token_Foreach')) {
- return true;
- }
- if (is_a($e,'HTML_Template_Flexy_Token_If')) {
- return true;
- }
- if (is_a($e,'HTML_Template_Flexy_Token_Method')) {
- return true;
- }
- if (!is_a($e,'HTML_Template_Flexy_Token_Tag')) {
- return false;
- }
- if ($e->getAttribute('FLEXY:IF') !== false) {
- return true;
- }
- if ($e->getAttribute('FLEXY:FOREACH') !== false) {
- return true;
- }
- foreach($e->attributes as $k=>$v) {
- if (is_array($v) || is_object($v)) {
- return true;
- }
- }
- foreach($e->children as $c) {
- if ($this->elementUsesDynamic($c)) {
- return true;
- }
- }
- return false;
-
-
-
- }
-
-
-
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-class HTML_Template_Flexy_Compiler_Regex {
-
- /**
- * The main flexy engine
- *
- * @var object HTML_Template_Flexy
- * @access public
- */
-
- var $flexy;
- /**
- * classicParse - the older regex based code generator.
- * here all the replacing, filtering and writing of the compiled file is done
- * well this is not much work, but still its in here :-)
- *
- * @access private
- * @version 01/12/03
- * @author Wolfram Kriesing <wolfram@kriesing.de>
- * @author Alan Knowles <alan@akbkhome.com>
- * @return boolean (basically true all the time here)
- */
- function compile(&$flexy)
- {
- $this->flexy = &$flexy;
- // read the entire file into one variable
- $fileContent = file_get_contents($flexy->currentTemplate);
-
- // apply pre filter
- $fileContent = $this->applyFilters( $fileContent , "/^pre_/i" );
- $fileContent = $this->applyFilters( $fileContent , "/^(pre_|post_)/i",TRUE);
- $fileContent = $this->applyFilters( $fileContent , "/^post_/i" );
- // write the compiled template into the compiledTemplate-File
- if( ($cfp = fopen( $flexy->compiledTemplate , 'w' )) ) {
- fwrite($cfp,$fileContent);
- fclose($cfp);
- @chmod($flexy->compiledTemplate,0775);
- }
-
- return true;
- }
- /**
- * actually it will only be used to apply the pre and post filters
- *
- * @access public
- * @version 01/12/10
- * @author Alan Knowles <alan@akbkhome.com>
- * @param string $input the string to filter
- * @param array $prefix the subset of methods to use.
- * @return string the filtered string
- */
- function applyFilters( $input , $prefix = "",$negate=FALSE)
- {
- $this->flexy->debug("APPLY FILTER $prefix<BR>");
- $filters = $this->options['filters'];
- $this->flexy->debug(serialize($filters)."<BR>");
- foreach($filters as $filtername) {
- $class = "HTML_Template_Flexy_Compiler_Regex_{$filtername}";
- require_once("HTML/Template/Flexy/Compiler/Regex/{$filtername}.php");
-
- if (!class_exists($class)) {
- return HTML_Template_Flexy::raiseError("Failed to load filter $filter",null,HTML_TEMPLATE_FLEXY_ERROR_DIE);
- }
-
- if (!@$this->filter_objects[$class]) {
- $this->filter_objects[$class] = new $class;
- $this->filter_objects[$class]->_set_engine($this);
- }
- $filter = &$this->filter_objects[$class];
- $methods = get_class_methods($class);
- $this->flexy->debug("METHODS:");
- $this->flexy->debug(serialize($methods)."<BR>");
- foreach($methods as $method) {
- if ($method{0} == "_") {
- continue; // private
- }
- if ($method == $class) {
- continue; // constructor
- }
- $this->flexy->debug("TEST: $negate $prefix : $method");
- if ($negate && preg_match($prefix,$method)) {
- continue;
- }
- if (!$negate && !preg_match($prefix,$method)) {
- continue;
- }
-
- $this->flexy->debug("APPLYING $filtername $method<BR>");
- $input = $filter->$method($input);
- }
- }
-
- return $input;
- }
-}
-
-
+++ /dev/null
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Alan Knowles <alan@akbkhome.com>
-// +----------------------------------------------------------------------+
-//
-
-
-/**
-* The html Body only filter
-*
-* @abstract
-* a Simple filter to remove the everything thats not in the body!
-*
-* @package HTML_Template_Flexy
-*
-*/
-
-
-class HTML_Template_Flexy_Compiler_Regex_BodyOnly
-{
-
- /**
- * Standard Set Engine
- *
- *
- * @param object HTML_Template_Flexy the main engine
- * @access private
- */
-
- function _set_engine(&$engine)
- {
- }
- /**
- * Strip everything before and including the BODY tag
- *
- * @param string The template
- * @access public
- */
-
- function strip_body_head ($input)
- {
- if (!preg_match("/^(.*)<body/si", $input)) {
- return $input;
- }
- $input = preg_replace("/^(.*)<body/si", "",$input);
- $input = preg_replace("/^([^>]*)>/si", "",$input);
- return $input;
- }
- /**
- * Strip everything after and including the end BODY tag
- *
- * @param string The template
- * @access public
- */
- function strip_body_foot ($input)
- {
- if (!preg_match("/<\/body>.*/si", $input)) {
- return $input;
- }
- $input = preg_replace("/<\/body>.*/si", "",$input);
- return $input;
-
-
- }
-
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Alan Knowles <alan@akbkhome.com>
-// +----------------------------------------------------------------------+
-//
-
-
-/**
-* The Mail filter template (sorts out cr removal in php)
-*
-*
-* @package HTML_Template_Flexy
-*
-*
-*
-*/
-
-class HTML_Template_Flexy_Compiler_Regex_Mail {
- /**
- * Standard Set Engine
- *
- *
- * @param object HTML_Template_Flexy the main engine
- * @access private
- */
- function _set_engine(&$engine)
- {
- }
- /*
- * add an extra cr to the end php tag, so it show correctly in Emails
- *
- * @param string The template
- * @access public
- */
-
- function post_fix_php_cr ($input)
- {
- $input = str_replace("?>\n","?>\n\n",$input);
- return str_replace("?>\r\n","?>\r\n\r\n",$input);
- }
-
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Alan Knowles <alan@akbkhome.com>
-// +----------------------------------------------------------------------+
-//
-
-
-/**
-* A Math Filter
-*
-* enable simple maths to be done in the template
-*
-* TODO: add an {if:t.xxx%2} type syntax..
-*
-* @package HTML_Template_Flexy
-*
-*/
-
-
-class HTML_Template_Flexy_Compiler_Regex_Math {
- /*
- * @var string $start the start tag for the template (escaped for regex)
- */
- var $start = '\{';
- /*
- * @var string $stop the stopt tag for the template (escaped for regex)
- */
- var $stop = '\}'; //ending template tag
- /**
- * Standard Set Engine
- *
- *
- * @param object HTML_Template_Flexy the main engine
- * @access private
- */
- function _set_engine(&$engine) {
-
- }
-
- /*
- * allow simple add multiply, divide and subtraction
- *
- * eg.
- * {(12+t.somevar)*2} maps to =(12+$t->somevar)*2
- *
- * @param string The template
- * @access public
- */
- function variables ($input) {
- $input = preg_replace(
- "/".$this->start."([0-9\(\)+*\/-]*)([a-z0-9]+)([0-9\(\)+*\/-]*)".$this->stop."/ie",
- "'<?=\\1($'.str_replace('.','->','\\2').')\\3?>'",
- $input);
-
- return $input;
- }
-
-
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Alan Knowles <alan@akbkhome.com>
-// +----------------------------------------------------------------------+
-//
-
-
-/**
-* Remove PHP tags and replace them with echo '< ? '
-*
-* should be the first filter if you use it
-*
-*
-*
-* @package HTML_Template_Flexy
-*
-*/
-class HTML_Template_Flexy_Compiler_Regex_Php
-{
- /**
- * Standard Set Engine
- *
- *
- * @param object HTML_Template_Flexy the main engine
- * @access private
- */
- function _set_engine(&$engine)
- {
- }
- /*
- * replace the php tags
- *
- * @param string The template
- * @access public
- */
- function pre_strip_php ($input)
- {
- $input = str_replace("<?","__{<__?}__",$input);
- $input = str_replace("?>","<?php echo '?'.'>'; ?>",$input);
- return str_replace("__{<__?}__","<?php echo '<'.'>'; ?>",$input);
- }
-
-
-}
-
-?>
+++ /dev/null
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Alan Knowles <alan@akbkhome.com>
-// +----------------------------------------------------------------------+
-//
-
-
-/**
-* The rtf SimpleTags filter
-*
-* really an extension of simple tags with \\\{ and \\\\} as the tag delimiters
-* can parse an RTF template and generate a file.
-*
-* usually best used with callback ouput buffering to reduce memory loads.
-*
-* @package HTML_Template_Flexy
-*
-*/
-
-
-require_once "HTML/Template/Flexy/Filter/SimpleTags.php";
-
-class HTML_Template_Flexy_Compiler_Regex_RtfSimpleTags extends HTML_Template_Flexy_Compiler_Regex_simpletags
-{
- /*
- * @var string $start the start tag for the template (escaped for regex)
- */
- var $start = '\\\{';
- /*
- * @var string $stop the stopt tag for the template (escaped for regex)
- */
- var $stop= '\\\}';
-
-
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Alan Knowles <alan@akbkhome.com>
-// +----------------------------------------------------------------------+
-//
-
-
-/**
-* The Standard Tag filter
-*
-* @abstract
-* does all the clever stuff...
-*
-* Security Notes:
-* Templates should not originate from untrusted sources,
-* - the method(#.....#) could be regarded as insecure.
-* - there is no attempt to protect your from <script / <?php in templates.
-*
-* @package HTML_Template_Flexy
-*
-*/
-
-
-class HTML_Template_Flexy_Compiler_Regex_SimpleTags
-{
- /*
- * @var object HTML_Template_Flexy the main engine
- */
- var $engine; // the engine (with options)
- /*
- * @var string $start the start tag for the template (escaped for regex)
- */
- var $start = '\{';
-
- /*
- * @var string $stop the stopt tag for the template (escaped for regex)
- */
- var $stop = '\}';
- /*
- * @var string $error show/hide the PHP error messages on/off in templates
- */
- var $error = "@"; // change to blank to debug errors.
- /**
- * Standard Set Engine
- *
- *
- * @param object HTML_Template_Flexy the main engine
- * @access private
- */
- function _set_engine(&$engine) {
- $this->engine = &$engine;
- if ($this->engine->options['debug']) {
- $this->error = "";
- }
- }
-
-
-
- /**
- * Standard Variable replacement
- *
- *
- * Maps variables
- * {i.xyz} maps to <?php echo htmlspecialchars($i->xyz)?>
- * {i.xyz:h} maps to <?php echo $i->xyz?>
- * {i.xyz:u} maps to <?php echo urlencode($i->xyz)?>
- * {i.xyz:ru} maps to <?php echo rawurlencode($i->xyz)?>
- *
- * {i.xyz:r} maps to <PRE><?php echo print_r($i->xyz)?></PRE>
- * {i.xyz:n} maps to <?php echo nl2br(htmlspecialchars($i->xyz))?>
- *
- *
- * @param string $input the template
- * @return string the result of the filtering
- * @access public
- */
-
-
-
- function variables ($input) {
- $input = preg_replace(
- "/".$this->start."([a-z0-9_.]+)".$this->stop."/ie",
- "'<?php echo htmlspecialchars(".$this->error."$'.str_replace('.','->','\\1').')?>'",
- $input);
-
-
- $input = preg_replace(
- "/".$this->start."([a-z0-9_.]+):h".$this->stop."/ie",
- "'<?php echo ".$this->error."$'.str_replace('.','->','\\1').'?>'",
- $input);
-
- $input = preg_replace(
- "/".$this->start."([a-z0-9_.]+):u".$this->stop."/ie",
- "'<?php echo urlencode(".$this->error."$'.str_replace('.','->','\\1').')?>'",
- $input);
-
- $input = preg_replace(
- "/".$this->start."([a-z0-9_.]+):ru".$this->stop."/ie",
- "'<?php echo rawurlencode(".$this->error."$'.str_replace('.','->','\\1').')?>'",
- $input);
-
- $input = preg_replace(
- "/".$this->start."([a-z0-9_.]+):r".$this->stop."/ie",
- "'<PRE><?php echo print_r($'.str_replace('.','->','\\1').')?></PRE>'",
- $input);
-
- $input = preg_replace(
- "/".$this->start."([a-z0-9_.]+):n".$this->stop."/ie",
- "'<?php echo nl2br(htmlspecialchars(".$this->error."$'.str_replace('.','->','\\1').'))?>'",
- $input);
- return $input;
-
- }
- /**
- * Urlencoded Variable replacement
- *
- * Often when you use a WYSISYG editor, it replaces { in
- * the href="{somevar}" with the urlencoded version, this bit fixes it.
- *
- * Maps variables
- * %??i.xyz%?? maps to <?php echo htmlspecialchars($i->xyz)?>
- * %??i.xyz:h%?? maps to <?php echo $i->xyz?>
- * %??i.xyz:u%?? maps to <?php echo urlencode($i->xyz)?>
- * %??i.xyz:ru%?? maps to <?php echo urlencode($i->xyz)?>
- * THIS IS PROBABLY THE ONE TO USE!
- *
- * %??i.xyz:uu%?? maps to <?php echo urlencode(urlencode($i->xyz))?>
- *
- *
- * @param string $input the template
- * @return string the result of the filtering
- * @access public
- */
-
- function urlencoded_variables ($input) {
- $input = preg_replace(
- "/".urlencode(stripslashes($this->start))."([a-z0-9_.]+)".urlencode(stripslashes($this->stop))."/ie",
- "'<?php echo htmlspecialchars(".$this->error."$'.str_replace('.','->','\\1').')?>'",
- $input);
-
-
- $input = preg_replace(
- "/".urlencode(stripslashes($this->start))."([a-z0-9_.]+):h".urlencode(stripslashes($this->stop))."/ie",
- "'<?php echo ".$this->error."$'.str_replace('.','->','\\1').'?>'",
- $input);
-
- $input = preg_replace(
- "/".urlencode(stripslashes($this->start))."([a-z0-9_.]+):u".urlencode(stripslashes($this->stop))."/ie",
- "'<?php echo urlencode(".$this->error."$'.str_replace('.','->','\\1').')?>'",
- $input);
-
- $input = preg_replace(
- "/".urlencode(stripslashes($this->start))."([a-z0-9_.]+):uu".urlencode(stripslashes($this->stop))."/ie",
- "'<?php echo urlencode(urlencode(".$this->error."$'.str_replace('.','->','\\1').'))?>'",
- $input);
- return $input;
- }
- /**
- * Calling Methods
- *
- * This allows you to call methods of your application
- *
- * Maps Methods
- * {t.xxxx_xxxx()} maps to <?php echo htmlspecialchars($t->xxxx_xxxx())?>
- * {t.xxxx_xxxx():h} maps to <?php echo $t->xxxx_xxxx()?>
- *
- * {t.xxxx_xxxx(sssss.dddd)} maps to <?php echo htmlspecialchars($t->xxxx_xxxx($ssss->dddd))?>
- * {t.xxxx_xxxx(sssss.dddd):h} maps to <?php echo $t->xxxx_xxxx($ssss->dddd)?>
- * {t.xxxx_xxxx(sssss.dddd):s} maps to <?php highlight_string($t->xxxx_xxxx($ssss->dddd))?>
- *
- * {t.xxxx_xxxx(#XXXXX#)} maps to <?php echo htmlspecialchars($t->xxxx_xxxx('XXXXXX'))?>
- * {t.xxxx_xxxx(#XXXXX#):h} maps to <?php echo $t->xxxx_xxxx('XXXXXX')?>
- *
- * {t.xxxx_xxxx(sss.ddd,sss.ddd)} maps to <?php echo htmlspecialchars($t->xxxx_xxxx($sss->ddd,$sss->ddd))?>
- * {t.xxxx_xxxx(#aaaa#,sss.ddd)} maps to <?php echo htmlspecialchars($t->xxxx_xxxx("aaaa",$sss->ddd))?>
- * {t.xxxx_xxxx(sss.ddd,#aaaa#)} maps to <?php echo htmlspecialchars($t->xxxx_xxxx($sss->ddd,"aaaa"))?>
- *
- *
- *
- * @param string $input the template
- * @return string the result of the filtering
- * @access public
- */
-
-
-
-
-
- function methods($input) {
-
- /* no vars */
- $input = preg_replace(
- "/".$this->start."([a-z0-9_.]+)\(\)".$this->stop."/ie",
- "'<?php echo htmlspecialchars(".$this->error."$'.str_replace('.','->','\\1').'())?>'",
- $input);
-
- $input = preg_replace(
- "/".$this->start."([a-z0-9_.]+)\(\):h".$this->stop."/ie",
- "'<?php echo ".$this->error."$'.str_replace('.','->','\\1').'()?>'",
- $input);
- /* single vars */
- $input = preg_replace(
- "/".$this->start."([a-z0-9_.]+)\(([a-z0-9_.]+)\)".$this->stop."/ie",
- "'<?php echo htmlspecialchars(".$this->error."$'.str_replace('.','->','\\1').'($' . str_replace('.','->','\\2') . '))?>'",
- $input);
-
- $input = preg_replace(
- "/".$this->start."([a-z0-9_.]+)\(([a-z0-9_.]+)\):h".$this->stop."/ie",
- "'<?php echo ".$this->error."$'.str_replace('.','->','\\1').'($' . str_replace('.','->','\\2') . ')?>'",
- $input);
- $input = preg_replace(
- "/".$this->start."([a-z0-9_.]+)\(([a-z0-9_.]+)\):s".$this->stop."/ie",
- "'<?php highlight_string($'.str_replace('.','->','\\1').'($' . str_replace('.','->','\\2') . '));?>'",
- $input);
- /* double vars */
- $input = preg_replace(
- "/".$this->start."([a-z0-9_.]+)\(([a-z0-9_.]+),([a-z0-9_.]+)\)".$this->stop."/ie",
- "'<?php echo htmlspecialchars(".$this->error."$'.str_replace('.','->','\\1').'($' . str_replace('.','->','\\2') . ',$' . str_replace('.','->','\\3') . '))?>'",
- $input);
- /* double vars:: # #'d ,var */
- $input = preg_replace(
- "/".$this->start."([a-z0-9_.]+)\(\#([^\#]+)\#,([a-z0-9_.]+)\)".$this->stop."/ie",
- "'<?php echo htmlspecialchars(".$this->error."$'.str_replace('.','->','\\1').'(\''. str_replace(\"'\",\"\\\'\",'\\2') . '\',$' . str_replace('.','->','\\3') . '))?>'",
- $input);
- /* double vars:: var , # #'d */
- $input = preg_replace(
- "/".$this->start."([a-z0-9_.]+)\(([a-z0-9_.]+),\#([^\#]+)\#\)".$this->stop."/ie",
- "'<?php echo htmlspecialchars(".$this->error."$'.str_replace('.','->','\\1').'($' . str_replace('.','->','\\2') . ',\''. str_replace(\"'\",\"\\\'\",'\\3') . '\'))?>'",
- $input);
-
- /*strings or integers */
- $input = preg_replace(
- "/".$this->start."([a-z0-9_.]+)\(\#([^\#]+)\#\)".$this->stop."/ie",
- "'<?php echo htmlspecialchars(\$'.str_replace('.','->','\\1') . '(\''. str_replace(\"'\",\"\\\'\",'\\2') . '\'))?>'",
- $input);
-
- $input = preg_replace(
- "/".$this->start."([a-z0-9_.]+)\(\#([^\#]+)\#\):h".$this->stop."/ie",
- "'<?php echo ".$this->error."$'.str_replace('.','->','\\1').'(\"' . str_replace(\"'\",\"\\\'\",'\\2') . '\")?>'",
- $input);
-
- return $input;
- }
- /**
- * Looping
- *
- * This allows you to do loops on variables (eg. nested/ repeated blocks!)
- *
- * Maps Methods
- * {foreach:t.xyz,zzz} maps to <?php if ($i->xyz) foreach ($t->xyz as $zzz) { ?>
- * {foreach:t.xyz,xxx,zzz} maps to <?php if ($i->xyz) foreach ($t->xyz as $xxx=>$zzz) { ?>
- * {end:} maps to <?php }?>
- * {else:} maps to <?php }else{?>
- *
- *
- *
- * @param string $input the template
- * @return string the result of the filtering
- * @access public
- */
-
-
- function looping($input) {
-
-
- $input = preg_replace(
- "/".$this->start."foreach:([a-z0-9_.]+),([a-z0-9_.]+)".$this->stop."/ie",
- "'<?php if (".$this->error."$' . str_replace('.','->','\\1') . ') foreach( $' . str_replace('.','->','\\1') . ' as $' . str_replace('.','->','\\2') . ') { ?>'",
- $input);
- $input = preg_replace(
- "/".$this->start."foreach:([a-z0-9_.]+),([a-z0-9_.]+),([a-z0-9_.]+)".$this->stop."/ie",
- "'<?php if (".$this->error."$' . str_replace('.','->','\\1') . ') foreach( $' . str_replace('.','->','\\1') . ' as $' . str_replace('.','->','\\2') . '=>$' . str_replace('.','->','\\3') .') { ?>'",
- $input);
-
- $input = str_replace(stripslashes($this->start)."else:".stripslashes($this->stop),'<?php }else{?>', $input);
- $input = str_replace(stripslashes($this->start)."end:".stripslashes($this->stop),'<?php }?>', $input);
- return $input;
- }
- /**
- * Conditional inclusion
- *
- * This allows you to do conditional inclusion (eg. blocks!)
- *
- * Maps conditions
- *
- * {if:t.xxxx} => <?php if ($t->xxxx) { ?>
- * {if:t.x_xxx()} => <?php if ($t->x_xxx()) { ?>
- *
- * @param string $input the template
- * @return string the result of the filtering
- * @access public
- */
-
- function conditionals($input) {
-
- $input = preg_replace(
- "/".$this->start."if:([a-z0-9_.]+)".$this->stop."/ie",
- "'<?php if (".$this->error."$' . str_replace('.','->','\\1') . ') { ?>'",
- $input);
-
- $input = preg_replace(
- "/".$this->start."if:([a-z0-9_.]+)\(\)".$this->stop."/ie",
- "'<?php if (".$this->error."$' . str_replace('.','->','\\1') . '()) { ?>'",
- $input);
-
- return $input;
- }
- /**
- * sub template inclusion
- *
- * This allows you to do include other files (either flat or generated templates.).
- *
- * {include:t.abcdef} maps to <?php
- * if($t->abcdef && file_exists($compileDir . "/". $t->abcdef . "en.php"))
- * include($compileDir . "/". $t->abcdef . ".en.php");
- * ?>
- *
- * include abcdef.en.php (Eg. hard coded compiled template
- * {include:#abcdef#} => <?php
- * if(file_exists($compileDir . "/abcdef.en.php"))
- * include($compileDir . "/abcdef.en.php");
- * ?>
- *
- * include raw
- * {t_include:#abcdef.html#} => <?php
- * if(file_exists($templateDir . "/abcdef.html"))
- * include($compileDir . "/abcdef.html");
- * ?>
- * Compile and include
- * {q_include:#abcdef.html#} => <?php
- * HTML_Template_Flexy::staticQuickTemplate('abcedef.html',$t);
- * ?>
- *
- *
- * @param string $input the template
- * @return string the result of the filtering
- * @access public
- */
-
- function include_template($input) {
-
- $input = preg_replace(
- "/".$this->start."include:([a-z0-9_.]+)".$this->stop."/ie",
- "'<?php
- if ((".$this->error."$' . str_replace('.','->','\\1') . ') &&
- file_exists(\"" . $this->engine->options['compileDir'] .
- "/\{$' . str_replace('.','->','\\1') . '}.en.php\"))
- include(\"" . $this->engine->options['compileDir'] .
- "/\{$' . str_replace('.','->','\\1') . '}.en.php\");?>'",
- $input);
-
- $input = preg_replace(
- "/".$this->start."include:#([a-z0-9_.]+)#".$this->stop."/ie",
- "'<?php if (file_exists(\"" . $this->engine->options['compileDir'] . "/\\1.en.php\")) include(\"" .
- $this->engine->options['compileDir'] . "/\\1.en.php\");?>'",
- $input);
-
- $input = preg_replace(
- "/".$this->start."t_include:#([a-z0-9_.]+)#".$this->stop."/ie",
- "'<?php if (file_exists(\"" . $this->engine->options['templateDir'] .
- "/\\1\")) include(\"" . $this->engine->options['templateDir'] . "/\\1\");?>'",
- $input);
-
- $input = preg_replace(
- "/".$this->start."q_include:#([a-z0-9_.]+)#".$this->stop."/ie",
- "'<?php HTML_Template_Flexy::staticQuickTemplate(\"\\1\",\$t); ?>'",
- $input);
-
- return $input;
- }
-
-
-
-
-
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Alan Knowles <alan@akbkhome.com>
-// +----------------------------------------------------------------------+
-//
-
-
-/**
-* Replace XML tags with echo '<' .'?xml';
-*
-
-* @package HTML_Template_Flexy
-*
-*/
-
-
-class HTML_Template_Flexy_Compiler_Regex_Xml
-{
- /**
- * Standard Set Engine
- *
- *
- * @param object HTML_Template_Flexy the main engine
- * @access private
- */
- function _set_engine(&$engine)
- {
- }
- /*
- * replace the xml tags
- *
- * @param string The template
- * @access public
- */
- function pre_replace_xml ($input)
- {
- $input = str_replace("?>","<?php echo '?'.'>'; ?>\n",$input);
- $input = str_replace("<?xml","<?php echo '<'.'?xml'; ?>",$input);
- return $input;
- }
-
-
-}
-
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Alan Knowles <alan@akbkhome.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: SmartyConvertor.php,v 1.1.1.1 2008/04/28 15:20:50 jamie Exp $
-//
-// Smarty Conversion compiler
-// takes a smarty template, and converts it to a flexy one.
-// then does a standard flexy compile.
-//
-// anything that is not supported gets changed to HTML comments
-
-/* Usage:
-a simple script: 'convertsmarty.php'
-
-#!/usr/bin/php
- $file = $_SERVER['argv'][1];
- $x = new HTML_Template_Flexy(array(
- 'compileDir' => dirname(__FILE__) , // where do you want to write to..
- 'templateDir' => $dir , // where are your templates
- 'locale' => 'en', // works with gettext
- 'forceCompile' => true, // only suggested for debugging
- 'debug' => false, // prints a few errors
- 'nonHTML' => false, // dont parse HTML tags (eg. email templates)
- 'allowPHP' => false, // allow PHP in template
- 'compiler' => 'SmartyConvertor', // which compiler to use.
- 'compileToString' => true, // returns the converted template (rather than actually
- // converting to PHP.
- 'filters' => array(), // used by regex compiler..
- 'numberFormat' => ",2,'.',','", // default number format = eg. 1,200.00 ( {xxx:n} )
- 'flexyIgnore' => 0 // turn on/off the tag to element code
- ));
-
- echo $x->compile(basename($file));
-
-then run it at the command line:
-php convertsmarty.php /path/to/a/smarty/template.tpl > /path/to/the/flexy/templates.html
-*/
-
-
-require_once 'HTML/Template/Flexy/Compiler.php';
-
-/**
-* The Smarty Converter implementation.
-* designed primarily to be used as above, to convert from one to another.
-* however it could be used inline to convert simple smarty templates into
-* flexy ones - then compile them on the fly.
-*
-* @version $Id: SmartyConvertor.php,v 1.1.1.1 2008/04/28 15:20:50 jamie Exp $
-*/
-class HTML_Template_Flexy_Compiler_SmartyConvertor extends HTML_Template_Flexy_Compiler {
-
- /**
- * compile implementation
- *
- * see HTML_Template_Flexy_Compiler::compile()
- *
- * @param object The core flexy object.
- * @param string optionally a string to compile.
- *
- * @return true | string string when compiling to String.
- * @access public
- */
-
- function compile(&$flexy,$string=false)
- {
- $data = $string;
- if ($string === false) {
- $data = file_get_contents($flexy->currentTemplate);
- }
-
-
-
- $data = $this->convertToFlexy($data);
-
- if ($flexy->options['compileToString']) {
- return $data;
- }
-
- require_once 'HTML/Template/Flexy/Compiler/Standard.php';
- $flexyCompiler = new HTML_Template_Flexy_Compiler_Standard;
- $flexyCompiler->compile($flexy,$data);
- return true;
- }
-
-
-
- /**
- * The core work of parsing a smarty template and converting it into flexy.
- *
- * @param string the contents of the smarty template
- *
- * @return string the flexy version of the template.
- * @access public|private
- * @see see also methods.....
- */
- function convertToFlexy($data)
- {
-
- $leftq = preg_quote('{', '!');
- $rightq = preg_quote('}', '!');
-
- preg_match_all("!" . $leftq . "\s*(.*?)\s*" . $rightq . "!s", $data, $matches);
- $tags = $matches[1];
- // find all the tags/text...
- $text = preg_split("!" . $leftq . ".*?" . $rightq . "!s", $data);
-
- $max_text = count($text);
- $max_tags = count($tags);
-
- for ($i = 0 ; $i < $max_tags ; $i++) {
- $compiled_tags[] = $this->_compileTag($tags[$i]);
- }
- // error handling for closing tags.
-
-
- $data = '';
- for ($i = 0; $i < $max_tags; $i++) {
- $data .= $text[$i].$compiled_tags[$i];
- }
- $data .= $text[$i];
- return $data;
-
- }
-
- /**
- * stack for conditional and closers.
- *
- * @var array
- * @access public
- */
- var $stack = array(
- 'if' => 0,
- );
-
-
-
- /**
- * compile a smarty { tag } into a flexy one.
- *
- * @param string the tag
- *
- * @return string the converted version
- * @access private
- */
- function _compileTag($str)
- {
- // skip comments
- if (($str{0} == '*') && (substr($str,-1,1) == '*')) {
- return '';
- }
-
-
- switch($str{0}) {
- case '$':
- // its a var
- return $this->_convertVar($str);
- case '#':
- // its a config var
- return $this->_convertConfigVar($str);
- case '%':
- // wtf does this do
- return "<!-- what is this? $str -->";
- }
-
-
-
-
-
-
- // this is where it gets messy
- // this is very slow - but what the hell
- // - its only done once
- // - its alot more readable than a long regext.
- // - it doesnt infringe on copyright...
- switch(true) {
- case (preg_match('/^config_load\s/', $str)):
- // convert to $t->TemplateConfigLoad()
- $args = $this->convertAttributesToKeyVal(substr($str,strpos( $str,' ')));
- return '{plugin(#smartyConfigLoad#,#'.$args['file'].'#,#'.$args['section'].'#)}';
-
- case (preg_match('/^include\s/', $str)):
- // convert to $t->TemplateConfigLoad()
- $args = $this->convertAttributesToKeyVal(substr($str,strpos( $str,' ')));
-
- return '{plugin(#smartyInclude#,#'.$args['file'].'#)}';
-
- case ($str == 'ldelim'):
- return '{';
- case ($str == 'rdelim'):
- return '}';
-
-
- case (preg_match('/^if \$(\S+)$/', $str,$matches)):
- case (preg_match('/^if \$(\S+)\seq\s""$/', $str,$matches)):
- // simple if variable..
- // convert to : {if:sssssss}
- $this->stack['if']++;
- $var = $this->_convertVar('$'.$matches[1]);
- return '{if:'.substr($var,1);
-
- case (preg_match('/^if #(\S+)#$/', $str,$matches)):
- case (preg_match('/^if #(\S+)#\sne\s""$/', $str,$matches)):
- // simple if variable..
- // convert to : {if:sssssss}
- $this->stack['if']++;
- $var = $this->_convertConfigVar('#'.$matches[1].'#');
- return '{if:'.substr($var,1);
-
- // negative matches
- case (preg_match('/^if\s!\s\$(\S+)$/', $str,$matches)):
- case (preg_match('/^if \$(\S+)\seq\s""$/', $str,$matches)):
- // simple if variable..
- // convert to : {if:sssssss}
- $this->stack['if']++;
- $var = $this->_convertVar('$'.$matches[1]);
- return '{if:!'.substr($var,1);
-
- case ($str == 'else'):
- if (!$this->stack['if']) {
- break;
- }
- return '{else:}';
-
-
- case ($str == '/if'):
- if (!$this->stack['if']) {
- break;
- }
- $this->stack['if']--;
- return '{end:}';
-
-
- }
-
- return "<!-- UNSUPPORTED TAG: $str FOUND -->";
-
-
-
-
- }
-
- /**
- * convert a smarty var into a flexy one.
- *
- * @param string the inside of the smart tag
- *
- * @return string a flexy version of it.
- * @access private
- */
-
- function _convertVar($str)
- {
- // look for modfiers first.
- $mods = explode('|', $str);
- $var = array_shift($mods);
- $var = substr($var,1); // strip $
-
- // various formats :
- // aaaa.bbbb.cccc => aaaa[bbbb][cccc]
- // aaaa[bbbb] => aaa[bbbb]
- // aaaa->bbbb => aaaa.bbbb
-
- $bits = explode('.',$var);
- $var = array_shift($bits);
- foreach($bits as $k) {
- $var.= '['.$k .']';
- }
- $bits = explode('->',$var);
- $var = implode('.',$bits);
- $mods = implode('|',$mods);
-
- if (strlen($mods)) {
- return '{plugin(#smartyModifiers#,'.$var.',#'.$mods.'#):h}';
- }
- return '{'.$var .'}' . $mods;
- }
- /**
- * convert a smarty key="value" string into a key value array
- * cheap and cheerfull - doesnt handle spaces inside the strings...
- *
- * @param string the key value part of the tag..
- *
- * @return array key value array
- * @access private
- */
- function convertAttributesToKeyVal($str)
- {
- $atts = explode(' ', $str);
- $ret = array();
- foreach($atts as $bit) {
- $bits = explode('=',$bit);
- // loose stuff!!!
- if (count($bits) != 2) {
- continue;
- }
- $ret[$bits[0]] = ($bits[1]{0} == '"') ? substr($bits[1],1,-1) : $bits[1];
- }
- return $ret;
- }
- /**
- * convert a smarty config var into a flexy one.
- *
- * @param string the inside of the smart tag
- *
- * @return string a flexy version of it.
- * @access private
- */
-
- function _convertConfigVar($str)
- {
- $mods = explode('|', $str);
- $var = array_shift($mods);
- $var = substr($var,1,-1); // strip #'s
- $mods = implode('|',$mods);
- if (strlen($mods)) {
- $mods = "<!-- UNSUPPORTED MODIFIERS: $mods -->";
- }
- return '{configVars.'.$var .'}' . $mods;
- }
-}
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Alan Knowles <alan@akbkhome.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Standard.php,v 1.1.1.1 2008/04/28 15:20:50 jamie Exp $
-//
-// Base Compiler Class
-// Standard 'Original Flavour' Flexy compiler
-
-/*------------------------------------------------------------------------------------------
- NOTICE:
- THIS COMPILER IS DEPRECIATED
- USE THE FLEXY COMPILER
-
- The Flexy Compiler should be Compatible
-
-------------------------------------------------------------------------------------------*/
-
-require_once 'HTML/Template/Flexy/Tokenizer.php';
-require_once 'HTML/Template/Flexy/Token.php';
-
-// cache for po files..
-$GLOBALS['_html_template_flexy_compiler_standard']['PO'] = array();
-
-
-class HTML_Template_Flexy_Compiler_Standard extends HTML_Template_Flexy_Compiler
-{
-
-
-
- /**
- * The compile method.
- *
- * @params object HTML_Template_Flexy
- * @params string|false string to compile of false to use a file.
- * @return string filename of template
- * @access public
- */
- function compile(&$flexy,$string=false)
- {
- // read the entire file into one variable
-
- // note this should be moved to new HTML_Template_Flexy_Token
- // and that can then manage all the tokens in one place..
- global $_HTML_TEMPLATE_FLEXY_COMPILER;
-
- $gettextStrings = &$_HTML_TEMPLATE_FLEXY_COMPILER['gettextStrings'];
- $gettextStrings = array(); // reset it.
-
- if (@$this->options['debug']) {
- echo "compiling template $flexy->currentTemplate<BR>";
-
- }
-
- // reset the elements.
- $flexy->_elements = array();
-
- // replace this with a singleton??
-
- $GLOBALS['_HTML_TEMPLATE_FLEXY']['currentOptions'] = $this->options;
- $GLOBALS['_HTML_TEMPLATE_FLEXY']['elements'] = array();
- $GLOBALS['_HTML_TEMPLATE_FLEXY']['filename'] = $flexy->currentTemplate;
- $GLOBALS['_HTML_TEMPLATE_FLEXY']['prefixOutput'] = '';
- $GLOBALS['_HTML_TEMPLATE_FLEXY']['compiledTemplate'] = $flexy->compiledTemplate;
-
- if (is_array($this->options['Translation2'])) {
- require_once 'Translation2.php';
- $this->options['Translation2'] = new Translation2(
- $this->options['Translation2']['driver'],
- @$this->options['Translation2']['options']
- );
- }
-
-
- if (is_a($this->options['Translation2'],'Translation2')) {
- $this->options['Translation2']->setLang($this->options['locale']);
- // fixme - needs to be more specific to which template to use..
- foreach ($this->options['templateDir'] as $tt) {
- $n = basename($flexy->currentTemplate);
- if (substr($flexy->currentTemplate,0,strlen($tt)) == $tt) {
- $n = substr($flexy->currentTemplate,strlen($tt)+1);
- }
- //echo $n;
- }
- $this->options['Translation2']->setPageID($n);
- } else {
- setlocale(LC_ALL, $this->options['locale']);
- }
-
-
-
-
-
-
-
- $data = $string;
- $res = false;
- if ($string === false) {
- $data = file_get_contents($flexy->currentTemplate);
- }
-
- // PRE PROCESS {_(.....)} translation markers.
- $got_gettext_markup = false;
-
-
-
- if (strpos($data,'{_(') !== false) {
- $matches = array();
- $lmatches = explode ('{_(', $data);
- array_shift($lmatches);
- // shift the first..
- foreach ($lmatches as $k) {
- if (false === strpos($k,')_}')) {
- continue;
- }
- $x = explode(')_}',$k);
- $matches[] = $x[0];
- }
-
-
- //echo '<PRE>';print_r($matches);
- // we may need to do some house cleaning here...
- $gettextStrings = $matches;
- $got_gettext_markup = true;
-
-
- // replace them now..
- // ** leaving in the tag (which should be ignored by the parser..
- // we then get rid of the tags during the toString method in this class.
- foreach($matches as $v) {
- $data = str_replace('{_('.$v.')_}', '{_('.$this->translateString($v).')_}',$data);
- }
-
- }
-
- if (isset($_HTML_TEMPLATE_FLEXY_COMPILER['cache'][md5($data)])) {
- $res = $_HTML_TEMPLATE_FLEXY_COMPILER['cache'][md5($data)];
- } else {
-
-
- $tokenizer = new HTML_Template_Flexy_Tokenizer($data);
- $tokenizer->fileName = $flexy->currentTemplate;
-
-
- //$tokenizer->debug=1;
- $tokenizer->options['ignore_html'] = $this->options['nonHTML'];
- $tokenizer->options['ignore_php'] = !$this->options['allowPHP'];
-
- $res = HTML_Template_Flexy_Token::buildTokens($tokenizer);
-
- $_HTML_TEMPLATE_FLEXY_COMPILER['cache'][md5($data)] = $res;
-
- }
-
- if (is_a($res,'PEAR_Error')) {
- return $res;
- }
- // turn tokens into Template..
-
- $data = $res->compile($this);
-
- if (is_a($data,'PEAR_Error')) {
- return $data;
- }
-
- $data = $GLOBALS['_HTML_TEMPLATE_FLEXY']['prefixOutput'] . $data;
-
- if ( @$this->options['debug']) {
- echo "<B>Result: </B><PRE>".htmlspecialchars($data)."</PRE><BR>";
-
- }
-
- if ($this->options['nonHTML']) {
- $data = str_replace("?>\n","?>\n\n",$data);
- }
-
-
-
-
- // at this point we are into writing stuff...
- if ($this->options['compileToString']) {
- $flexy->elements = $GLOBALS['_HTML_TEMPLATE_FLEXY']['elements'];
- return $data;
- }
-
-
-
-
- // error checking?
- $file = $flexy->compiledTemplate;
- if (isset($flexy->options['output.block'])) {
- list($file,$part) = explode('#',$file );
- }
-
- if( ($cfp = fopen( $file , 'w' )) ) {
- if (@$this->options['debug']) {
- echo "<B>Writing: </B>".htmlspecialchars($data)."<BR>";
-
- }
- fwrite($cfp,$data);
- fclose($cfp);
-
- chmod($file,0775);
- // make the timestamp of the two items match.
- clearstatcache();
- touch($file, filemtime($flexy->currentTemplate));
- if ($file != $flexy->compiledTemplate) {
- chmod($flexy->compiledTemplate,0775);
- // make the timestamp of the two items match.
- clearstatcache();
- touch($flexy->compiledTemplate, filemtime($flexy->currentTemplate));
- }
-
-
- } else {
- return HTML_Template_Flexy::raiseError('HTML_Template_Flexy::failed to write to '.$flexy->compiledTemplate,
- HTML_TEMPLATE_FLEXY_ERROR_FILE ,HTML_TEMPLATE_FLEXY_ERROR_RETURN);
- }
- // gettext strings
- if (file_exists($flexy->getTextStringsFile)) {
- unlink($flexy->getTextStringsFile);
- }
-
- if($gettextStrings && ($cfp = fopen( $flexy->getTextStringsFile, 'w') ) ) {
-
- fwrite($cfp,serialize(array_unique($gettextStrings)));
- fclose($cfp);
- }
-
- // elements
- if (file_exists($flexy->elementsFile)) {
- unlink($flexy->elementsFile);
- }
-
- if( $GLOBALS['_HTML_TEMPLATE_FLEXY']['elements'] &&
- ($cfp = fopen( $flexy->elementsFile, 'w') ) ) {
- fwrite($cfp,serialize( $GLOBALS['_HTML_TEMPLATE_FLEXY']['elements']));
- fclose($cfp);
- // now clear it.
-
- }
-
- return true;
- }
-
- /**
- * Flag indicating compiler is inside {_( .... )_} block, and should not
- * add to the gettextstrings array.
- *
- * @var boolean
- * @access public
- */
- var $inGetTextBlock = false;
-
- /**
- * This is the base toString Method, it relays into toString{TokenName}
- *
- * @param object HTML_Template_Flexy_Token_*
- *
- * @return string string to build a template
- * @access public
- * @see toString*
- */
-
-
- function toString($element)
- {
- static $len = 26; // strlen('HTML_Template_Flexy_Token_');
- if ($this->options['debug']) {
- $x = $element;
- unset($x->children);
- echo htmlspecialchars(print_r($x,true))."<BR>\n";
- }
- if ($element->token == 'GetTextStart') {
- $this->inGetTextBlock = true;
- return '';
- }
- if ($element->token == 'GetTextEnd') {
- $this->inGetTextBlock = false;
- return '';
- }
-
-
- $class = get_class($element);
- if (strlen($class) >= $len) {
- $type = substr($class,$len);
- return $this->{'toString'.$type}($element);
- }
-
- $ret = $element->value;
- $add = $element->compileChildren($this);
- if (is_a($add,'PEAR_Error')) {
- return $add;
- }
- $ret .= $add;
-
- if ($element->close) {
- $add = $element->close->compile($this);
- if (is_a($add,'PEAR_Error')) {
- return $add;
- }
- $ret .= $add;
- }
-
- return $ret;
- }
-
-
- /**
- * HTML_Template_Flexy_Token_Else toString
- *
- * @param object HTML_Template_Flexy_Token_Else
- *
- * @return string string to build a template
- * @access public
- * @see toString*
- */
-
-
- function toStringElse($element)
- {
- // pushpull states to make sure we are in an area.. - should really check to see
- // if the state it is pulling is a if...
- if ($element->pullState() === false) {
- return $this->appendHTML(
- "<font color=\"red\">Unmatched {else:} on line: {$element->line}</font>"
- );
- }
- $element->pushState();
- return $this->appendPhp("} else {");
- }
-
- /**
- * HTML_Template_Flexy_Token_End toString
- *
- * @param object HTML_Template_Flexy_Token_Else
- *
- * @return string string to build a template
- * @access public
- * @see toString*
- */
-
- function toStringEnd($element)
- {
- // pushpull states to make sure we are in an area.. - should really check to see
- // if the state it is pulling is a if...
- if ($element->pullState() === false) {
- return $this->appendHTML(
- "<font color=\"red\">Unmatched {end:} on line: {$element->line}</font>"
- );
- }
-
- return $this->appendPhp("}");
- }
-
- /**
- * HTML_Template_Flexy_Token_EndTag toString
- *
- * @param object HTML_Template_Flexy_Token_EndTag
- *
- * @return string string to build a template
- * @access public
- * @see toString*
- */
-
-
-
- function toStringEndTag($element)
- {
- return $this->toStringTag($element);
- }
-
-
-
- /**
- * HTML_Template_Flexy_Token_Foreach toString
- *
- * @param object HTML_Template_Flexy_Token_Foreach
- *
- * @return string string to build a template
- * @access public
- * @see toString*
- */
-
-
- function toStringForeach($element)
- {
-
- $loopon = $element->toVar($element->loopOn);
- if (is_a($loopon,'PEAR_Error')) {
- return $loopon;
- }
-
- $ret = 'if ($this->options[\'strict\'] || ('.
- 'is_array('. $loopon. ') || ' .
- 'is_object(' . $loopon . '))) ' .
- 'foreach(' . $loopon . " ";
-
- $ret .= "as \${$element->key}";
-
- if ($element->value) {
- $ret .= " => \${$element->value}";
- }
- $ret .= ") {";
-
- $element->pushState();
- $element->pushVar($element->key);
- $element->pushVar($element->value);
- return $this->appendPhp($ret);
- }
- /**
- * HTML_Template_Flexy_Token_If toString
- *
- * @param object HTML_Template_Flexy_Token_If
- *
- * @return string string to build a template
- * @access public
- * @see toString*
- */
-
- function toStringIf($element)
- {
-
- $var = $element->toVar($element->condition);
- if (is_a($var,'PEAR_Error')) {
- return $var;
- }
-
- $ret = "if (".$element->isNegative . $var .") {";
- $element->pushState();
- return $this->appendPhp($ret);
- }
-
- /**
- * get Modifier Wrapper
- *
- * converts :h, :u, :r , .....
- * @param object HTML_Template_Flexy_Token_Method|Var
- *
- * @return array prefix,suffix
- * @access public
- * @see toString*
- */
-
- function getModifierWrapper($element)
- {
- $prefix = 'echo ';
-
- $suffix = '';
- $modifier = strlen(trim($element->modifier)) ? $element->modifier : ' ';
-
- switch ($modifier{0}) {
- case 'h':
- break;
- case 'u':
- $prefix = 'echo urlencode(';
- $suffix = ')';
- break;
- case 'r':
- $prefix = 'echo \'<pre>\'; echo htmlspecialchars(print_r(';
- $suffix = ',true)); echo \'</pre>\';';
- break;
- case 'n':
- // blank or value..
- $numberformat = @$GLOBALS['_HTML_TEMPLATE_FLEXY']['currentOptions']['numberFormat'];
- $prefix = 'echo number_format(';
- $suffix = $GLOBALS['_HTML_TEMPLATE_FLEXY']['currentOptions']['numberFormat'] . ')';
- break;
- case 'b': // nl2br + htmlspecialchars
- $prefix = 'echo nl2br(htmlspecialchars(';
-
- // add language ?
- $suffix = '))';
- break;
- case ' ':
- $prefix = 'echo htmlspecialchars(';
- // add language ?
- $suffix = ')';
- break;
- default:
- $prefix = 'echo $this->plugin("'.trim($element->modifier) .'",';
- $suffix = ')';
-
-
- }
-
- return array($prefix,$suffix);
- }
-
-
-
- /**
- * HTML_Template_Flexy_Token_Var toString
- *
- * @param object HTML_Template_Flexy_Token_Method
- *
- * @return string string to build a template
- * @access public
- * @see toString*
- */
-
- function toStringVar($element)
- {
- // ignore modifier at present!!
-
- $var = $element->toVar($element->value);
- if (is_a($var,'PEAR_Error')) {
- return $var;
- }
- list($prefix,$suffix) = $this->getModifierWrapper($element);
- return $this->appendPhp( $prefix . $var . $suffix .';');
- }
- /**
- * HTML_Template_Flexy_Token_Method toString
- *
- * @param object HTML_Template_Flexy_Token_Method
- *
- * @return string string to build a template
- * @access public
- * @see toString*
- */
-
- function toStringMethod($element)
- {
-
-
- // set up the modifier at present!!
- list($prefix,$suffix) = $this->getModifierWrapper($element);
-
- // add the '!' to if
-
- if ($element->isConditional) {
- $prefix = 'if ('.$element->isNegative;
- $element->pushState();
- $suffix = ')';
- }
-
-
- // check that method exists..
- // if (method_exists($object,'method');
- $bits = explode('.',$element->method);
- $method = array_pop($bits);
-
- $object = implode('.',$bits);
-
- $var = $element->toVar($object);
- if (is_a($var,'PEAR_Error')) {
- return $var;
- }
-
- if (($object == 'GLOBALS') &&
- $GLOBALS['_HTML_TEMPLATE_FLEXY']['currentOptions']['globalfunctions']) {
- // we should check if they something weird like: GLOBALS.xxxx[sdf](....)
- $var = $method;
- } else {
- $prefix = 'if ($this->options[\'strict\'] || (isset('.$var.
- ') && method_exists('.$var .",'{$method}'))) " . $prefix;
- $var = $element->toVar($element->method);
- }
-
-
- if (is_a($var,'PEAR_Error')) {
- return $var;
- }
-
- $ret = $prefix;
- $ret .= $var . "(";
- $s =0;
-
-
-
- foreach($element->args as $a) {
-
- if ($s) {
- $ret .= ",";
- }
- $s =1;
- if ($a{0} == '#') {
- $ret .= '"'. addslashes(substr($a,1,-1)) . '"';
- continue;
- }
-
- $var = $element->toVar($a);
- if (is_a($var,'PEAR_Error')) {
- return $var;
- }
- $ret .= $var;
-
- }
- $ret .= ")" . $suffix;
-
- if ($element->isConditional) {
- $ret .= ' { ';
- } else {
- $ret .= ";";
- }
-
-
-
- return $this->appendPhp($ret);
-
-
-
- }
- /**
- * HTML_Template_Flexy_Token_Processing toString
- *
- * @param object HTML_Template_Flexy_Token_Processing
- *
- * @return string string to build a template
- * @access public
- * @see toString*
- */
-
-
- function toStringProcessing($element)
- {
- // if it's XML then quote it..
- if (strtoupper(substr($element->value,2,3)) == 'XML') {
- return $this->appendPhp("echo '" . str_replace("'","\\"."'", $element->value) . "';");
- }
- // otherwise it's PHP code - so echo it..
- return $element->value;
- }
-
- /**
- * HTML_Template_Flexy_Token_Text toString
- *
- * @param object HTML_Template_Flexy_Token_Text
- *
- * @return string string to build a template
- * @access public
- * @see toString*
- */
-
-
-
- function toStringText($element)
- {
-
- // first get rid of stuff thats not translated etc.
- // empty strings => output.
- // comments -> just output
- // our special tags -> output..
-
- if (!strlen(trim($element->value) )) {
- return $this->appendHtml($element->value);
- }
- // dont add comments to translation lists.
-
- if (substr($element->value,0,4) == '<!--') {
- return $this->appendHtml($element->value);
- }
- // ignore anything wrapped with {_( .... )_}
- if ($this->inGetTextBlock) {
- return $this->appendHtml($element->value);
- }
-
- // argTokens is built before the tag matching (it combined
- // flexy tags into %s, into the string,
- // and made a list of tokens in argTokens.
-
- if (!count($element->argTokens) && !$element->isWord()) {
- return $this->appendHtml($element->value);
- }
-
- // grab the white space at start and end (and keep it!
-
- $value = ltrim($element->value);
- $front = substr($element->value,0,-strlen($value));
- $value = rtrim($element->value);
- $rear = substr($element->value,strlen($value));
- $value = trim($element->value);
-
-
- // convert to escaped chars.. (limited..)
- //$value = strtr($value,$cleanArray);
-
- $this->addStringToGettext($value);
- $value = $this->translateString($value);
- // its a simple word!
- if (!count($element->argTokens)) {
- return $this->appendHtml($front . $value . $rear);
- }
-
-
- // there are subtokens..
- // print_r($element->argTokens );
- $args = array();
- // these should only be text or vars..
-
- foreach($element->argTokens as $i=>$token) {
- $args[] = $token->compile($this);
- }
-
- // we break up the translated string, and put the compiled tags
- // in between the values here.
-
- $bits = explode('%s',$value);
- $ret = $front;
-
- foreach($bits as $i=>$v) {
- $ret .= $v . @$args[$i];
- }
-
- return $ret . $rear;
-
- }
- /**
- * addStringToGettext
- *
- * Adds a string to the gettext array.
- *
- * @param mixed preferably.. string to store
- *
- * @return none
- * @access public
- */
-
- function addStringToGettext($string)
- {
-
-
-
-
- if (!is_string($string)) {
- return;
- }
-
- if (!preg_match('/[a-z]+/i', $string)) {
- return;
- }
- $string = trim($string);
-
- if (substr($string,0,4) == '<!--') {
- return;
- }
-
- $GLOBALS['_HTML_TEMPLATE_FLEXY_COMPILER']['gettextStrings'][] = $string;
- }
-
-
- /**
- * translateString - a gettextWrapper
- *
- * tries to do gettext or falls back on File_Gettext
- * This has !!!NO!!! error handling - if it fails you just get english..
- * no questions asked!!!
- *
- * @param string string to translate
- *
- * @return string translated string..
- * @access public
- */
-
- function translateString($string)
- {
-
-
-
- if (is_a($this->options['Translation2'],'Translation2')) {
- $result = $this->options['Translation2']->get($string);
- if (!empty($result)) {
- return $result;
- }
- return $string;
- }
-
- // note this stuff may have been broken by removing the \n replacement code
- // since i dont have a test for it... it may remain broken..
- // use Translation2 - it has gettext backend support
- // and should sort out the mess that \n etc. entail.
-
-
- $prefix = basename($GLOBALS['_HTML_TEMPLATE_FLEXY']['filename']).':';
- if (@$this->options['debug']) {
- echo __CLASS__.":TRANSLATING $string<BR>";
- }
- if (function_exists('gettext') && !$this->options['textdomain']) {
- if (@$this->options['debug']) {
- echo __CLASS__.":USING GETTEXT?<BR>";
- }
- $t = gettext($string);
- if ($t != $string) {
- return $t;
- }
- $tt = gettext($prefix.$string);
- if ($tt != $prefix.$string) {
- return $tt;
- }
- // give up it's not translated anywhere...
- return $t;
-
- }
- if (!$this->options['textdomain'] || !$this->options['textdomainDir']) {
- // text domain is not set..
- if (@$this->options['debug']) {
- echo __CLASS__.":MISSING textdomain settings<BR>";
- }
- return $string;
- }
- $pofile = $this->options['textdomainDir'] .
- '/' . $this->options['locale'] .
- '/LC_MESSAGES/' . $this->options['textdomain'] . '.po';
-
-
- // did we try to load it already..
- if (@$GLOBALS['_'.__CLASS__]['PO'][$pofile] === false) {
- if (@$this->options['debug']) {
- echo __CLASS__.":LOAD failed (Cached):<BR>";
- }
- return $string;
- }
- if (!@$GLOBALS['_'.__CLASS__]['PO'][$pofile]) {
- // default - cant load it..
- $GLOBALS['_'.__CLASS__]['PO'][$pofile] = false;
- if (!file_exists($pofile)) {
- if (@$this->options['debug']) {
- echo __CLASS__.":LOAD failed: {$pofile}<BR>";
- }
- return $string;
- }
-
- if (!@include_once 'File/Gettext.php') {
- if (@$this->options['debug']) {
- echo __CLASS__.":LOAD no File_gettext:<BR>";
- }
- return $string;
- }
-
- $GLOBALS['_'.__CLASS__]['PO'][$pofile] = File_Gettext::factory('PO',$pofile);
- $GLOBALS['_'.__CLASS__]['PO'][$pofile]->load();
- //echo '<PRE>'.htmlspecialchars(print_r($GLOBALS['_'.__CLASS__]['PO'][$pofile]->strings,true));
-
- }
- $po = &$GLOBALS['_'.__CLASS__]['PO'][$pofile];
- // we should have it loaded now...
- // this is odd - data is a bit messed up with CR's
- $string = str_replace('\n',"\n",$string);
-
- if (isset($po->strings[$prefix.$string])) {
- return $po->strings[$prefix.$string];
- }
-
- if (!isset($po->strings[$string])) {
- if (@$this->options['debug']) {
- echo __CLASS__.":no match:<BR>";
- }
- return $string;
- }
- if (@$this->options['debug']) {
- echo __CLASS__.":MATCHED: {$po->strings[$string]}<BR>";
- }
-
- // finally we have a match!!!
- return $po->strings[$string];
-
- }
- /**
- * HTML_Template_Flexy_Token_Tag toString
- *
- * @param object HTML_Template_Flexy_Token_Tag
- *
- * @return string string to build a template
- * @access public
- * @see toString*
- */
-
- function toStringTag($element) {
- if (strpos($element->tag,':') === false) {
- $namespace = 'Tag';
- } else {
- $bits = explode(':',$element->tag);
- $namespace = $bits[0];
- }
- if ($namespace{0} == '/') {
- $namespace = substr($namespace,1);
- }
- if (empty($this->tagHandlers[$namespace])) {
-
- require_once 'HTML/Template/Flexy/Compiler/Standard/Tag.php';
- $this->tagHandlers[$namespace] = &HTML_Template_Flexy_Compiler_Standard_Tag::factory($namespace,$this);
- if (!$this->tagHandlers[$namespace] ) {
- return HTML_Template_Flexy::raiseError('HTML_Template_Flexy::failed to create Namespace Handler '.$namespace .
- ' in file ' . $GLOBALS['_HTML_TEMPLATE_FLEXY']['filename'],
- HTML_TEMPLATE_FLEXY_ERROR_SYNTAX ,HTML_TEMPLATE_FLEXY_ERROR_RETURN);
- }
-
- }
- return $this->tagHandlers[$namespace]->toString($element);
-
-
- }
-
-
-}
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Alan Knowles <alan@akkbhome.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Flexy.php,v 1.1.1.1 2008/04/28 15:20:50 jamie Exp $
-//
-// Handler code for the <flexy: namespace
-//
-
-/**
-* the <flexy:XXXX namespace
-*
-*
-* at present it handles
-* <flexy:toJavascript flexy:prefix="Javascript_prefix" javscriptName="PHPvar" .....>
-* <flexy:include src="xxx.htm">
-*
-*
-*
-* @version $Id: Flexy.php,v 1.1.1.1 2008/04/28 15:20:50 jamie Exp $
-*/
-
-class HTML_Template_Flexy_Compiler_Standard_Flexy {
-
-
- /**
- * Parent Compiler for
- *
- * @var object HTML_Template_Flexy_Compiler
- *
- * @access public
- */
- var $compiler;
-
-
- /**
- * The current element to parse..
- *
- * @var object
- * @access public
- */
- var $element;
-
-
-
-
-
- /**
- * toString - display tag, attributes, postfix and any code in attributes.
- * Relays into namspace::method to get results..
- *
- *
- * @see parent::toString()
- */
- function toString($element)
- {
-
- list($namespace,$method) = explode(':',$element->oTag);
- if (!strlen($method)) {
- return '';
- }
- // things we dont handle...
- if (!method_exists($this,$method.'ToString')) {
- return '';
- }
- return $this->{$method.'ToString'}($element);
-
- }
- /**
- * toJavascript handler
- * <flexy:toJavascript flexy:prefix="some_prefix_" javascriptval="php.val" ....>
- *
- * @see parent::toString()
- */
-
- function toJavascriptToString($element)
- {
- $ret = $this->compiler->appendPhp( "require_once 'HTML/Javascript/Convert.php';");
- $ret .= $this->compiler->appendHTML("\n<script type='text/javascript'>\n");
- $prefix = ''. $element->getAttribute('FLEXY:PREFIX');
-
-
- foreach ($element->attributes as $k=>$v) {
- // skip directives..
- if (strpos($k,':')) {
- continue;
- }
- if ($k == '/') {
- continue;
- }
- $v = substr($v,1,-1);
- $ret .= $this->compiler->appendPhp(
- '$__tmp = HTML_Javascript_Convert::convertVar('.$element->toVar($v) .',\''.$prefix . $k.'\',true);'.
- 'echo (is_a($__tmp,"PEAR_Error")) ? ("<pre>".print_r($__tmp,true)."</pre>") : $__tmp;');
- $ret .= $this->compiler->appendHTML("\n");
- }
- $ret .= $this->compiler->appendHTML("</script>");
- return $ret;
- }
- /**
- * include handler
- * <flexy:include src="test.html">
- *
- * @see parent::toString()
- */
- function includeToString($element)
- {
- // this is disabled by default...
- // we ignore modifier pre/suffix
-
-
-
-
- $arg = $element->getAttribute('SRC');
- if (!$arg) {
- return $this->compiler->appendHTML("<B>Flexy:Include without a src=filename</B>");
- }
- // ideally it would be nice to embed the results of one template into another.
- // however that would involve some complex test which would have to stat
- // the child templates anyway..
- // compile the child template....
- // output... include $this->options['compiled_templates'] . $arg . $this->options['locale'] . '.php'
- return $this->compiler->appendPHP( "\n".
- "\$x = new HTML_Template_Flexy(\$this->options);\n".
- "\$x->compile('{$arg}');\n".
- "\$x->outputObject(\$t);\n"
- );
-
- }
-
- /**
- * Convert flexy tokens to HTML_Template_Flexy_Elements.
- *
- * @param object token to convert into a element.
- * @return object HTML_Template_Flexy_Element
- * @access public
- */
- function toElement($element)
- {
- return '';
- }
-
-
- /**
- * Handler for User defined functions in templates..
- * <flexy:function name="xxxxx">.... </flexy:block> // equivilant to function xxxxx() {
- * <flexy:function call="{xxxxx}">.... </flexy:block> // equivilant to function {$xxxxx}() {
- * <flexy:function call="xxxxx">.... </flexy:block> // equivilant to function {$xxxxx}() {
- *
- * This will not handle nested blocks initially!! (and may cause even more problems with
- * if /foreach stuff..!!
- *
- * @param object token to convert into a element.
- * @access public
- */
-
-
- function functionToString($element)
- {
-
- if ($arg = $element->getAttribute('NAME')) {
- // this is a really kludgy way of doing this!!!
- // hopefully the new Template Package will have a sweeter method..
- $GLOBALS['_HTML_TEMPLATE_FLEXY']['prefixOutput'] .=
- $this->compiler->appendPHP(
- "\nfunction _html_template_flexy_compiler_standard_flexy_{$arg}(\$t,\$this) {\n").
- $element->compileChildren($this->compiler) .
- $this->compiler->appendPHP( "\n}\n");
-
- return '';
- }
- if (!isset($element->ucAttributes['CALL'])) {
-
- return HTML_Template_Flexy::raiseError(
- ' tag flexy:function needs an argument call or name'.
- " Error on Line {$element->line} <{$element->tag}>",
- null, HTML_TEMPLATE_FLEXY_ERROR_DIE);
- }
- // call is a stirng : nice and simple..
- if (is_string($element->ucAttributes['CALL'])) {
- $arg = $element->getAttribute('CALL');
- return $this->compiler->appendPHP(
- "if (function_exists('_html_template_flexy_compiler_standard_flexy_'.{$arg})) " .
- " _html_template_flexy_compiler_standard_flexy_{$arg}(\$t,\$this);");
- }
-
- // we make a big assumption here.. - it should really be error checked..
- // that the {xxx} element is item 1 in the list...
- $e=$element->ucAttributes['CALL'][1];
- $add = $e->toVar($e->value);
- if (is_a($add,'PEAR_Error')) {
- return $add;
- }
- return $this->compiler->appendPHP(
- "if (function_exists('_html_template_flexy_compiler_standard_flexy_'.{$add})) ".
- "call_user_func_array('_html_template_flexy_compiler_standard_flexy_'.{$add},array(\$t,\$this));");
-
-
-
- }
-
-}
-
-
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Alan Knowles <alan@akbkhome> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Tag.php,v 1.1.1.1 2008/04/28 15:20:50 jamie Exp $
-/* FC/BC compatibility with php5 */
-if ( (substr(phpversion(),0,1) < 5) && !function_exists('clone')) {
- eval('function clone($t) { return $t; }');
-}
-
-/**
-* Compiler That deals with standard HTML Tag output.
-* Since it's pretty complex it has it's own class.
-* I guess this class should deal with the main namespace
-* and the parent (standard compiler can redirect other namespaces to other classes.
-*
-* one instance of these exists for each namespace.
-*
-*
-* @version $Id: Tag.php,v 1.1.1.1 2008/04/28 15:20:50 jamie Exp $
-*/
-
-class HTML_Template_Flexy_Compiler_Standard_Tag {
-
-
- /**
- * Parent Compiler for
- *
- * @var object HTML_Template_Flexy_Compiler
- *
- * @access public
- */
- var $compiler;
-
- /**
- *
- * Factory method to create Tag Handlers
- *
- * $type = namespace eg. <flexy:toJavascript loads Flexy.php
- * the default is this... (eg. Tag)
- *
- *
- * @param string Namespace handler for element.
- * @param object HTML_Template_Flexy_Compiler
- *
- *
- * @return object tag compiler
- * @access public
- */
-
- function &factory($type,&$compiler) {
- if (!$type) {
- $type = 'Tag';
- }
- // if we dont have a handler - just use the basic handler.
- if (!file_exists(dirname(__FILE__) . '/'. ucfirst(strtolower($type)) . '.php')) {
- $type = 'Tag';
- }
-
- include_once 'HTML/Template/Flexy/Compiler/Standard/' . ucfirst(strtolower($type)) . '.php';
-
- $class = 'HTML_Template_Flexy_Compiler_Standard_' . $type;
- if (!class_exists($class)) {
- return false;
- }
- $ret = new $class;
- $ret->compiler = &$compiler;
- return $ret;
- }
-
-
- /**
- * The current element to parse..
- *
- * @var object
- * @access public
- */
- var $element;
-
- /**
- * Flag to indicate has attribute flexy:foreach (so you cant mix it with flexy:if!)
- *
- * @var boolean
- * @access public
- */
- var $hasForeach = false;
-
-
-
-
- /**
- * toString - display tag, attributes, postfix and any code in attributes.
- * Note first thing it does is call any parseTag Method that exists..
- *
- *
- * @see parent::toString()
- */
- function toString($element)
- {
-
- global $_HTML_TEMPLATE_FLEXY_TOKEN;
- global $_HTML_TEMPLATE_FLEXY;
-
- // store the element in a variable
- $this->element = $element;
- // echo "toString: Line {$this->element->line} <{$this->element->tag}>\n";
-
- // if the FLEXYSTARTCHILDREN flag was set, only do children
- // normally set in BODY tag.
- // this will probably be superseeded by the Class compiler.
-
- if (isset($element->ucAttributes['FLEXY:STARTCHILDREN'])) {
-
- return $element->compileChildren($this->compiler);
- }
-
- $flexyignore = $this->parseAttributeIgnore();
-
- // rewriting should be done with a tag.../flag.
-
- $this->reWriteURL("HREF");
- $this->reWriteURL("SRC");
-
- // handle elements
- if (($ret =$this->_parseTags()) !== false) {
- return $ret;
- }
- // these add to the close tag..
-
- $ret = $this->parseAttributeForeach();
- $ret .= $this->parseAttributeIf();
-
- // spit ou the tag and attributes.
-
- if ($element->oTag{0} == '?') {
- $ret .= '<?php echo "<"; ?>';
- } else {
- $ret .= "<";
- }
- $ret .= $element->oTag;
-
- foreach ($element->attributes as $k=>$v) {
- // if it's a flexy tag ignore it.
-
-
- if (strtoupper($k) == 'FLEXY:RAW') {
- if (!is_array($v) || !isset($v[1]) || !is_object($v[1])) {
- return HTML_Template_Flexy::raiseError(
- 'flexy:raw only accepts a variable or method call as an argument, eg.'.
- ' flexy:raw="{somevalue}" you provided something else.' .
- " Error on Line {$this->element->line} <{$this->element->tag}>",
- null, HTML_TEMPLATE_FLEXY_ERROR_DIE);
- }
- $add = $v[1]->compile($this->compiler);
- if (is_a($add,'PEAR_Error')) {
- return $add;
- }
- $ret .= ' ' . $add;
- continue;
-
- }
-
- if (strtoupper(substr($k,0,6)) == 'FLEXY:') {
- continue;
- }
- // true == an attribute without a ="xxx"
- if ($v === true) {
- $ret .= " $k";
- continue;
- }
-
- // if it's a string just dump it.
- if (is_string($v)) {
- $ret .= " {$k}={$v}";
- continue;
- }
-
- // normally the value is an array of string, however
- // if it is an object - then it's a conditional key.
- // eg. if (something) echo ' SELECTED';
- // the object is responsible for adding it's space..
-
- if (is_object($v)) {
- $add = $v->compile($this->compiler);
- if (is_a($add,'PEAR_Error')) {
- return $add;
- }
-
- $ret .= $add;
- continue;
- }
-
- // otherwise its a key="sometext{andsomevars}"
-
- $ret .= " {$k}=";
-
- foreach($v as $item) {
- if (is_string($item)) {
- $ret .= $item;
- continue;
- }
- $add = $item->compile($this->compiler);
- if (is_a($add,'PEAR_Error')) {
- return $add;
- }
- $ret .= $add;
- }
- }
- $ret .= ">";
-
- // post stuff this is probably in the wrong place...
-
- if ($element->postfix) {
- foreach ($element->postfix as $e) {
- $add = $e->compile($this->compiler);
- if (is_a($add,'PEAR_Error')) {
- return $add;
- }
- $ret .= $add;
- }
- } else if ($this->element->postfix) { // if postfixed by self..
- foreach ($this->element->postfix as $e) {
- $add = $e->compile($this->compiler);
- if (is_a($add,'PEAR_Error')) {
- return $add;
- }
-
- $ret .= $add;
- }
- }
- // dump contents of script raw - to prevent gettext additions..
- // print_r($element);
- if ($element->tag == 'SCRIPT') {
- foreach($element->children as $c) {
- //print_R($c);
- if (!$c) {
- continue;
- }
- if ($c->token == 'Text') {
- $ret .= $c->value;
- continue;
- }
- // techically we shouldnt have anything else inside of script tags.
- // as the tokeinzer is supposted to ignore it..
- }
- } else {
- $add = $element->compileChildren($this->compiler);
- if (is_a($add,'PEAR_Error')) {
- return $add;
- }
- $ret .= $add;
- }
-
-
-
- // output the closing tag.
-
- if ($element->close) {
- $add = $element->close->compile($this->compiler);
- if (is_a($add,'PEAR_Error')) {
- return $add;
- }
- $ret .= $add;
- }
-
- // reset flexyignore
-
- $_HTML_TEMPLATE_FLEXY_TOKEN['flexyIgnore'] = $flexyignore;
-
- if (isset($_HTML_TEMPLATE_FLEXY['currentOptions']['output.block']) &&
- ($_HTML_TEMPLATE_FLEXY['currentOptions']['output.block'] == $element->getAttribute('ID'))) {
-
- // echo $_HTML_TEMPLATE_FLEXY['compiledTemplate'];
-
- $fh = fopen($_HTML_TEMPLATE_FLEXY['compiledTemplate'],'w');
- fwrite($fh,$ret);
- fclose($fh);
-
- }
-
-
-
- return $ret;
- }
- /**
- * Reads an flexy:foreach attribute -
- *
- *
- * @return string to add to output.
- * @access public
- */
-
- function parseAttributeIgnore()
- {
-
- global $_HTML_TEMPLATE_FLEXY_TOKEN;
-
- $flexyignore = $_HTML_TEMPLATE_FLEXY_TOKEN['flexyIgnore'];
-
- if ($this->element->getAttribute('FLEXY:IGNORE') !== false) {
- $_HTML_TEMPLATE_FLEXY_TOKEN['flexyIgnore'] = true;
- $this->element->clearAttribute('FLEXY:IGNORE');
- }
- return $flexyignore;
-
- }
-
- /**
- * Reads an flexy:foreach attribute -
- *
- *
- * @return string to add to output.
- * @access public
- */
-
- function parseAttributeForeach()
- {
- $foreach = $this->element->getAttribute('FLEXY:FOREACH');
- if ($foreach === false) {
- return '';
- }
- //var_dump($foreach);
-
- $this->element->hasForeach = true;
- // create a foreach element to wrap this with.
-
- $foreachObj = $this->element->factory('Foreach',
- explode(',',$foreach),
- $this->element->line);
- // failed = probably not enough variables..
-
-
- if ($foreachObj === false) {
- return HTML_Template_Flexy::raiseError(
- "Missing Arguments: An flexy:foreach attribute was foundon Line {$this->element->line}
- in tag <{$this->element->tag} flexy:foreach="$foreach" .....><BR>
- the syntax is <sometag flexy:foreach="onarray,withvariable[,withanothervar] ><BR>",
- null, HTML_TEMPLATE_FLEXY_ERROR_DIE);
- }
-
-
-
- // does it have a closetag?
- if (!$this->element->close) {
-
- if ($this->element->getAttribute('/') === false) {
-
-
- return HTML_Template_Flexy::raiseError(
- "A flexy:foreach attribute was found in <{$this->element->name} tag without a corresponding </{$this->element->tag}
- tag on Line {$this->element->line} <{$this->element->tag}>",
- null, HTML_TEMPLATE_FLEXY_ERROR_DIE);
- }
- // it's an xhtml tag!
- $this->element->postfix = array($this->element->factory("End", '', $this->element->line));
- } else {
- $this->element->close->postfix = array($this->element->factory("End", '', $this->element->line));
- }
-
- $this->element->clearAttribute('FLEXY:FOREACH');
- return $foreachObj->compile($this->compiler);
- }
- /**
- * Reads an flexy:if attribute -
- *
- *
- * @return string to add to output.
- * @access public
- */
-
- function parseAttributeIf()
- {
- // dont use the together, if is depreciated..
- $if = $this->element->getAttribute('FLEXY:IF');
-
- if ($if === false) {
- return '';
- }
-
- if (isset($this->element->hasForeach)) {
- return HTML_Template_Flexy::raiseError(
- "You may not use FOREACH and IF tags in the same tag on Line {$this->element->line} <{$this->element->tag}>",
- null, HTML_TEMPLATE_FLEXY_ERROR_DIE);
- }
-
- // allow if="!somevar"
- $ifnegative = '';
-
- if ($if{0} == '!') {
- $ifnegative = '!';
- $if = substr($if,1);
- }
- // if="xxxxx"
- // if="xxxx.xxxx()" - should create a method prefixed with 'if:'
- // these checks should really be in the if/method class..!!!
-
-
-
- if (!preg_match('/^[_A-Z][A-Z0-9_]*(\[[0-9]+\])?((\[|%5B)[A-Z0-9_]+(\]|%5D))*'.
- '(\.[_A-Z][A-Z0-9_]*((\[|%5B)[A-Z0-9_]+(\]|%5D))*)*(\\([^)]*\))?$/i',$if)) {
- return HTML_Template_Flexy::raiseError(
- "IF tags only accept simple object.variable or object.method() values on
- Line {$this->element->line} <{$this->element->tag}>
- {$if}",
- null, HTML_TEMPLATE_FLEXY_ERROR_DIE);
- }
-
- if (substr($if,-1) == ')') {
- // grab args..
- $args = substr($if,strpos($if,'(')+1,-1);
- // simple explode ...
-
- $args = strlen(trim($args)) ? explode(',',$args) : array();
- //print_R($args);
-
- // this is nasty... - we need to check for quotes = eg. # at beg. & end..
- $args_clean = array();
- for ($i=0; $i<count($args); $i++) {
- if ($args[$i]{0} != '#') {
- $args_clean[] = $args[$i];
- continue;
- }
- // single # - so , must be inside..
- if ((strlen($args[$i]) > 1) && ($args[$i]{strlen($args[$i])-1}=='#')) {
- $args_clean[] = $args[$i];
- continue;
- }
-
- $args[$i] .=',' . $args[$i+1];
- // remove args+1..
- array_splice($args,$i+1,1);
- $i--;
- // reparse..
- }
-
-
-
- $ifObj = $this->element->factory('Method',
- array('if:'.$ifnegative.substr($if,0,strpos($if,'(')), $args_clean),
- $this->element->line);
- } else {
- $ifObj = $this->element->factory('If', $ifnegative.$if, $this->element->line);
- }
-
- // does it have a closetag? - you must have one - so you will have to hack in <span flexy:if=..><img></span> on tags
- // that do not have close tags - it's done this way to try and avoid mistakes.
-
-
- if (!$this->element->close) {
- //echo "<PRE>";print_R($this->element);
-
- if ($this->element->getAttribute('/') !== false) {
- $this->element->postfix = array($this->element->factory("End",'', $this->element->line));
- } else {
-
- return HTML_Template_Flexy::raiseError(
- "An flexy:if attribute was found in <{$this->element->name} tag without a corresponding </{$this->element->name}
- tag on Line {$this->element->line} <{$this->element->tag}>",
- null, HTML_TEMPLATE_FLEXY_ERROR_DIE);
- }
- } else {
-
- $this->element->close->postfix = array($this->element->factory("End",'', $this->element->line));
- }
- $this->element->clearAttribute('FLEXY:IF');
- return $ifObj->compile($this->compiler);
- }
-
- /**
- * Reads Tags - and relays to parseTagXXXXXXX
- *
- *
- * @return string | false = html output or ignore (just output the tag)
- * @access private
- */
-
-
- function _parseTags()
- {
- global $_HTML_TEMPLATE_FLEXY_TOKEN;
- // doesnt really need strtolower etc. as php functions are not case sensitive!
-
- if ($this->element->getAttribute('FLEXY:DYNAMIC')) {
- return $this->compiler->appendPhp(
- $this->getElementPhp( $this->element->getAttribute('ID') )
- );
-
- }
-
- if ($this->element->getAttribute('FLEXY:IGNOREONLY') !== false) {
- return false;
- }
- if ($_HTML_TEMPLATE_FLEXY_TOKEN['flexyIgnore']) {
- return false;
- }
- $tag = $this->element->tag;
- if (strpos($tag,':') !== false) {
- $bits = explode(':',$tag);
- $tag = $bits[1];
- }
-
- $method = 'parseTag'.$tag;
- if (!method_exists($this,$method)) {
- return false;
- }
- // do any of the attributes use flexy data...
- foreach ($this->element->attributes as $k=>$v) {
- if (is_array($v)) {
- return false;
- }
- }
-
- //echo "call $method" . serialize($this->element->attributes). "\n";
-
- return $this->$method();
- // allow the parse methods to return output.
-
- }
-
-
-
-
- /**
- * produces the code for dynamic elements
- *
- * @return string | false = html output or ignore (just output the tag)
- * @access public
- */
-
- function getElementPhp($id,$mergeWithName=false) {
-
- global $_HTML_TEMPLATE_FLEXY;
- static $tmpId=0;
- if (!$id) {
- return HTML_Template_Flexy::raiseError(
- "Error:{$_HTML_TEMPLATE_FLEXY['filename']} on Line {$this->element->line} <{$this->element->tag}>: " .
- " Dynamic tags require an ID value",
- null, HTML_TEMPLATE_FLEXY_ERROR_DIE);
- }
-
- // dont mix and match..
- if (($this->element->getAttribute('FLEXY:IF') !== false) ||
- ($this->element->getAttribute('FLEXY:FOREACH') !== false) )
- {
- return HTML_Template_Flexy::raiseError(
- "Error:{$_HTML_TEMPLATE_FLEXY['filename']} on Line {$this->element->line} <{$this->element->tag}>: " .
- " You can not mix flexy:if= or flexy:foreach= with dynamic form elements " .
- " (turn off tag to element code with flexyIgnore=0, use flexy:ignore="yes" in the tag" .
- " or put the conditional outside in a span tag",
- null, HTML_TEMPLATE_FLEXY_ERROR_DIE);
- }
-
- if ((strtolower($this->element->getAttribute('type')) == 'checkbox' ) &&
- (substr($this->element->getAttribute('name'),-2) == '[]')) {
- if ($this->element->getAttribute('id') === false) {
- $id = 'tmpId'. (++$tmpId);
- $this->element->attributes['id'] = $id;
- $this->element->ucAttributes['ID'] = $id;
- }
- $mergeWithName = true;
- }
-
-
-
-
-
- if (isset($_HTML_TEMPLATE_FLEXY['elements'][$id])) {
- // echo "<PRE>";print_r($this);print_r($_HTML_TEMPLATE_FLEXY['elements']);echo "</PRE>";
- return HTML_Template_Flexy::raiseError(
- "Error:{$_HTML_TEMPLATE_FLEXY['filename']} on Line {$this->element->line} in Tag <{$this->element->tag}>:<BR> " .
- "The Dynamic tag Name '$id' has already been used previously by tag <{$_HTML_TEMPLATE_FLEXY['elements'][$id]->tag}>",
- null,HTML_TEMPLATE_FLEXY_ERROR_DIE);
- }
-
- // this is for a case where you can use a sprintf as the name, and overlay it with a variable element..
- $_HTML_TEMPLATE_FLEXY['elements'][$id] = $this->toElement($this->element);
-
- if ($var = $this->element->getAttribute('FLEXY:NAMEUSES')) {
-
- $var = 'sprintf(\''.$id .'\','.$this->element->toVar($var) .')';
- return
- 'if (!isset($this->elements['.$var.'])) $this->elements['.$var.']= $this->elements[\''.$id.'\'];
- $this->elements['.$var.'] = $this->mergeElement($this->elements[\''.$id.'\'],$this->elements['.$var.']);
- $this->elements['.$var.']->attributes[\'name\'] = '.$var. ';
- echo $this->elements['.$var.']->toHtml();';
- } elseif ($mergeWithName) {
- $name = $this->element->getAttribute('NAME');
- return
- '$element = $this->elements[\''.$id.'\'];
- $element = $this->mergeElement($element,$this->elements[\''.$name.'\']);
- echo $element->toHtml();';
-
-
- } else {
- return 'echo $this->elements[\''.$id.'\']->toHtml();';
- }
- }
-
- /**
- * Reads an Script tag - check if PHP is allowed.
- *
- * @return false|PEAR_Error
- * @access public
- */
- function parseTagScript() {
-
-
- $lang = $this->element->getAttribute('LANGUAGE');
- if (!$lang) {
- return false;
- }
- $lang = strtoupper($lang);
-
- if ($GLOBALS['_HTML_TEMPLATE_FLEXY']['currentOptions']['allowPHP']) {
- return false;
- }
-
- if ($lang == "PHP") {
-
- return HTML_Template_Flexy::raiseError('PHP code found in script',
- HTML_TEMPLATE_FLEXY_ERROR_SYNTAX,HTML_TEMPLATE_FLEXY_ERROR_RETURN
- );
- }
- return false;
-
- }
- /**
- * Reads an Input tag - build a element object for it
- *
- *
- * @return string | false = html output or ignore (just output the tag)
- * @access public
- */
-
-
- function parseTagInput()
- {
- global $_HTML_TEMPLATE_FLEXY;
-
- if (in_array(strtoupper($this->element->getAttribute('TYPE')), array('SUBMIT','BUTTON','INPUT',''))) {
- $this->compiler->addStringToGettext($this->element->getAttribute('VALUE'));
- }
- // form elements : format:
- //value - fill out as PHP CODE
-
- // as a general rule, this uses name, rather than ID except on
- // radio
- $mergeWithName = false;
- $id = $this->element->getAttribute('NAME');
- // checkboxes need more work.. - at the momemnt assume one with the same value...
- if (in_array(strtoupper($this->element->getAttribute('TYPE')), array('RADIO'))) {
-
- if (!isset($_HTML_TEMPLATE_FLEXY['elements'][$id])) {
- // register it.. - so we dont overwrite it...
- $_HTML_TEMPLATE_FLEXY['elements'][$id] = false;
- } else if ($_HTML_TEMPLATE_FLEXY['elements'][$id] != false) {
-
-
- return HTML_Template_Flexy::raiseError(
- "Error:{$_HTML_TEMPLATE_FLEXY['filename']} on Line {$this->element->line} ".
- "in Tag <{$this->element->tag}>:<BR>".
- "The Dynamic tag Name '$id' has already been used previously by ".
- "tag <{$_HTML_TEMPLATE_FLEXY['elements'][$id]->tag}>",
- null, HTML_TEMPLATE_FLEXY_ERROR_DIE
- );
- }
-
- $id = $this->element->getAttribute('ID');
- if (!$id) {
- return HTML_Template_Flexy::raiseError("Error in {$_HTML_TEMPLATE_FLEXY['filename']} on Line {$this->element->line} <{$this->element->tag}>:
- Radio Input's require an ID tag..",
- null, HTML_TEMPLATE_FLEXY_ERROR_DIE);
- }
- $mergeWithName = true;
-
- }
- if (!$id) {
- return false;
- }
- return $this->compiler->appendPhp($this->getElementPhp( $id,$mergeWithName));
-
- }
-
- /**
- * Deal with a TextArea tag - build a element object for it
- *
- * @return string | false = html output or ignore (just output the tag)
- * @access public
- */
-
- function parseTagTextArea()
- {
-
- return $this->compiler->appendPhp(
- $this->getElementPhp( $this->element->getAttribute('NAME')));
-
-
-
- }
- /**
- * Deal with Selects - build a element object for it (unless flexyignore is set)
- *
- *
- * @return string | false = html output or ignore (just output the tag)
- * @access public
- */
-
- function parseTagSelect()
- {
- return $this->compiler->appendPhp(
- $this->getElementPhp( $this->element->getAttribute('NAME')));
- }
-
-
-
-
- /**
- * Reads an Form tag - and set up the element object header etc.
- *
- * @return string | false = html output or ignore (just output the tag)
- * @access public
- */
-
- function parseTagForm()
- {
- global $_HTML_TEMPLATE_FLEXY;
- $copy = clone($this->element);
- $copy->children = array();
- $id = $this->element->getAttribute('NAME');
- if (!$id) {
- $id = 'form';
- }
-
- // this adds the element to the elements array.
- $old = clone($this->element);
- $this->element = $copy;
- $this->getElementPhp($id);
- $this->element= $old;
-
-
- return
- $this->compiler->appendPhp('echo $this->elements[\''.$id.'\']->toHtmlnoClose();') .
- $this->element->compileChildren($this->compiler) .
- $this->compiler->appendHtml( "</{$copy->oTag}>");
-
- }
-
-
-
-
-
- /**
- * reWriteURL - can using the config option 'url_rewrite'
- * format "from:to,from:to"
- * only handle left rewrite.
- * so
- * "/images:/myroot/images"
- * would change
- * /images/xyz.gif to /myroot/images/xyz.gif
- * /images/stylesheet/imagestyles.css to /myroot/images/stylesheet/imagestyles.css
- * note /imagestyles did not get altered.
- * will only work on strings (forget about doing /images/{someimage}
- *
- *
- * @param string attribute to rewrite
- * @return none
- * @access public
- */
- function reWriteURL($which)
- {
- global $_HTML_TEMPLATE_FLEXY;
-
-
- if (!is_string($original = $this->element->getAttribute($which))) {
- return;
- }
-
- if ($original == '') {
- return;
- }
-
- if (empty($_HTML_TEMPLATE_FLEXY['currentOptions']['url_rewrite'])) {
- return;
- }
-
- $bits = explode(",",$_HTML_TEMPLATE_FLEXY['currentOptions']['url_rewrite']);
- $new = $original;
-
- foreach ($bits as $bit) {
- if (!strlen(trim($bit))) {
- continue;
- }
- $parts = explode (':', $bit);
- if (!isset($parts[1])) {
- return HTML_Template_Flexy::raiseError('HTML_Template_Flexy: url_rewrite syntax incorrect'.
- print_r(array($bits,$bits),true),null,HTML_TEMPLATE_FLEXY_ERROR_DIE);
- }
- $new = preg_replace('#^'.$parts[0].'#',$parts[1], $new);
- }
-
-
- if ($original == $new) {
- return;
- }
- $this->element->ucAttributes[$which] = '"'. $new . '"';
- }
-
- /**
- * Convert flexy tokens to HTML_Template_Flexy_Elements.
- *
- * @param object token to convert into a element.
- * @return object HTML_Template_Flexy_Element
- * @access public
- */
- function toElement($element) {
- require_once 'HTML/Template/Flexy/Element.php';
- $ret = new HTML_Template_Flexy_Element;
-
- if (strtolower(get_class($element)) != 'html_template_flexy_token_tag') {
- $this->compiler->addStringToGettext($element->value);
- return $element->value;
- }
-
-
- $ret->tag = strtolower($element->tag);
-
- $ats = $element->getAttributes();
-
- if (isset($element->attributes['flexy:xhtml'])) {
- $ats['flexy:xhtml'] = true;
- }
-
- foreach(array_keys($ats) as $a) {
- $ret->attributes[$a] = $this->unHtmlEntities($ats[$a]);
- }
- //print_r($ats);
- if (!$element->children) {
- return $ret;
- }
-
- // children - normally to deal with <element>
-
- //print_r($this->children);
- foreach(array_keys($element->children) as $i) {
- // not quite sure why this happens - but it does.
- if (!is_object($element->children[$i])) {
- continue;
- }
- $ret->children[] = $this->toElement($element->children[$i]);
- }
- return $ret;
- }
-
- /**
- * do the reverse of htmlspecialchars on an attribute..
- *
- * copied from get-html-translation-table man page
- *
- * @param mixed from attribute values
- *
- * @return string return
- * @access public
- * @see see also methods.....
- */
-
- function unHtmlEntities ($in)
- {
- if (!is_string($in)) {
- return $in;
- }
- $trans_tbl = get_html_translation_table (HTML_ENTITIES);
- $trans_tbl = array_flip ($trans_tbl);
- $ret = strtr ($in, $trans_tbl);
- return preg_replace('/&#(\d+);/me', "chr('\\1')",$ret);
- }
-
-}
-
-
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997, 1998, 1999, 2000, 2001 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Alan Knowles <alan@akbkhome.com> |
-// | Based on HTML_Common by: Adam Daniel <adaniel1@eesus.jnj.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Element.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-/**
- * Lightweight HTML Element builder and render
- *
- * This differs from HTML_Common in the following ways:
- *
- * $element->attributes is Public
- * $element->override if set to anything other than false, renders the value rather than
- * the defined element
- *
- * $element->children is a recursvable child array which is rendered by toHTML
- * $element->toHtml() is implemented
- * $element->toHtmlNoClose() renders only the first tag and children (designed for <form
- * No support for tab offsets, comments ...
- *
- * Full support for Select, and common Form elements using
- * setValue()
- * setOptions()
- *
- * overlay support with SetFrom - base + inherited..
- *
- * attributes array values:
- * key="value" // standard key="value" in output
- * key = true // outputs just key.
- *
- * children can be
- * another HTML_Element
- * or string (raw text)
- *
- *
- * @author Adam Daniel <adaniel1@eesus.jnj.com>
- * @version 1.6
- * @since PHP 4.0.3pl1
- * @abstract
- */
-class HTML_Template_Flexy_Element {
-
-
-
- /**
- * Tag that this Element represents.
- * @var array
- * @access public
- */
- var $tag = '';
- /**
- * Associative array of table attributes
- * Note Special values:
- * true == only display the key
- * false == remove
- *
- * @var array
- * @access public
- */
- var $attributes = array();
-
- /**
- * Sequence array of children
- * children that are strings are assumed to be text
- * @var array
- * @access public
- */
- var $children = array();
-
- /**
- * override the tag.
- * if this is set to anything other than false, it will be output
- * rather than the tags+children
- * @var array
- * @access public
- */
- var $override = false;
- /**
- * prefix the tag.
- * this is output by toHtml as a prefix to the tag (can be used for require tags)
- * @var array
- * @access private
- */
- var $prefix = '';
- /**
- * suffix the tag.
- * this is output by toHtml as a suffix to the tag (can be used for error messages)
- * @var array
- * @access private
- */
- var $suffix = '';
-
- /**
- * a value for delayed merging into live objects
- * if you set this on an element, it is merged by setValue, at merge time.
- * @var array
- * @access public
- */
- var $value = null;
- /**
- * Class constructor
- * @param mixed $attributes Associative array of table tag attributes
- * or HTML attributes name="value" pairs
- * @access public
- */
- function HTML_Template_Flexy_Element($tag='', $attributes=null)
- {
-
- $this->tag = strtolower($tag);
- if (false !== strpos($tag, ':')) {
- $bits = explode(':',$this->tag);
- $this->tag = $bits[0] . ':'.strtolower($bits[1]);
- }
-
- $this->setAttributes($attributes);
- } // end constructor
-
-
- /**
- * Returns an HTML formatted attribute string
- * @param array $attributes
- * @return string
- * @access private
- */
- function attributesToHTML()
- {
- $strAttr = '';
- $xhtmlclose = '';
- $charset = empty($GLOBALS['HTML_Template_Flexy']['options']['charset']) ? 'ISO-8859-1' : $GLOBALS['HTML_Template_Flexy']['options']['charset'];
- foreach ($this->attributes as $key => $value) {
-
- // you shouldn't do this, but It shouldnt barf when you do..
- if (is_array($value) || is_object($value)) {
- continue;
- }
-
- if ($key == 'flexy:xhtml') {
- continue;
- }
- if ($value === false) {
- continue;
- }
- if ($value === true) {
- // this is not xhtml compatible..
- if ($key == '/') {
- $xhtmlclose = ' /';
- continue;
- }
- if (isset($this->attributes['flexy:xhtml'])) {
- $strAttr .= " {$key}=\"{$key}\"";
- } else {
- $strAttr .= ' ' . $key;
- }
- } else {
- // dont replace & with &
- if ($this->tag == 'textbox') { // XUL linefeed fix.
- $value = str_replace("\n", ' ', htmlspecialchars($value,ENT_COMPAT,$charset));
- } else {
- $value = str_replace('&nbsp;',' ',htmlspecialchars($value,ENT_COMPAT,$charset));
- }
- $strAttr .= ' ' . $key . '="' . $value . '"';
- }
-
- }
- $strAttr .= $xhtmlclose;
- return $strAttr;
- } // end func _getAttrString
-
- /**
- * Static Method to get key/value array from attributes.
- * Returns a valid atrributes array from either a string or array
- * @param mixed $attributes Either a typical HTML attribute string or an associative array
- * @access private
- */
- function parseAttributes($attributes)
- {
- if (is_array($attributes)) {
- $ret = array();
- foreach ($attributes as $key => $value) {
- if (is_int($key)) {
- $ret[strtolower($value)] = true;
- } else {
- $ret[strtolower($key)] = $value;
- }
- }
- return $ret;
-
- } elseif (is_string($attributes)) {
- $preg = "/(([A-Za-z_:]|[^\\x00-\\x7F])([A-Za-z0-9_:.-]|[^\\x00-\\x7F])*)" .
- "([ \\n\\t\\r]+)?(=([ \\n\\t\\r]+)?(\"[^\"]*\"|'[^']*'|[^ \\n\\t\\r]*))?/";
- if (preg_match_all($preg, $attributes, $regs)) {
- for ($counter=0; $counter<count($regs[1]); $counter++) {
- $name = $regs[1][$counter];
- $check = $regs[0][$counter];
- $value = $regs[7][$counter];
- if (trim($name) == trim($check)) {
- $arrAttr[strtolower(trim($name))] = strtolower(trim($name));
- } else {
- if (substr($value, 0, 1) == "\"" || substr($value, 0, 1) == "'") {
- $value = substr($value, 1, -1);
- }
- $arrAttr[strtolower(trim($name))] = trim($value);
- }
- }
- return $arrAttr;
- }
- }
- } // end func _parseAttributes
-
-
-
-
- /**
- * Utility function to set values from common tag types.
- * @param HTML_Element $from override settings from another element.
- * @access public
- */
-
- function setValue($value) {
- // store the value in all situations
- $this->value = $value;
- $tag = strtolower($this->tag);
- if (strpos($tag,':') !== false) {
- $bits = explode(':',$tag);
- $tag = $bits[1];
- }
- switch ($tag) {
- case 'input':
- switch (isset($this->attributes['type']) ? strtolower($this->attributes['type']) : '') {
- case 'checkbox':
- if (isset($this->attributes['checked'])) {
- unset($this->attributes['checked']);
- }
- // if value is nto set, it doesnt make any difference what you set ?
- if (!isset($this->attributes['value'])) {
- return;
- }
- //print_r($this); echo "SET TO "; serialize($value);
- if (isset($this->attributes['name']) && (substr($this->attributes['name'],-2) == '[]')) {
- if (is_array($value) &&
- in_array((string) $this->attributes['value'],$value)
- ) {
- $this->attributes['checked'] = true;
- }
- return;
- }
- if ($this->attributes['value'] == $value) {
- $this->attributes['checked'] = true;
- }
-
-
- return;
- case 'radio':
- if (isset($this->attributes['checked'])) {
- unset($this->attributes['checked']);
- }
- // if we dont have values associated yet, store it..
- if (!isset($this->attributes['value'])) {
- $this->value = $value;
- return;
- }
- if ($this->attributes['value'] == $value) {
- $this->attributes['checked'] = true;
- }
- return;
-
- default:
- // no other input accepts array as a value.
- if (is_array($value)) {
- return;
- }
-
- $this->attributes['value'] = $value;
- return;
- }
-
- case 'select':
-
- if (!is_array($value)) {
- $value = array($value);
- }
-
- // its setting the default value..
-
- foreach($this->children as $i=>$child) {
-
- if (is_string($child)) {
- continue;
- }
- if ($child->tag == 'optgroup') {
- foreach($this->children[$i]->children as $ii=>$child) {
-
- // does the value exist and match..
- if (isset($child->attributes['value'])
- && in_array((string) $child->attributes['value'], $value))
- {
- $this->children[$i]->children[$ii]->attributes['selected'] =
- isset($this->attributes['flexy:xhtml']) ? 'selected' : true;
- continue;
- }
- if (isset($child->attributes['value']) &&
- isset($this->children[$i]->children[$ii]->attributes['selected']))
- {
- unset($this->children[$i]->children[$ii]->attributes['selected']);
- continue;
- }
- // value doesnt exst..
-
- if (isset($this->children[$i]->children[$ii]->attributes['selected'])) {
- unset($this->children[$i]->children[$ii]->attributes['selected']);
- continue;
- }
- }
- continue;
- }
-
- // standard option value...
- //echo "testing {$child->attributes['value']} against ". print_r($value,true)."\n";
- // does the value exist and match..
-
- if (isset($child->attributes['value'])
- && in_array((string) $child->attributes['value'], $value))
- {
-
-
- $this->children[$i]->attributes['selected'] =
- isset($this->attributes['flexy:xhtml']) ? 'selected' : true;;
- continue;
- }
- // no value attribute try and use the contents.
- if (!isset($child->attributes['value'])
- && is_string($child->children[0])
- && in_array((string) $child->children[0], $value))
- {
-
- $this->children[$i]->attributes['selected'] =
- isset($this->attributes['flexy:xhtml']) ? 'selected' : true;
- continue;
- }
-
- if (isset($child->attributes['value']) &&
- isset($this->children[$i]->attributes['selected']))
- {
- //echo "clearing selected\n";
- unset($this->children[$i]->attributes['selected']);
- continue;
- }
- // value doesnt exst..
-
- if (isset($this->children[$i]->attributes['selected'])) {
- //echo "clearing selected\n";
- unset($this->children[$i]->attributes['selected']);
- continue;
- }
-
-
- }
- return;
- case 'textarea':
- case 'label':
- $charset = empty($GLOBALS['HTML_Template_Flexy']['options']['charset']) ? 'ISO-8859-1' : $GLOBALS['HTML_Template_Flexy']['options']['charset'];
- $this->children = array(htmlspecialchars($value,ENT_COMPAT,$charset));
- return;
- case '': // dummy objects.
- $this->value = $value;
- return;
-
- // XUL elements
- case 'menulist':
- case 'textbox':
- case 'checkbox':
- require_once 'HTML/Template/Flexy/Element/Xul.php';
- HTML_Template_Flexy_Element_Xul::setValue($this,$value);
- return ;
-
- default:
- if (is_array($value)) {
- return;
- }
- $this->value = $value;
- }
-
-
-
-
- }
- /**
- * Utility function equivilant to HTML_Select - loadArray **
- * but using
- * key=>value maps
- * <option value="key">Value</option>
- * Key=key (eg. both the same) maps to
- * <option>key</option>
- * and label = array(key=>value) maps to
- * <optgroup label="label"> <option value="key">value</option></optgroup>
- *
- * $element->setOptions(array('a'=>'xxx','b'=>'yyy'));
- * or
- * $element->setOptions(array('a','b','c','d'),true);
- *
- *
- *.
- * @param HTML_Element $from override settings from another element.
- * @param HTML_Element $noValue ignore the key part of the array
- * @access public
- */
-
- function setOptions($array,$noValue=false)
- {
- if (!is_array($array)) {
- $this->children = array();
- return;
- }
-
- $charset = empty($GLOBALS['HTML_Template_Flexy']['options']['charset']) ? 'ISO-8859-1' : $GLOBALS['HTML_Template_Flexy']['options']['charset'];
-
- $tag = strtolower($this->tag);
- $namespace = '';
- if (false !== strpos($this->tag, ':')) {
-
- $bits = explode(':',$this->tag);
- $namespace = $bits[0] . ':';
- $tag = strtolower($bits[1]);
-
- }
- // if we have specified a xultag!!?
- if (strlen($tag) && ($tag != 'select')) {
- require_once 'HTML/Template/Flexy/Element/Xul.php';
- return HTML_Template_Flexy_Element_Xul::setOptions($this,$array,$noValue);
- }
-
- foreach($array as $k=>$v) {
- if (is_array($v)) { // optgroup
- $child = new HTML_Template_Flexy_Element($namespace . 'optgroup',array('label'=>$k));
- foreach($v as $kk=>$vv) {
- $atts=array();
- if (($kk !== $vv) && !$noValue) {
- $atts = array('value'=>$kk);
- } else {
- $atts = array('value'=>$vv);
- }
- $add = new HTML_Template_Flexy_Element($namespace . 'option',$atts);
- $add->children = array(htmlspecialchars($vv,ENT_COMPAT,$charset));
- $child->children[] = $add;
- }
- $this->children[] = $child;
- continue;
- }
- $atts=array();
- if (($k !== $v) && !$noValue) {
- $atts = array('value'=>$k);
- } else {
- $atts = array('value'=>$v);
- }
- $add = new HTML_Template_Flexy_Element($namespace . 'option',$atts);
- $add->children = array(htmlspecialchars($v,ENT_COMPAT,$charset));
- $this->children[] = $add;
- }
-
- }
-
-
-
- /**
- * Returns THIS select element's options as an associative array
- * Validates that $this element is "select"
- * @return array $options
- * @access public
- */
- function getOptions()
- {
-
- $tag = strtolower($this->tag);
- $namespace = '';
- if (false !== strpos($this->tag, ':')) {
- $bits = explode(':',$this->tag);
- $namespace = $bits[0] . ':';
- $tag = strtolower($bits[1]);
- }
-
- // this is not a select element
- if (strlen($tag) && ($tag != 'select')) {
- return false;
- }
-
- // creates an associative array that can be used by setOptions()
- // null does work for no value ( a "Please Choose" option, for example)
- foreach ($this->children as $child) {
- if (is_object($child)) {
- $child->attributes['value'] = isset($child->attributes['value']) ? $child->attributes['value'] : '';
- $children[$child->attributes['value']] = $child->children[0];
- }
- }
- return $children;
- }
-
- /**
- * Removes all of this element's options
- * Validates that $this element is "select"
- * @return bool result
- * @access public
- */
- function clearOptions($children = array())
- {
- $tag = strtolower($this->tag);
- $namespace = '';
- if (false !== strpos($this->tag, ':')) {
- $bits = explode(':',$this->tag);
- $namespace = $bits[0] . ':';
- $tag = strtolower($bits[1]);
- }
-
- // this is not a select element
- if (strlen($tag) && ($tag != 'select')) {
- return false;
- }
-
- // clear this select's options
- $this->children = array(null);
- $this->values = array(null);
-
- // If called with an array of new options go ahead and set them
- $this->setOptions($children);
-
- return true;
- }
-
- /**
- * Sets the HTML attributes
- * @param mixed $attributes Either a typical HTML attribute string or an associative array
- * @access public
- */
-
- function setAttributes($attributes)
- {
- $attrs= $this->parseAttributes($attributes);
- if (!is_array($attrs)) {
- return false;
- }
- foreach ($attrs as $key => $value) {
- $this->attributes[$key] = $value;
- }
- } // end func updateAttributes
-
- /**
- * Removes an attributes
- *
- * @param string $attr Attribute name
- * @since 1.4
- * @access public
- * @return void
- * @throws
- */
- function removeAttributes($attrs)
- {
- if (is_string($attrs)) {
- $attrs = array($attrs);
- }
- foreach ($attrs as $attr) {
- if (isset($this->attributes[strtolower($attr)])) {
- $this->attributes[strtolower($attr)] = false;
- }
- }
- } //end func removeAttribute
-
-
- /**
- * Output HTML and children
- *
- * @access public
- * @param object $overlay = merge data from object.
- * @return string
- * @abstract
- */
- function toHtml($overlay=false)
- {
-
- //echo "BEFORE<PRE>";print_R($this);
- $ret = $this;
- if ($overlay !== false) {
- $ret = HTML_Template_Flexy::mergeElement($this,$overlay);
- }
-
- if ($ret->override !== false) {
- return $ret->override;
- }
- $prefix = $ret->prefix;
- if (is_object($prefix)) {
- $prefix = $prefix->toHtml();
- }
- $suffix = $ret->suffix;
- if (is_object($suffix)) {
- $suffix = $suffix->toHtml();
- }
- //echo "AFTER<PRE>";print_R($ret);
-
- $tag = $this->tag;
- if (strpos($tag,':') !== false) {
- $bits = explode(':',$tag);
- $tag = $bits[1];
- }
- // tags that never should have closers
- $close = "</{$ret->tag}>";
- if (in_array(strtoupper($tag),array("INPUT","IMG", "LINK", "META", "HR", "BR"))) {
- $close = '';
- }
- if (isset($this->attributes['/'])) {
- $close = '';
- }
-
- $close .= $suffix ;
-
- return "{$prefix}<{$ret->tag}".$ret->attributesToHTML() . '>'.$ret->childrenToHTML() .$close;
-
-
- } // end func toHtml
-
-
- /**
- * Output Open Tag and any children and not Child tag (designed for use with <form + hidden elements>
- *
- * @access public
- * @param object $overlay = merge data from object.
- * @return string
- * @abstract
- */
- function toHtmlnoClose($overlay=false)
- {
- $ret = $this;
- if ($ret->override !== false) {
- return $ret->override;
- }
- if ($overlay !== false) {
- $ret = HTML_Template_Flexy::mergeElement($this,$overlay);
- }
-
-
- return "<{$ret->tag}".$ret->attributesToHTML() . '>' . $ret->childrenToHTML();
-
-
- } // end func toHtml
-
-
- /**
- * Output HTML and children
- *
- * @access public
- * @return string
- * @abstract
- */
- function childrenToHtml()
- {
- $ret = '';
- foreach($this->children as $child) {
- if (!is_object($child)) {
- $ret .= $child;
- continue;
- }
-
- $ret .= $child->toHtml();
- }
- return $ret;
- } // end func toHtml
-
-
-
-
-
-} // end class HTML_Template_Flexy_Element
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997, 1998, 1999, 2000, 2001 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Alan Knowles <alan@akbkhome.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Xul.php,v 1.1.1.1 2008/04/28 15:20:50 jamie Exp $
-
-/**
- * Extension HTML Element builder and render to provide features for Xul
- *
- * All methods are static, and expect the first argument to be a HTML_Template_Flexy_Element
- *
- * @author Alan Knowles <alan@akbkhome.com>
- */
-class HTML_Template_Flexy_Element_Xul {
-
-
- /**
- * Utility function to set values for common tag types.
- * @param HTML_Template_Flexy_Element $element override settings from another element.
- * @param mixed $value value to use.
- * @access public
- */
-
- function setValue(&$element,$value) {
- // store the value in all situations
- $element->value = $value;
- $tag = $element->tag;
- if (strpos($tag,':') !== false) {
- $bits = explode(':',$tag);
- $tag = $bits[1];
- }
- switch ($tag) {
- case 'menulist':
-
- if (!is_array($value)) {
- $value = array($value);
- }
-
- // is the first childa menupopup
- if (!isset($element->children[0])) {
- $element->children[0] = HTML_Template_Flexy_Element('menupopup');
- }
- if (!is_a($element->children[0],'HTML_Template_Flexy_Element')) {
- // oh sh*t big problem!
- return HTML_Template_Flexy::raiseError(
- __CLASS__ . '::setValue expected a Flexy Element as the child of a menuitem but got something else! '.
- print_r($element,true),
- HTML_TEMPLATE_FLEXY_ERROR_SYNTAX,
- HTML_TEMPLATE_FLEXY_ERROR_DIE);
- }
-
-
- // its setting the default value..
- // if the children havent been built we dont really care?
- // it will be done at the merge stage anyway..
-
- foreach(array_keys($element->children[0]->children) as $i) {
- $child = &$element->children[0]->children[$i];
-
- if (is_string($child)) {
- continue;
- }
-
-
- // standard option value...
- //echo "testing {$child->attributes['value']} against ". print_r($value,true)."\n";
- // does the value exist and match..
-
- if (isset($child->attributes['value'])
- && in_array((string) $child->attributes['value'], $value))
- {
- // echo "MATCH!\n";
- $child->attributes['selected'] = 'true';
- continue;
- }
-
- // otherwise..
- $child->attributes['selected'] = 'false';
-
- }
-
- return;
-
- case 'textbox':
- $this->attributes['value'] = $value;
- return;
-
- case 'checkbox':
- if (!isset($this->attributes['value'])) {
- return; // should be an error condition really...
- }
- $this->attributes['checked'] = ($value == $this->attributes['value']) ? 'true' : 'false';
- return;
-
- }
-
-
-
-
- }
- /**
- * Utility function equivilant to HTML_Select - loadArray ** For xul:menulist.
- * but using
- * key=>value maps
- * <option value="key">Value</option>
- * Key=key (eg. both the same) maps to
- *
- *
- *
- * @param HTML_Element $from override settings from another element.
- * @param HTML_Element $noValue ignore the key part of the array
- * @access public
- */
-
- function setOptions(&$element, $array,$noValue=false) {
- if (!is_array($array)) {
- $element->children = array();
- return;
- }
-
-
- $tag = '';
- $namespace = '';
- if (false !== strpos($element->tag, ':')) {
-
- $bits = explode(':',$element->tag);
- $namespace = $bits[0] . ':';
- $tag = strtolower($bits[1]);
-
- }
- if (!isset($element->children[0])) {
- $element->children[0] = new HTML_Template_Flexy_Element('menupopup');
- }
- if (!is_a($element->children[0],'HTML_Template_Flexy_Element')) {
- // oh sh*t big problem!
- return HTML_Template_Flexy::raiseError(
- __CLASS__ . '::setValue expected a menupopup as the child of a menuitem?',
- HTML_TEMPLATE_FLEXY_ERROR_SYNTAX,
- HTML_TEMPLATE_FLEXY_ERROR_DIE);
- }
- foreach($array as $k=>$v) {
-
- $atts=array();
- if (($k !== $v) && !$noValue) {
- $atts = array('value'=>$k);
- } else {
- $atts = array('value'=>$v);
- }
- $atts['label'] = htmlspecialchars($v);
- $atts['/'] = true;
- $add = new HTML_Template_Flexy_Element($namespace . 'menuitem',$atts);
- $element->children[0]->children[] = $add;
- }
-
- }
-
-
-
-
-
-} // end class HTML_Template_Flexy_Element
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: nobody <nobody@localhost> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Factory.php,v 1.1.1.1 2008/04/28 15:20:50 jamie Exp $
-//
-// Factory tools for managing groups of HTML_Elements
-//
-
-require_once 'HTML/Template/Flexy/Element.php';
-
-class HTML_Template_Flexy_Factory {
-
-
- /**
- * fromArray - builds a set of elements from a key=>value array (eg. DO->toArray())
- * the second parameter is an optional HTML_Element array to merge it into.
- *
- *
- * @param array key(tag name) => value
- * @param optional array key(tag name) => HTML_Element
- *
- * @return array Array of HTML_Elements
- * @access public
- */
-
- function fromArray($ar,$ret=array())
- {
-
- foreach($ar as $k=>$v) {
- if (is_array($v)) {
- $ret = HTML_Template_Flexy_Factory::fromArrayPrefixed($k,$v,$ret);
- }
-
-
- if (!isset($ret[$k])) {
- $ret[$k] = new HTML_Template_Flexy_Element();
- }
- $ret[$k]->setValue($v);
- }
- return $ret;
- }
-
- /**
- * fromArrayPrefixed - takes a multi dimensional array, and builds the 'xxx[sss][xx]' => value
- *
- * @param array key(tag name) => value
- * @param array key(tag name) => value
- * @param optional array key(tag name) => HTML_Element
- *
- * @return array Array of HTML_Elements
- * @access public
- */
-
- function fromArrayPrefixed($prefix, $ar,$ret=array())
- {
-
- foreach($ar as $k=>$v) {
- if (is_array($v)) {
- $ret = HTML_Template_Flexy_Factory::fromArrayPrefixed($prefix.'['.$k.']',$v,$ret);
- if (!isset($ret[$prefix.'['.$k.'][]'])) {
- $ret[$prefix.'['.$k.'][]'] = new HTML_Template_Flexy_Element();
- }
- $ret[$prefix.'['.$k.'][]']->setValue($v);
- }
-
- if (!isset($ret[$prefix.'['.$k.']'])) {
- $ret[$prefix.'['.$k.']'] = new HTML_Template_Flexy_Element();
- }
- $ret[$prefix.'['.$k.']']->setValue($v);
-
-
-
- }
- return $ret;
- }
-
-
- /**
- * setErrors - sets the suffix of an element to a value..
- *
- * HTML_Element_Factory::setErrors($elements,array('name','not long enough'));
- *
- * @depreciated - this is really outside the scope of Factory - it should be
- * seperated into a rendering toolkit of some kind.
-
- * @param array of HTML_Element's
- * @param array key(tag name) => error
- * @param string sprintf error format..
- *
- * @return array Array of HTML_Elements
- * @access public
- */
-
- function &setErrors(&$ret,$set,$format='<span class="error">%s</span>')
- {
- if (empty($ret) || !is_array($ret)) {
- $ret = array();
- }
- // check what you send this.. !!!
- if (!is_array($set)) {
- return HTML_Template_Flexy::raiseError(
- 'invalid arguments "$set" (should be an array) sent to HTML_Template_Flexy_Factory::setErrors',
- 0, HTML_TEMPLATE_FLEXY_ERROR_DIE);
- }
- foreach($set as $k=>$v) {
- if (!$v) {
- continue;
- }
- if (!isset($ret[$k])) {
- $ret[$k] = new HTML_Template_Flexy_Element;
- }
- $ret[$k]->suffix .= sprintf($format,$v);
- }
- return $ret;
- }
-
-
- /**
- * setRequired - sets the prefix of an element to a value..
- *
- * HTML_Element_Factory::setRequired($elements,array('name',true));
- *
- * @depreciated - this is really outside the scope of Factory - it should be
- * seperated into a rendering toolkit
- *
- * @param array of HTML_Element's
- * @param array key(tag name) => error
- * @param string sprintf error format..
- *
- *
- * @return array Array of HTML_Elements
- * @access public
- */
-
- function &setRequired(&$ret,$set,$format='<span class="required">*</span>')
- {
-
-
- if (empty($ret) || !is_array($ret)) {
- $ret = array();
- }
- foreach($set as $k=>$v) {
- if (!$v) {
- continue;
- }
- if (!isset($ret[$k])) {
- $ret[$k] = new HTML_Template_Flexy_Element();
- }
- $ret[$k]->prefix .= sprintf($format,$v);
- }
- return $ret;
- }
-
-
- /**
- * freeze - freeze's an element. - just copies the value to the override.
- * this probably needs more thought.. - it would probably need to merge
- * the full tag info with types, to be usefull..
- *
- * $ar = HTML_Element_Factory::freeze($ar);
- *
- * @depreciated - this is really outside the scope of Factory - it should be
- * seperated into a rendering toolkit
- *
- *
- * @param array (return by referencekey(tag name) => HTML_Element
- *
- * @return array Array of HTML_Elements
- * @access public
- */
- function freeze(&$array) {
-
- foreach($array as $k=>$v) {
- $array[$k]->override = $array[$k]->value;
- }
- }
-
-
-}
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: nobody <nobody@localhost> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Plugin.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-//
-// Plugin API provides support for < ? = $this->plugin(".....",.....); ? >
-// or {this.plugin(#xxxxx#,#xxxx#):h}
-//
-// BASICALLY THIS IS SAVANT'S PLUGIN PROVIDER.
-// @author Paul M. Jones <pmjones@ciaweb.net>
-
-
-class HTML_Template_Flexy_Plugin {
-
- /**
- * reference to main engine..
- *
- * @var object HTML_Template_Flexy
- * @access public
- */
- var $flexy; // reference to flexy.
- var $pluginCache = array(); // store of instanced plugins..
-
- /**
- * Call a Plugin method.
- *
- * Look up in all the plugins to see if the method exists, if it does, call it.
- *
- *
- * @param array name of method, arguments.
- *
- *
- * @return string hopefully
- * @access public
- */
-
- function call($args)
- {
-
-
- $method = $args[0];
- // attempt to load the plugin on-the-fly
- $class = $this->_loadPlugins($method);
-
- if (is_a($class,'PEAR_Error')) {
- //echo $class->toString();
- return $class->toString();
- }
-
-
- // first argument is always the plugin name; shift the first
- // argument off the front of the array and reduce the number of
- // array elements.
- array_shift($args);
-
- return call_user_func_array(array(&$this->plugins[$class],$method), $args);
- }
-
- /**
- * Load the plugins, and lookup which one provides the required method
- *
- *
- * @param string Name
- *
- * @return string|PEAR_Error the class that provides it.
- * @access private
- */
-
- function _loadPlugins($name)
- {
- // name can be:
- // ahref = maps to {class_prefix}_ahref::ahref
- $this->plugins = array();
- if (empty($this->plugins)) {
-
- foreach ($this->flexy->options['plugins'] as $cname=>$file) {
- if (!is_int($cname)) {
- include_once $file;
- $this->plugins[$cname] = new $cname;
- $this->plugins[$cname]->flexy = &$this->flexy;
- continue;
- }
- $cname = $file;
- require_once 'HTML/Template/Flexy/Plugin/'. $cname . '.php';
- $class = "HTML_Template_Flexy_Plugin_{$cname}";
- $this->plugins[$class] = new $class;
- $this->plugins[$class]->flexy = &$this->flexy;
- }
- }
-
-
- foreach ($this->plugins as $class=>$o) {
- //echo "checking :". get_class($o). ":: $name\n";
- if (method_exists($o,$name)) {
- return $class;
- }
- }
- return HTML_Template_Flexy::raiseError("could not find plugin with method: '$name'");
- }
-
-
-}
+++ /dev/null
-<?php
-
-/**
-* it under the terms of the GNU Lesser General Public License as
-* published by the Free Software Foundation; either version 2.1 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
-* Lesser General Public License for more details.
-*
-* @license http://www.gnu.org/copyleft/lesser.html LGPL
-*
-*/
-class HTML_Template_Flexy_Plugin_Savant {
- /**
- * Output an HTML <a href="">...</a> tag.
- *
- * @author Paul M. Jones <pmjones@ciaweb.net>
- *
- * @package Savant
- *
- *
- * @access public
- *
- * @param string $href The URL for the resulting <a href="">...</a> tag.
- *
- * @param string $text The text surrounded by the <a>...</a> tag set.
- *
- * @param string $extra Any "extra" HTML code to place within the <a>
- * opening tag.
- *
- * @return string
- */
-
-
-
- function ahref($href, $text, $extra = null)
- {
- $output = '<a href="' . $href . '"';
-
- if (! is_null($extra)) {
- $output .= ' ' . $extra;
- }
-
- $output .= '>' . $text . '</a>';
-
- return $output;
- }
-
- /**
- *
- * Output a single checkbox <input> element.
-
- * @author Paul M. Jones <pmjones@ciaweb.net>
- *
- * @package Savant
- *
- * @version $Id: Savant.php,v 1.1.1.1 2008/04/28 15:20:50 jamie Exp $
- *
- * @access public
- *
- * @param string $name The HTML "name=" value for the checkbox.
- *
- * @param mixed $value The value of the checkbox if checked.
- *
- * @param mixed $selected Check $value against this; if they match,
- * mark the checkbox as checked.
- *
- * @param string $set_unchecked If null, this will add no HTML to the
- * output. However, if set to any non-null value, the value will be
- * added as a hidden element before the checkbox so that if the
- * checkbox is unchecked, the hidden value will be returned instead
- * of the checked value.
- *
- * @param string $extra Any "extra" HTML code to place within the
- * checkbox element.
- *
- * @return string
- *
- */
- function checkbox(
- $name,
- $value,
- $selected = null,
- $set_unchecked = null,
- $extra = null)
- {
- $html = '';
-
- if (! is_null($set_unchecked)) {
- // this sets the unchecked value of the checkbox.
- $html .= "<input type=\"hidden\" ";
- $html .= "name=\"$name\" ";
- $html .= "value=\"$set_unchecked\" />\n";
- }
-
- $html .= "<input type=\"checkbox\" ";
- $html .= "name=\"$name\" ";
- $html .= "value=\"$value\"";
-
- if ($value == $selected) {
- $html .= " checked=\"checked\"";
- }
-
- $html .= " $extra />";
-
- return $html;
- }
-
- /**
- *
- * Output a set of checkbox <input>s.
- *
- *
- * @author Paul M. Jones <pmjones@ciaweb.net>
- *
- * @package Savant
- *
- * @version $Id: Savant.php,v 1.1.1.1 2008/04/28 15:20:50 jamie Exp $
- *
- * @access public
- *
- * @param string $name The HTML "name=" value of all the checkbox
- * <input>s. The name will get [] appended to it to make it an array
- * when returned to the server.
- *
- * @param array $options An array of key-value pairs where the key is
- * the checkbox value and the value is the checkbox label.
- *
- * @param string $set_unchecked If null, this will add no HTML to the
- * output. However, if set to any non-null value, the value will be
- * added as a hidden element before every checkbox so that if the
- * checkbox is unchecked, the hidden value will be returned instead
- * of the checked value.
- *
- * @param string $sep The HTML text to place between every checkbox
- * in the set.
- *
- * @param string $extra Any "extra" HTML code to place within the
- * checkbox element.
- *
- * @return string
- *
- */
-
- function checkboxes(
-
- $name,
- $options,
- $selected = array(),
- $set_unchecked = null,
- $sep = "<br />\n",
- $extra = null)
- {
- // force $selected to be an array. this allows multi-checks to
- // have multiple checked boxes.
- settype($selected, 'array');
-
- // the text to be returned
- $html = '';
-
- if (is_array($options)) {
-
- // an iteration counter. we use this to track which array
- // elements are checked and which are unchecked.
- $i = 0;
-
- foreach ($options as $value => $label) {
-
- if (! is_null($set_unchecked)) {
- // this sets the unchecked value of the checkbox.
- $html .= "<input type=\"hidden\" ";
- $html .= "name=\"{$name}[$i]\" ";
- $html .= "value=\"$set_unchecked\" />\n";
- }
-
-
- $html .= "<input type=\"checkbox\" ";
- $html .= "name=\"{$name}[$i]\" ";
- $html .= "value=\"$value\"";
-
- if (in_array($value, $selected)) {
- $html .= " checked=\"checked\"";
- }
-
- if (! is_null($extra)) {
- $html .= " $extra";
- }
-
- $html .= " />$label$sep";
-
- $i++;
- }
- }
-
- return $html;
- }
-
-
-
- /**
- *
- * Cycle through a series of values based on an iteration number,
- * with optional group repetition.
- *
- * For example, if you have three values in a cycle (a, b, c) the iteration
- * returns look like this:
- *
- * 0 => a
- * 1 => b
- * 2 => c
- * 3 => a
- * 4 => b
- * 5 => c
- *
- * If you repeat each cycle value (a,b,c) 2 times on the iterations,
- * the returns look like this:
- *
- * 0 => a
- * 1 => a
- * 2 => b
- * 3 => b
- * 4 => c
- * 5 => c
- *
- *
- * @author Paul M. Jones <pmjones@ciaweb.net>
- *
- * @package Savant
- *
- * @version $Id: Savant.php,v 1.1.1.1 2008/04/28 15:20:50 jamie Exp $
- *
- * @access public
- *
- * @param int $iteration The iteration number for the cycle.
- *
- * @param array $values The values to cycle through.
- *
- * @param int $repeat The number of times to repeat a cycle value.
- *
- * @return string
- *
- */
- function cycle($iteration, $values = null, $repeat = 1)
- {
- settype($values, 'array');
-
- // prevent divide-by-zero errors
- if ($repeat == 0) {
- $repeat = 1;
- }
-
- return $values[($iteration / $repeat) % count($values)];
- }
-
-
- /**
- *
- * Output a formatted date using strftime() conventions.
- *
- *
- * @author Paul M. Jones <pmjones@ciaweb.net>
- *
- * @package Savant
- *
- * @version $Id: Savant.php,v 1.1.1.1 2008/04/28 15:20:50 jamie Exp $
- *
- * @access public
- *
- * @param string $datestring Any date-time string suitable for
- * strtotime().
- *
- * @param string $format The strftime() formatting string.
- *
- * @return string
- *
- */
-
- function dateformat($datestring, $format = false)
- {
- if ($format === false) {
- $format = isset($this->flexy->options['plugin.dateformat']) ?
- $this->flexy->options['plugin.dateformat'] : '%d %b %Y';
- }
- if (trim($datestring) == '') {
- return '';
- }
-
- $date = strtotime($datestring);
- if ($date > 1) {
- return strftime($format, $date);
- }
- require_once 'Date.php';
- $date = new Date($date);
- return $date->format($format);
-
- }
- /**
- *
- * Output a formatted number using number_format
- *
- *
- *
- * @param string $datestring Any date-time string suitable for
- * strtotime().
- *
- * @param string $format The strftime() formatting string.
- *
- * @return string
- *
- */
-
- function numberformat($number, $dec=false,$point=false,$thousands=false)
- {
- if (!strlen(trim($number))) {
- return;
- }
- // numberformat int decimals, string dec_point, string thousands_sep
- $dec = ($dec !== false) ? $dec : (
- isset($this->flexy->options['plugin.numberformat.decimals']) ?
- $this->flexy->options['plugin.numberformat.decimals'] : 2
- );
- $point = ($point !== false) ? $point : (
- isset($this->flexy->options['plugin.numberformat.point']) ?
- $this->flexy->options['plugin.numberformat.point'] : '.');
- $thousands = ($thousands !== false) ? $thousands : (
- isset($this->flexy->options['plugin.numberformat.thousands']) ?
- $this->flexy->options['plugin.numberformat.thousands'] : ',');
-
-
- return number_format($number,$dec,$point,$thousands);
- }
-
-
-
- /**
- *
- * Output an <image ... /> tag.
- *
- *
- * @author Paul M. Jones <pmjones@ciaweb.net>
- *
- * @package Savant
- *
- * @version $Id: Savant.php,v 1.1.1.1 2008/04/28 15:20:50 jamie Exp $
- *
- * @access public
- *
- * @param string $src The image source as a relative or absolute HREF.
- *
- * @param string $link Providing a link will make the image clickable,
- * leading to the URL indicated by $link; defaults to null.
- *
- * @param string $alt Alternative descriptive text for the image;
- * defaults to the filename of the image.
- *
- * @param int $border The border width for the image; defaults to zero.
- *
- * @param int $width The displayed image width in pixels; defaults to
- * the width of the image.
- *
- * @param int $height The displayed image height in pixels; defaults to
- * the height of the image.
- *
- */
-
- function image(
- $src,
- $alt = null,
- $border = 0,
- $width = null,
- $height = null)
- {
- $size = '';
-
- // build the alt tag
- if (is_null($alt)) {
- $alt = basename($src);
- }
-
- $alt = ' alt="' . htmlentities($alt) . '"';
-
- // build the border tag
- $border = ' border="' . htmlentities($border) . '"';
-
- // get the width and height of the image
- if (is_null($width) && is_null($height)) {
-
- if (substr(strtolower($src), 0, 7) == 'http://' ||
- substr(strtolower($src), 0, 8) == 'https://') {
-
- // the image is not on the local filesystem
- $root = '';
-
- } else {
-
- // we need to set a base root path so we can find images on the
- // local file system
- $root = isset($GLOBALS['HTTP_SERVER_VARS']['DOCUMENT_ROOT'])
- ? $GLOBALS['HTTP_SERVER_VARS']['DOCUMENT_ROOT'] . '/'
- : '';
- }
-
- $info = @getimagesize($root . $src);
-
- $width = (is_null($width)) ? $info[0] : $width;
- $height = (is_null($height)) ? $info[1] : $height;
-
- unset($info);
- }
-
- // build the width tag
- if ($width > 0) {
- $size .= ' width="' . htmlentities($width) . '"';
- }
-
- // build the height tag
- if ($height > 0) {
- $size .= ' height="' . htmlentities($height) . '"';
- }
-
- // done!
- return '<img src="' . $src . '"' .
- $alt .
- $border .
- $size .
- ' />';
- }
-
-
- /**
- *
- * Output a single <input> element.
- *
- * @license http://www.gnu.org/copyleft/lesser.html LGPL
- *
- * @author Paul M. Jones <pmjones@ciaweb.net>
- *
- * @package Savant
- *
- * @version $Id: Savant.php,v 1.1.1.1 2008/04/28 15:20:50 jamie Exp $
- *
- * @access public
- *
- * @param string $type The HTML "type=" value (e.g., 'text',
- * 'hidden', 'password').
- *
- * @param string $name The HTML "name=" value.
- *
- * @param mixed $value The initial value of the input element.
- *
- * @param string $extra Any "extra" HTML code to place within the
- * checkbox element.
- *
- * @return string
- *
- */
-
- function input($type, $name, $value = '', $extra = '')
- {
- $output = "<input type=\"$type\" name=\"$name\" ";
- $output .= "value=\"$value\" $extra />";
- return $output;
- }
-
- /**
- *
- * Output a <script></script> link to a JavaScript file.
- *
- *
- * @license http://www.gnu.org/copyleft/lesser.html LGPL
- *
- * @author Paul M. Jones <pmjones@ciaweb.net>
- *
- * @package Savant
- *
- * @version $Id: Savant.php,v 1.1.1.1 2008/04/28 15:20:50 jamie Exp $
- *
- * @access public
- *
- * @param string $href The HREF leading to the JavaScript source
- * file.
- *
- * @return string
- *
- */
-
- function javascript($href)
- {
- return '<script language="javascript" type="text/javascript" src="' .
- $href . '"></script>';
- }
-
-
- /**
- *
- * Output a value using echo after processing with optional modifier
- * functions.
- *
- * Allows you to pass a space-separated list of value-manipulation
- * functions so that the value is "massaged" before output. For
- * example, if you want to strip slashes, force to lower case, and
- * convert to HTML entities (as for an input text box), you might do
- * this:
- *
- * $this->modify($value, 'stripslashes strtolower htmlentities');
- *
- * @license http://www.gnu.org/copyleft/lesser.html LGPL
- *
- * @author Paul M. Jones <pmjones@ciaweb.net>
- *
- * @package Savant
- *
- * @version $Id: Savant.php,v 1.1.1.1 2008/04/28 15:20:50 jamie Exp $
- *
- * @access public
- *
- * @param string $value The value to be printed.
- *
- * @param string $functions A space-separated list of
- * single-parameter functions to be applied to the $value before
- * printing.
- *
- * @return string
- *
- */
-
- function modify($value, $functions = null)
- {
- // is there a space-delimited function list?
- if (is_string($functions)) {
-
- // yes. split into an array of the
- // functions to be called.
- $list = explode(' ', $functions);
-
- // loop through the function list and
- // apply to the output in sequence.
- foreach ($list as $func) {
- if (!function_exists($func)) {
- continue;
- }
- // extend this..
- if (!in_array($func, array('htmlspecialchars','nl2br','urlencode'))) {
- continue;
- }
- $value = $func($value);
-
- }
- }
-
- return $value;
- }
-
-
-
- /**
- *
- * Output a series of HTML <option>s based on an associative array
- * where the key is the option value and the value is the option
- * label. You can pass a "selected" value as well to tell the
- * function which option value(s) should be marked as seleted.
- *
- *
- * @author Paul M. Jones <pmjones@ciaweb.net>
- *
- * @package Savant
- *
- * @version $Id: Savant.php,v 1.1.1.1 2008/04/28 15:20:50 jamie Exp $
- *
- * @access public
- *
- * @param array $options An associative array of key-value pairs; the
- * key is the option value, the value is the option lable.
- *
- * @param mixed $selected A string or array that matches one or more
- * option values, to tell the function what options should be marked
- * as selected. Defaults to an empty array.
- *
- * @return string
- *
- */
- function options( $options, $selected = array(), $extra = null)
- {
- $html = '';
-
- // force $selected to be an array. this allows multi-selects to
- // have multiple selected options.
- settype($selected, 'array');
-
- // is $options an array?
- if (is_array($options)) {
-
- // loop through the options array
- foreach ($options as $value => $label) {
-
- $html .= '<option value="' . $value . '"';
- $html .= ' label="' . $label . '"';
-
- if (in_array($value, $selected)) {
- $html .= ' selected="selected"';
- }
-
- if (! is_null($extra)) {
- $html .= ' ' . $extra;
- }
-
- $html .= ">$label</option>\n";
- }
- }
-
- return $html;
- }
-
-
- /**
- *
- * Output a set of radio <input>s with the same name.
- *
- *
- * @author Paul M. Jones <pmjones@ciaweb.net>
- *
- * @package Savant
- *
- * @version $Id: Savant.php,v 1.1.1.1 2008/04/28 15:20:50 jamie Exp $
- *
- * @access public
- *
- * @param string $name The HTML "name=" value of all the radio <input>s.
- *
- * @param array $options An array of key-value pairs where the key is the
- * radio button value and the value is the radio button label.
- *
- * $options = array (
- * 0 => 'zero',
- * 1 => 'one',
- * 2 => 'two'
- * );
- *
- * @param string $checked A comparison string; if any of the $option
- * element values and $checked are the same, that radio button will
- * be marked as "checked" (otherwise not).
- *
- * @param string $extra Any "extra" HTML code to place within the
- * <input /> element.
- *
- * @param string $sep The HTML text to place between every radio
- * button in the set.
- *
- * @return string
- *
- */
-
-
- function radios(
- $name,
- $options,
- $checked = null,
- $set_unchecked = null,
- $sep = "<br />\n",
- $extra = null)
- {
- $html = '';
-
- if (is_array($options)) {
-
- if (! is_null($set_unchecked)) {
- // this sets the unchecked value of the
- // radio button set.
- $html .= "<input type=\"hidden\" ";
- $html .= "name=\"$name\" ";
- $html .= "value=\"$set_unchecked\" />\n";
- }
-
- foreach ($options as $value => $label) {
- $html .= "<input type=\"radio\" ";
- $html .= "name=\"$name\" ";
- $html .= "value=\"$value\"";
-
- if ($value == $checked) {
- $html .= " checked=\"checked\"";
- }
- $html .= " $extra />$label$sep";
- }
- }
-
- return $html;
- }
-
- /**
- *
- * Output a <link ... /> to a CSS stylesheet.
- *
- *
- * @author Paul M. Jones <pmjones@ciaweb.net>
- *
- * @package Savant
- *
- * @version $Id: Savant.php,v 1.1.1.1 2008/04/28 15:20:50 jamie Exp $
- *
- * @access public
- *
- * @param string $href The HREF leading to the stylesheet file.
- *
- * @return string
- *
- */
-
- function stylesheet($href)
- {
- return '<link rel="stylesheet" type="text/css" href="' .
- $href . '" />';
- }
-
-
-
-
- /**
- *
- * Output a single <textarea> element.
- *
- * @license http://www.gnu.org/copyleft/lesser.html LGPL
- *
- * @author Paul M. Jones <pmjones@ciaweb.net>
- *
- * @package Savant
- *
- * @version $Id: Savant.php,v 1.1.1.1 2008/04/28 15:20:50 jamie Exp $
- *
- * @access public
- *
- * @param string $name The HTML "name=" value.
- *
- * @param string $text The initial value of the textarea element.
- *
- * @param int $tall How many rows tall should the area be?
- *
- * @param mixed $wide The many columns wide should the area be?
- *
- * @param string $extra Any "extra" HTML code to place within the
- * checkbox element.
- *
- * @return string
- *
- */
-
- function textarea($name, $text, $tall = 24, $wide = 80, $extra = '')
- {
- $output = "<textarea name=\"$name\" rows=\"$tall\" ";
- $output .= "cols=\"$wide\" $extra>$text</textarea>";
- return $output;
- }
-}
-
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Alan Knowles <alan@akbkhome.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: SmartyAPI.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-//
-// Description this class emulates the Smarty API to attempt to enable
-// upgrading to flexy. (eg. for use with flexy templates (that have been
-// converted using the SmartyConverter Compiler.
-//
-// I've no idea how complete this will end up being..
-//
-// Technically Smarty is LGPL - so theortically no code in here should
-// use the copy & paste the original smarty code....
-//
-
-// to use as a full emulator :
-// try
-// class Smarty extends HTML_Template_Flexy_SmartyAPI {
-// function Smarty() { parent::construct(); }
-// }
-
-
-// not implemented:
-/*
-append_by_ref
-append
-register_function / unregister_function
-register_object / register_object
-register_block / unregister_block
-register_compiler_function / unregister_compiler_function
-register_modifier / unregister_modifier
-register_resource / unregister_resource
-register_prefilter / unregister_prefilter
-register_postfilter / unregister_postfilter
-register_outputfilter / unregister_outputfilter
-load_filter
-clear_cache
-clear_all_cache
-is_cached
-template_exists
-get_template_vars
-get_config_vars
-trigger_error
-
-fetch
-get_registered_object
-config_load
-clear_config
-_* (all the privates)
-*/
-
-/**
-* Smarty API emulator for Flexy
-* - designed to make transitions simpler
-* - provides only basic support for variables
-* - uses flexy templates (that have been converted previosly with the converor)
-*
-* @version $Id: SmartyAPI.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-*/
-
-class HTML_Template_Flexy_SmartyAPI {
-
- /**
- * where the data for the template gets stored.
- *
- * @var array
- * @access public
- */
- var $vars = array();
-
- /**
- * Standard Variable assignment
- *
- * @param string|array element name to assign value or assoc. array
- * @param mixed value of element.
- *
- * @return none
- * @access public
- */
- function assign($k,$v)
- {
- if (is_array($k)) {
- $this->vars = $k + $this->vars;
- return;
- }
- $this->vars[$k] = $v;
- }
- /**
- * Standard Variable assignment (by reference)
- *
- * @param string element name to assign value
- * @param mixed value of element.
- *
- * @return none
- * @access public
- */
- function assign_by_ref($k, &$v)
- {
- $this->vars[$k] = &$v;
- }
- /**
- * Unset a variable assignment
- *
- * @param string element name to remove
- *
- * @return none
- * @access public
- */
- function clear_assign($k)
- {
- if (is_array($k)) {
- foreach ($k as $kk) {
- $this->clear_assign($kk);
- }
- return;
- }
-
- if (isset($this->vars[$k])) {
- unset($this->vars[$k]);
- }
- }
- /**
- * Unset all variables
- *
- * @return none
- * @access public
- */
- function clear_all_assign()
- {
- $this->vars = array();
-
- }
-
- /**
- * output a template (optionally with flexy object & element.)
- *
- * @param string name of flexy template.
- * @param object object as per HTML_Template_Flexy:outputObject
- * @param array elements array as per HTML_Template_Flexy:outputObject
- *
- * @return none
- * @access public
- */
- function display($templatename,$object=null,$elements=array())
- {
- // some standard stuff available to a smarty template..
- $this->vars['SCRIPT_NAME'] = $_SERVER['SCRIPT_NAME'];
-
-
- $o = PEAR::getStaticProperty('HTML_Template_Flexy','options');
-
- require_once 'HTML/Template/Flexy.php';
- $t = new HTML_Template_Flexy;
- $t->compile($templatename);
- $object = ($object !== null) ? $object : new StdClass;
-
- foreach($this->vars as $k=>$v) {
- $object->$k = $v;
- }
- $t->outputObject($object,$elements);
- }
-
-}
-
+++ /dev/null
-#!/usr/bin/php
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: nobody <nobody@localhost> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Test.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-//
-// This is a temporary file - it includes some of the
-// Code that will have to go in the Engine eventually..
-// Used to test parsing and generation.
-//
-
-//ini_set('include_path', ini_get('include_path').realpath(dirname(__FILE__) . '/../../..'));
-require_once 'Gtk/VarDump.php';
-require_once 'Console/Getopt.php';
-require_once 'HTML/Template/Flexy.php';
-require_once 'HTML/Template/Flexy/Compiler.php';
-
-// this is the main runable...
-
-class HTML_Template_Flexy_Test {
-
-
- function HTML_Template_Flexy_Test () {
- // for testing!
- $GLOBALS['_HTML_TEMPLATE_FLEXY']['currentOptions'] = array(
- 'compileDir' => dirname(__FILE__),
- 'locale' => 'en',
-
-
- );
-
- $this->parseArgs();
- $this->parse();
-
- }
-
-
-
- function parseArgs() {
- // mapp of keys to values..
-
-
- $args = Console_Getopt::ReadPHPArgV();
- $vals = Console_Getopt::getopt($args,'');
- //print_r($vals);
- $files = $vals[1];
-
- if (!$files) {
- $this->error(0,"No Files supplied");
- }
-
- foreach($files as $file) {
- $realpath = realpath($file);
- if (!$realpath) {
- $this->error(0,"File $path Does not exist");
- }
- $this->files[] = $realpath;
- }
-
-
- }
-
- var $files; // array of files to compile
- var $quickform;
-
- function parse() {
- foreach($this->files as $file) {
- $flexy = new HTML_Template_Flexy(array(
- 'compileToString'=>true,
- 'valid_functions' => 'include'
- ));
- $compiler = HTML_Template_Flexy_Compiler::factory($flexy->options);
- $result = $compiler->compile($flexy,file_get_contents($file));
- echo $result;
- print_r(array_unique($GLOBALS['_HTML_TEMPLATE_FLEXY_TOKEN']['gettextStrings']));
- print_r($flexy->elements);
-
- }
-
-
-
-
-
- }
-
- function error($id,$msg) {
- echo "ERROR $id : $msg\n";
- exit(255);
- }
-
- function debug($id,$msg) {
- echo "Debug Message ($id) : $msg\n";
- }
-
-
-}
-
-
-
-new HTML_Template_Flexy_Test;
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Alan Knowles <alan@akbkhome> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Token.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-//
-// This is the master Token file for The New Token driver Engine.
-// All the Token output, and building routines are in here.
-//
-// Note overriden methods are not documented unless they differ majorly from
-// The parent.
-//
-$GLOBALS['_HTML_TEMPLATE_FLEXY_TOKEN']['base'] = 0;
-$GLOBALS['_HTML_TEMPLATE_FLEXY_TOKEN']['state'] = 0;
-$GLOBALS['_HTML_TEMPLATE_FLEXY_TOKEN']['statevars'] = array();
-$GLOBALS['_HTML_TEMPLATE_FLEXY_TOKEN']['activeForm'] = '';
-$GLOBALS['_HTML_TEMPLATE_FLEXY_TOKEN']['tokens'] = array();
-$GLOBALS['_HTML_TEMPLATE_FLEXY_TOKEN']['gettextStrings'] = array();
-$GLOBALS['_HTML_TEMPLATE_FLEXY_TOKEN']['activeFormId'] = 0;
-$GLOBALS['_HTML_TEMPLATE_FLEXY_TOKEN']['flexyIgnore'] = false;
-/**
-* Base Class for all Tokens.
-*
-* @abstract Provides the static Create Method, and default toString() methods
-*
-*/
-
-class HTML_Template_Flexy_Token {
-
- /**
- * the token type (Depreciated when we have classes for all tokens
- *
- * @var string
- * @access public
- */
- var $token;
- /**
- * the default value (normally a string)
- *
- * @var string
- * @access public
- */
- var $value;
- /**
- * the line the token is from
- *
- * @var int
- * @access public
- */
- var $line;
- /**
- * the character Position
- *
- * @var int
- * @access public
- */
- var $charPos;
-
-
- /**
- * factory a Token
- *
- * Standard factory method.. - with object vars.
- * ?? rename me to factory?
- * @param string Token type
- * @param mixed Initialization settings for token
- * @param int line that the token is defined.
- *
- *
- * @return object Created Object
- * @access public
- */
-
- function factory($token,$value,$line,$charPos=0) {
- // try not to reload the same class to often
- static $loaded = array();
-
-
- $c = 'HTML_Template_Flexy_Token_'.$token;
-
- if (!class_exists($c) && !isset($loaded[$token])) {
- // make sure parse errors are picked up - no @ here..
- if (file_exists(dirname(__FILE__)."/Token/{$token}.php")) {
- require_once 'HTML/Template/Flexy/Token/'.$token.'.php';
- }
- $loaded[$token] = true;
- }
-
- $t = new HTML_Template_Flexy_Token;
-
- if (class_exists($c)) {
- $t = new $c;
- }
- $t->token = $token;
- $t->charPos = $charPos;
-
- if ($t->setValue($value) === false) {
- // kick back error conditions..
- return false;
- }
- $t->line = $line;
-
- return $t;
- }
-
- /**
- * Standard Value iterpretor
- *
- * @param mixed value recieved from factory method
-
- * @return none
- * @access public
- */
-
- function setValue($value) {
- $this->value = $value;
- }
-
-
- /**
- * compile to String (vistor method) replaces toString
- *
- * @return string HTML
- * @access public
- */
-
- function compile(&$compiler) {
- return $compiler->toString($this);
- }
-
-
- /**
- * compile children (visitor approach).
- *
- * @return string HTML
- * @access public
- */
- function compileChildren( &$compiler) {
-
- if (!$this->children) {
- return '';
- }
- if ($this->ignoreChildren) {
- return;
- }
- $ret = '';
- //echo "output $this->id";
- //new Gtk_VarDump($this);
- foreach ($this->children as $child) {
- if (!$child) {
- continue;
- }
- $add = $child->compile($compiler);
- if (is_a($add,'PEAR_Error')) {
- return $add;
- }
- $ret .= $add;
- }
- return $ret;
- }
-
-
-
-
- /* ======================================================= */
- /* Token Managmenet = parse and store all the tokens in
- * an associative array and tree.
- */
-
- /**
- * Run a Tokenizer and Store its results
- * It should build a DOM Tree of the HTML
- *
- * @param object Tokenizer to run.. - Theoretically other Tokenizers could be done for email,rtf etc.
- *
- * @access public
- * @return base token (really a dummy token, which contains the tree)
- * @static
- */
-
- function buildTokens($tokenizer)
- {
-
- global $_HTML_TEMPLATE_FLEXY_TOKEN;
-
- // first record is a filler - to stick all the children on !
- // reset my globals..
- $_HTML_TEMPLATE_FLEXY_TOKEN['base'] = 0;
-
- $_HTML_TEMPLATE_FLEXY_TOKEN['statevars'] = array();
- $_HTML_TEMPLATE_FLEXY_TOKEN['state'] = 0;
-
- $_HTML_TEMPLATE_FLEXY_TOKEN['flexyIgnore'] = false;
- if (@$GLOBALS['_HTML_TEMPLATE_FLEXY']['currentOptions']['flexyIgnore']) {
- $_HTML_TEMPLATE_FLEXY_TOKEN['flexyIgnore'] = true;
- }
- $_HTML_TEMPLATE_FLEXY_TOKEN['activeFormId'] = 0;
- $_HTML_TEMPLATE_FLEXY_TOKEN['activeForm'] = '';
-
- $_HTML_TEMPLATE_FLEXY_TOKEN['tokens'] = array(new HTML_Template_Flexy_Token);
- $_HTML_TEMPLATE_FLEXY_TOKEN['tokens'][0]->id =0;
- $_HTML_TEMPLATE_FLEXY_TOKEN['gettextStrings'] = array();
- $i=1;
-
-
- // initialize state - this trys to make sure that
- // you dont do to many elses etc.
-
- //echo "RUNNING TOKENIZER";
- // step one just tokenize it.
- while ($t = $tokenizer->yylex()) {
-
- if ($t == HTML_TEMPLATE_FLEXY_TOKEN_ERROR) {
- //echo "ERROR";
-
- //print_r($tokenizer);
- $err = "<PRE>" . $tokenizer->error . "\n" .
- htmlspecialchars(substr($tokenizer->yy_buffer,0,$tokenizer->yy_buffer_end)) .
- "<font color='red'>". htmlspecialchars(substr($tokenizer->yy_buffer,$tokenizer->yy_buffer_end,100)) .
- ".......</font></PRE>";
-
- return HTML_Template_Flexy::raiseError('HTML_Template_Flexy::Syntax error in ".
- "Template line:'. $tokenizer->yyline .
- $err
- , HTML_TEMPLATE_FLEXY_ERROR_SYNTAX ,HTML_TEMPLATE_FLEXY_ERROR_RETURN);
- }
- if ($t == HTML_TEMPLATE_FLEXY_TOKEN_NONE) {
- continue;
- }
- if ( $tokenizer->value->token == 'Php' ) {
- if (!$GLOBALS['_HTML_TEMPLATE_FLEXY']['currentOptions']['allowPHP']) {
- return HTML_Template_Flexy::raiseError('PHP code found in script (Token)',
- HTML_TEMPLATE_FLEXY_ERROR_SYNTAX,HTML_TEMPLATE_FLEXY_ERROR_RETURN
- );
- }
-
- if ($GLOBALS['_HTML_TEMPLATE_FLEXY']['currentOptions']['allowPHP'] === 'delete') {
- continue;
- }
-
- }
- $i++;
- $_HTML_TEMPLATE_FLEXY_TOKEN['tokens'][$i] = $tokenizer->value;
- $_HTML_TEMPLATE_FLEXY_TOKEN['tokens'][$i]->id = $i;
-
- // this whole children thing needs rethinking
- // - I think the body of the page should be wrapped: ..
- // ?php if (!$this->bodyOnly) { .. <HTML> .... <BODY....> ?php } ?
- //
- // old values alias to new ones..
- if (isset($_HTML_TEMPLATE_FLEXY_TOKEN['tokens'][$i]->ucAttributes['FLEXYSTART'])) {
- unset($_HTML_TEMPLATE_FLEXY_TOKEN['tokens'][$i]->ucAttributes['FLEXYSTART']);
- $_HTML_TEMPLATE_FLEXY_TOKEN['tokens'][$i]->ucAttributes['FLEXY:START'] = true;
- }
-
- if (isset($_HTML_TEMPLATE_FLEXY_TOKEN['tokens'][$i]->ucAttributes['FLEXYSTARTCHILDREN'])) {
- unset($_HTML_TEMPLATE_FLEXY_TOKEN['tokens'][$i]->ucAttributes['FLEXYSTARTCHILDREN']);
- $_HTML_TEMPLATE_FLEXY_TOKEN['tokens'][$i]->ucAttributes['FLEXY:STARTCHILDREN'] = true;
- }
-
- if (isset($_HTML_TEMPLATE_FLEXY_TOKEN['tokens'][$i]->ucAttributes['FLEXY:START'])) {
- $_HTML_TEMPLATE_FLEXY_TOKEN['base'] = $i;
- unset($_HTML_TEMPLATE_FLEXY_TOKEN['tokens'][$i]->ucAttributes['FLEXY:START']);
- }
-
- if (isset($_HTML_TEMPLATE_FLEXY_TOKEN['tokens'][$i]->ucAttributes['FLEXY:STARTCHILDREN'])) {
- $_HTML_TEMPLATE_FLEXY_TOKEN['base'] = $i;
- }
-
-
- //print_r($_HTML_TEMPLATE_FLEXY_TOKEN['tokens'][$i]);
-
- }
- //echo "BUILT TOKENS";
-
- $res = &$_HTML_TEMPLATE_FLEXY_TOKEN['tokens'];
-
- // DEBUG DUMPTING : foreach($res as $k) { $k->dump(); }
-
-
- $stack = array();
- $total = $i +1;
-
- // merge strings and entities - blanking out empty text.
-
-
- for($i=1;$i<$total;$i++) {
- if (!isset($res[$i]) || !is_a($res[$i],'HTML_Template_Flexy_Token_Text')) {
- continue;
- }
- $first = $i;
- $i++;
- while ($i<$total && is_a($res[$i],'HTML_Template_Flexy_Token_Text')) {
- if (isset($res[$i])) {
- $res[$first]->value .= $res[$i]->value;
- $res[$i]->value = '';
- }
- $i++;
- }
- }
- // connect open and close tags.
-
- // this is done by having a stack for each of the tag types..
- // then removing it when it finds the closing one
- // eg.
- // <a href=""><img src=""></a>
- // ends up with a stack for <a>'s and a stack for <img>'s
- //
- //
- //
- //echo '<PRE>' . htmlspecialchars(print_R($res,true));//exit;
- //echo '<PRE>';
- for($i=1;$i<$total;$i++) {
-
- if (empty($res[$i]->tag)) {
- continue;
- }
- //echo "Checking TAG $i {$res[$i]->tag}\n";
- if ($res[$i]->tag{0} == '/') { // it's a close tag..
- //echo "GOT END TAG: {$res[$i]->tag}\n";
- $tag = strtoupper(substr($res[$i]->tag,1));
- if (!count($stack)) {
- continue;
- }
- $ssc = count($stack) - 1;
- /* go up the stack trying to find a match */
- for($s = $ssc; $s > -1; $s--) {
- if (!isset($stack[$s])) {
- echo "MISSED STACK? $s<BR><PRE>";print_r($stack);exit;
- }
- if (!isset($_HTML_TEMPLATE_FLEXY_TOKEN['tokens'][$stack[$s]])) {
- echo "STACKED BAD OFFSET : {$stack[$s]}<BR><PRE>";print_r($stack);exit;
- }
- $tok = &$_HTML_TEMPLATE_FLEXY_TOKEN['tokens'][$stack[$s]];
- if (strtoupper($tok->tag) == $tag) {
- // got the matching closer..
- // echo "MATCH: {$i}:{$tok->tag}({$tok->line}) to {$stack[$s]}:$tag<BR>";
- $tok->close = &$_HTML_TEMPLATE_FLEXY_TOKEN['tokens'][$i];
-
- array_splice($stack,$s);
- //print_R($stack);
-
- break;
- }
- }
- continue;
- }
- $stack[] = $i;
- // tag with no closer (or unmatched in stack..)
- }
-
-
- // create a dummy close for the end
- $i = $total;
- $_HTML_TEMPLATE_FLEXY_TOKEN['tokens'][$i] = new HTML_Template_Flexy_Token;
- $_HTML_TEMPLATE_FLEXY_TOKEN['tokens'][$i]->id = $total;
- $_HTML_TEMPLATE_FLEXY_TOKEN['tokens'][0]->close = &$_HTML_TEMPLATE_FLEXY_TOKEN['tokens'][$total];
-
- // now is it possible to connect children...
- // now we need to GLOBALIZE!! -
-
-
- $_HTML_TEMPLATE_FLEXY_TOKEN['tokens'] = $res;
-
- HTML_Template_Flexy_Token::buildChildren(0);
- //new Gtk_VarDump($_HTML_TEMPLATE_FLEXY_TOKEN['tokens'][0]);
- //echo '<PRE>';print_R($_HTML_TEMPLATE_FLEXY_TOKEN['tokens'][$_HTML_TEMPLATE_FLEXY_TOKEN['base']] );
- return $_HTML_TEMPLATE_FLEXY_TOKEN['tokens'][$_HTML_TEMPLATE_FLEXY_TOKEN['base']];
- }
- /**
- * Matching closing tag for a Token
- *
- * @var object|none optional closing tag
- * @access public
- */
-
-
- var $close;
-
- /**
- * array of children to each object.
- *
- * @var array
- * @access public|private
- */
-
-
- var $children = array();
-
- /**
- * Build the child array for each element.
- * RECURSIVE FUNCTION!!!!
- * @param int id of node to add children to.
- *
- * @access public
- * @static
- */
- function buildChildren($id)
- {
- global $_HTML_TEMPLATE_FLEXY_TOKEN;
-
- $base = &$_HTML_TEMPLATE_FLEXY_TOKEN['tokens'][$id];
- $base->children = array();
- $start = $base->id +1;
- $end = $base->close->id;
-
- for ($i=$start; $i<$end; $i++) {
- //echo "{$base->id}:{$base->tag} ADDING {$i}{$_HTML_TEMPLATE_FLEXY_TOKEN['tokens'][$i]->tag}<BR>";
- //if ($base->id == 1176) {
- // echo "<PRE>";print_r($_HTML_TEMPLATE_FLEXY_TOKEN['tokens'][$i]);
- // }
-
- $base->children[] = &$_HTML_TEMPLATE_FLEXY_TOKEN['tokens'][$i];
-
- if (isset($_HTML_TEMPLATE_FLEXY_TOKEN['tokens'][$i]) &&
- is_object($_HTML_TEMPLATE_FLEXY_TOKEN['tokens'][$i]->close)) {
-
- // if the close id is greater than my id - ignore it! -
- if ($_HTML_TEMPLATE_FLEXY_TOKEN['tokens'][$i]->close->id > $end) {
- continue;
- }
- HTML_Template_Flexy_Token::buildChildren($i);
- $i = $_HTML_TEMPLATE_FLEXY_TOKEN['tokens'][$i]->close->id;
- }
- }
- }
-
-
-
- /**
- * Flag to ignore children - Used to block output for select/text area etc.
- * may not be required as I moved the Tag parsing into the toString ph
- *
- * @var boolean ingore children
- * @access public
- */
-
-
- var $ignoreChildren = false;
-
-
-
-
- /* ======================================================== */
- /* variable STATE management
- *
- * raw variables are assumed to be $this->, unless defined by foreach..
- * it also monitors syntax - eg. end without an if/foreach etc.
- */
-
-
- /**
- * tell the generator you are entering a block
- *
- * @access public
- */
- function pushState()
- {
- global $_HTML_TEMPLATE_FLEXY_TOKEN;
-
- $_HTML_TEMPLATE_FLEXY_TOKEN['state']++;
- $s = $_HTML_TEMPLATE_FLEXY_TOKEN['state'];
-
- $_HTML_TEMPLATE_FLEXY_TOKEN['statevars'][$s] = array(); // initialize statevars
- }
- /**
- * tell the generator you are entering a block
- *
- * @return boolean parse error - out of bounds
- * @access public
- */
- function pullState()
- {
- global $_HTML_TEMPLATE_FLEXY_TOKEN;
-
- $s = $_HTML_TEMPLATE_FLEXY_TOKEN['state'];
- $_HTML_TEMPLATE_FLEXY_TOKEN['statevars'][$s] = array(); // initialize statevars
- $_HTML_TEMPLATE_FLEXY_TOKEN['state']--;
- if ($s<0) {
- return false;
- }
- return true;
- }
- /**
- * get the real variable name formated x.y.z => $this->x->y->z
- * if a variable is in the stack it return $x->y->z
- *
- * @return string PHP variable
- * @access public
- */
-
- function toVar($s) {
- // wrap [] with quotes.
- $s = str_replace('[',"['",$s);
- $s = str_replace('%5b',"['",$s);
- $s = str_replace('%5B',"['",$s);
- $s = str_replace(']',"']",$s);
- $s = str_replace('%5d',"']",$s);
- $s = str_replace('%5D',"']",$s);
- // strip the quotes if it's only numbers..
- $s = preg_replace("/'([-]?[0-9]+)'/", "\\1",$s);
-
- $parts = explode(".",$s);
-
-
- $ret = $this->findVar($parts[0]);
- if (is_a($ret,'PEAR_Error')) {
- return $ret;
- }
-
- array_shift($parts);
-
- if (!count($parts)) {
- return $ret;
- }
- foreach($parts as $p) {
- $ret .= "->{$p}";
- }
- return $ret;
- }
- /**
- * do the stack lookup on the variable
- * this relates to flexy
- * t relates to the object being parsed.
- *
- * @return string PHP variable
- * @access public
- */
-
- function findVar($string)
- {
- global $_HTML_TEMPLATE_FLEXY_TOKEN;
-
- if (!$string || $string == 't') {
- return '$t';
- }
- if ($string == 'this') {
- return '$this';
- }
- // accept global access on some string
- if (@$GLOBALS['_HTML_TEMPLATE_FLEXY']['currentOptions']['globals'] &&
- preg_match('/^(_POST|_GET|_REQUEST|_SESSION|_COOKIE|GLOBALS)\[/',$string)) {
- return '$'.$string;
- }
- if (!@$GLOBALS['_HTML_TEMPLATE_FLEXY']['currentOptions']['privates'] &&
- ($string{0} == '_')) {
- return HTML_Template_Flexy::raiseError('HTML_Template_Flexy::Attempt to access private variable:'.
- " on line {$this->line} of {$GLOBALS['_HTML_TEMPLATE_FLEXY']['filename']}".
- ", Use options[privates] to allow this."
- , HTML_TEMPLATE_FLEXY_ERROR_SYNTAX ,HTML_TEMPLATE_FLEXY_ERROR_RETURN);
- }
-
- $lookup = $string;
- if ($p = strpos($string,'[')) {
- $lookup = substr($string,0,$p);
- }
-
-
- for ($s = $_HTML_TEMPLATE_FLEXY_TOKEN['state']; $s > 0; $s--) {
- if (in_array($lookup , $_HTML_TEMPLATE_FLEXY_TOKEN['statevars'][$s])) {
- return '$'.$string;
- }
- }
- return '$t->'.$string;
- }
- /**
- * add a variable to the stack.
- *
- * @param string PHP variable
- * @access public
- */
-
- function pushVar($string)
- {
- global $_HTML_TEMPLATE_FLEXY_TOKEN;
- $s = $_HTML_TEMPLATE_FLEXY_TOKEN['state'];
- $_HTML_TEMPLATE_FLEXY_TOKEN['statevars'][$s][] = $string;
- }
-
- /**
- * dump to text ATM
- *
- *
- * @access public
- */
-
- function dump() {
- echo "{$this->token}/" . (isset($this->tag) ? "<{$this->tag}>" : '') . ": {$this->value}\n";
- }
-
-
-
-
-}
-
-
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Alan Knowles <alan@akbkhome> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Else.php,v 1.1.1.1 2008/04/28 15:20:50 jamie Exp $
-//
-
-/**
-* Class to handle Else
-*
-*
-*/
-class HTML_Template_Flexy_Token_Else extends HTML_Template_Flexy_Token {
-
-
-
-}
-
-
-
-
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Alan Knowles <alan@akbkhome> |
-// +----------------------------------------------------------------------+
-//
-// $Id: End.php,v 1.1.1.1 2008/04/28 15:20:50 jamie Exp $
-//
-
-/**
-* Class to handle End statements (eg. close brakets)
-*
-*
-*/
-class HTML_Template_Flexy_Token_End extends HTML_Template_Flexy_Token {
-
-
-}
-
-
-
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Alan Knowles <alan@akbkhome> |
-// +----------------------------------------------------------------------+
-//
-// $Id: EndTag.php,v 1.1.1.1 2008/04/28 15:20:50 jamie Exp $
-//
-
-/**
-* The closing HTML Tag = eg. /Table or /Body etc.
-*
-* @abstract
-* This just extends the generic HTML tag
-*
-*/
-
-require_once 'HTML/Template/Flexy/Token/Tag.php';
-
-
-class HTML_Template_Flexy_Token_EndTag extends HTML_Template_Flexy_Token_Tag { }
-
-
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Alan Knowles <alan@akbkhome> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Foreach.php,v 1.1.1.1 2008/04/28 15:20:50 jamie Exp $
-//
-
-/**
-* Class to handle foreach statements
-*
-*
-*/
-class HTML_Template_Flexy_Token_Foreach extends HTML_Template_Flexy_Token {
-
- /**
- * variable to loop on.
- *
- * @var string
- * @access public
- */
- var $loopOn = '';
- /**
- * key value
- *
- * @var string
- * @access public
- */
- var $key = '';
- /**
- * optional value (in key=>value pair)
- *
- * @var string
- * @access public
- */
- var $value = '';
-
- /**
- * Setvalue - a array of all three (last one optional)
- * @see parent::setValue()
- */
-
- function setValue($value) {
- $this->loopOn=$value[0];
- if (!isset($value[1]) || !strlen(trim($value[1]))) {
- // error condition.
- return false;
- }
- $this->key=$value[1];
- $this->value=@$value[2];
- }
-
-
-}
-
-
-
-
-
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Alan Knowles <alan@akbkhome> |
-// +----------------------------------------------------------------------+
-//
-// $Id: If.php,v 1.1.1.1 2008/04/28 15:20:50 jamie Exp $
-//
-
-/**
-* Class to handle If statements
-*
-*
-*/
-class HTML_Template_Flexy_Token_If extends HTML_Template_Flexy_Token{
- /**
- * Condition for the if statement.
- * @var string // a variable
- * @access public
- */
-
- var $condition;
- /**
- * if the statement is negative = eg. !somevar..
- * @var string
- * @access public
- */
-
-
- var $isNegative = '';
-
- /**
- * Setvalue - a string
- * @see parent::setValue()
- */
- function setValue($value) {
- //var_dump($value);
- if (strlen($value) && $value{0} == '!') {
- $this->isNegative = '!';
- $value = substr($value,1);
- }
- $this->condition=$value;
- }
-
-
-}
-
-
-
-
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Alan Knowles <alan@akbkhome> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Method.php,v 1.1.1.1 2008/04/28 15:20:50 jamie Exp $
-//
- /**
-* Class to handle method calls
-* *
-*
-*/
-
-class HTML_Template_Flexy_Token_Method extends HTML_Template_Flexy_Token {
- /**
- * variable modifier (h = raw, u = urlencode, none = htmlspecialchars)
- * TODO
- * @var char
- * @access public
- */
- var $modifier;
- /**
- * Method name
- *
- * @var char
- * @access public
- */
- var $method;
- /**
- * is it in if statement with a method?
- *
- * @var boolean
- * @access public
- */
- var $isConditional;
- /**
- * if the statement is negative = eg. !somevar..
- * @var string
- * @access public
- */
- var $isNegative = '';
-
- /**
- * arguments, either variables or literals eg. #xxxxx yyyy#
- *
- * @var array
- * @access public
- */
- var $args= array();
- /**
- * setvalue - at present array method, args (need to add modifier)
- * @see parent::setValue()
- */
-
- function setValue($value) {
- // var_dump($value);
- $method = $value[0];
- if (substr($value[0],0,3) == 'if:') {
- $this->isConditional = true;
- if ($value[0]{3} == '!') {
- $this->isNegative = '!';
- $method = substr($value[0],4);
- } else {
- $method = substr($value[0],3);
- }
- }
-
- if (strpos($method,":")) {
- list($method,$this->modifier) = explode(':',$method);
- }
- $this->method = $method;
-
- $this->args = $value[1];
- // modifier TODO!
-
- }
-
-}
-
-
-
-
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Alan Knowles <alan@akbkhome> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Processing.php,v 1.1.1.1 2008/04/28 15:20:50 jamie Exp $
-//
-
-/**
-* Class to handle Processing Directives = <?xml or <?php
-*
-*
-*/
-class HTML_Template_Flexy_Token_Processing extends HTML_Template_Flexy_Token {
-
-
-}
-
-
-
-
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Alan Knowles <alan@akbkhome> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Tag.php,v 1.1.1.1 2008/04/28 15:20:50 jamie Exp $
-
-
-$GLOBALS['_HTML_TEMPLATE_FLEXY_TOKEN_TAG']['activeSelect'] = false;
-require_once 'HTML/Template/Flexy/Element.php';
-/**
-* A standard HTML Tag = eg. Table/Body etc.
-*
-* @abstract
-* This is the generic HTML tag
-* a simple one will have some attributes and a name.
-*
-*/
-
-class HTML_Template_Flexy_Token_Tag extends HTML_Template_Flexy_Token {
-
- /**
- * HTML Tag: eg. Body or /Body - uppercase
- *
- * @var string
- * @access public
- */
- var $tag = '';
- /**
- * HTML Tag: (original case)
- *
- * @var string
- * @access public
- */
- var $oTag = '';
- /**
- * Associative array of attributes. (original case)
- *
- * key is the left, value is the right..
- * note:
- * values are raw (eg. include "")
- * valuse can be
- * text = standard
- * array (a parsed value with flexy tags in)
- * object (normally some PHP code that generates the key as well..)
- *
- *
- * @var array
- * @access public
- */
-
- var $attributes = array();
-
- /**
- * Associative array of attributes ucase to Original Case for attributes..
- *
- * @var array
- * @access public
- */
-
- var $ucAttributes = array();
-
-
-
- /**
- * postfix tokens
- * used to add code to end of tags "<xxxx>here....children .. <close tag>"
- *
- * @var array
- * @access public
- */
- var $postfix = '';
- /**
- * prefix tokens
- * used to add code to beginning of tags TODO "here<xxxx>....children .. <close tag>"
- *
- * @var array
- * @access public
- */
- var $prefix = '';
-
-
- /**
- * Alias to closing tag (built externally).
- * used to add < ? } ? > code to dynamic tags.
- * @var object alias
- * @access public
- */
- var $close; // alias to closing tag.
-
-
-
- /**
- * Setvalue - gets name, attribute as an array
- * @see parent::setValue()
- */
-
- function setValue($value)
- {
- global $_HTML_TEMPLATE_FLEXY_TOKEN;
- $this->tag = strtoupper($value[0]);
- $this->oTag = $value[0];
- if (isset($value[1])) {
- $this->attributes = $value[1];
- }
-
- foreach(array_keys($this->attributes) as $k) {
- $this->ucAttributes[strtoupper($k)] =& $this->attributes[$k];
- }
-
- }
-
-
-
- /**
- * getAttribute = reads an attribute value and strips the quotes
- *
- * TODO
- * does not handle values with flexytags in them
- *
- * @return string (
- * @access public
- */
- function getAttribute($key) {
- // all attribute keys are stored Upper Case,
- // however just to make sure we have not done a typo :)
- $key = strtoupper($key);
- //echo "looking for $key\n";
- //var_dump($this->attributes);
-
- // this is weird case isset() returns false on this being null!
-
- if (@$this->ucAttributes[$key] === true) {
- return true;
- }
-
- if (!isset($this->ucAttributes[$key])) {
- return false;
- }
- // general assumption - none of the tools can do much with dynamic
- // attributes - eg. stuff with flexy tags in it.
- if (!is_string($this->ucAttributes[$key])) {
- return false;
- }
- $v = $this->ucAttributes[$key];
-
- // unlikely :)
- if ($v=='') {
- return $v;
- }
-
- switch($v{0}) {
- case "\"":
- case "'":
- return substr($v,1,-1);
- default:
- return $v;
- }
- }
-
- /**
- * getAttributes = returns all the attributes key/value without quotes
- *
- *
- * @return array
- * @access string
- */
-
- function getAttributes() {
- $ret = array();
- foreach($this->attributes as $k=>$v) {
- if (substr(strtoupper($k),0,6) == 'FLEXY:') {
- continue;
- }
- $ret[$k] = $this->getAttribute($k);
- }
- return $ret;
- }
-
- /**
- * clearAttributes = removes an attribute from the object.
- *
- *
- * @return array
- * @access string
- */
- function clearAttribute($string) {
- if (isset($this->attributes[$string])) {
- unset($this->attributes[$string]);
- }
- }
-
-
-
-}
-
-
-
-
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Alan Knowles <alan@akbkhome> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Text.php,v 1.1.1.1 2008/04/28 15:20:50 jamie Exp $
-//
-
-
-/**
-* Class that represents a text string node.
-*
-*
-*/
-
-class HTML_Template_Flexy_Token_Text extends HTML_Template_Flexy_Token {
-
-
- /**
- * Simple check to see if this piece of text is a word
- * so that gettext and the merging tricks dont try
- * - merge white space with a flexy tag
- * - gettext doesnt translate etc.
- *
- * @return boolean true if this is a word
- * @access public
- */
- function isWord() {
- if (!strlen(trim($this->value))) {
- return false;
- }
- if (preg_match('/^\&[a-z0-9]+;$/i',trim($this->value))) {
- return false;
- }
- return preg_match('/\w/i',$this->value);
- }
-
-}
-
-
-
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Alan Knowles <alan@akbkhome> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Var.php,v 1.1.1.1 2008/04/28 15:20:50 jamie Exp $
-//
-
-/**
-* Class to handle variable output
-* *
-*
-*/
-
-class HTML_Template_Flexy_Token_Var extends HTML_Template_Flexy_Token {
-
- /**
- * variable modifier (h = raw, u = urlencode, none = htmlspecialchars)
- *
- * @var char
- * @access public
- */
- var $modifier;
- /**
- * Setvalue - at present raw text.. - needs sorting out..
- * @see parent::setValue()
- */
- function setValue($value) {
- // comes in as raw {xxxx}, {xxxx:h} or {xxx.yyyy:h}
-
- if (strpos($value,":")) {
- list($value,$this->modifier) = explode(':',$value);
- }
- $this->value = $value;
- }
-
-
-}
-
-
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Alan Knowles <alan@akbkhome.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Tokenizer.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-//
-// The Source Lex file. (Tokenizer.lex) and the Generated one (Tokenizer.php)
-// You should always work with the .lex file and generate by
-//
-// #mono phpLex/phpLex.exe Tokenizer.lex
-// The lexer is available at http://sourceforge.net/projects/php-sharp/
-//
-// or the equivialant .NET runtime on windows...
-//
-// Note need to change a few of these defines, and work out
-// how to modifiy the lexer to handle the changes..
-//
-define('HTML_TEMPLATE_FLEXY_TOKEN_NONE',1);
-define('HTML_TEMPLATE_FLEXY_TOKEN_OK',2);
-define('HTML_TEMPLATE_FLEXY_TOKEN_ERROR',3);
-define("YYINITIAL" ,0);
-define("IN_SINGLEQUOTE" , 1) ;
-define("IN_TAG" , 2) ;
-define("IN_ATTR" , 3);
-define("IN_ATTRVAL" , 4) ;
-define("IN_NETDATA" , 5);
-define("IN_ENDTAG" , 6);
-define("IN_DOUBLEQUOTE" , 7);
-define("IN_MD" , 8);
-define("IN_COM" , 9);
-define("IN_DS", 10);
-define("IN_FLEXYMETHOD" , 11);
-define("IN_FLEXYMETHODQUOTED" ,12);
-define("IN_FLEXYMETHODQUOTED_END" ,13);
-define("IN_SCRIPT", 14);
-define("IN_CDATA" , 15);
-define("IN_DSCOM", 16);
-define("IN_PHP", 17);
-define("IN_COMSTYLE" , 18);
-define('YY_E_INTERNAL', 0);
-define('YY_E_MATCH', 1);
-define('YY_BUFFER_SIZE', 4096);
-define('YY_F' , -1);
-define('YY_NO_STATE', -1);
-define('YY_NOT_ACCEPT' , 0);
-define('YY_START' , 1);
-define('YY_END' , 2);
-define('YY_NO_ANCHOR' , 4);
-define('YY_BOL' , 257);
-define('YY_EOF' , 258);
-
-
-class HTML_Template_Flexy_Tokenizer
-{
-
- /**
- * options array : meanings:
- * ignore_html - return all tags as text tokens
- *
- *
- * @var boolean public
- * @access public
- */
- var $options = array(
- 'ignore_html' => false,
- 'token_factory' => array('HTML_Template_Flexy_Token','factory'),
- );
- /**
- * flag if inside a style tag. (so comments are ignored.. )
- *
- * @var boolean
- * @access private
- */
- var $inStyle = false;
- /**
- * the start position of a cdata block
- *
- * @var int
- * @access private
- */
- var $yyCdataBegin = 0;
- /**
- * the start position of a comment block
- *
- * @var int
- * @access private
- */
- var $yyCommentBegin = 0;
- /**
- * the name of the file being parsed (used by error messages)
- *
- * @var string
- * @access public
- */
- var $fileName;
- /**
- * the string containing an error if it occurs..
- *
- * @var string
- * @access public
- */
- var $error;
- /**
- * Flexible constructor
- *
- * @param string string to tokenize
- * @param array options array (see options above)
- *
- *
- * @return HTML_Template_Flexy_Tokenizer
- * @access public
- */
- function &construct($data,$options= array())
- {
- $t = new HTML_Template_Flexy_Tokenizer($data);
- foreach($options as $k=>$v) {
- if (is_object($v) || is_array($v)) {
- $t->options[$k] = &$v;
- continue;
- }
- $t->options[$k] = $v;
- }
- return $t;
- }
- /**
- * raise an error: = return an error token and set the error variable.
- *
- *
- * @param string Error type
- * @param string Full Error message
- * @param boolean is it fatal..
- *
- * @return int the error token.
- * @access public
- */
- function raiseError($s,$n='',$isFatal=false)
- {
- $this->error = "ERROR $n in File {$this->fileName} on Line {$this->yyline} Position:{$this->yy_buffer_end}: $s\n";
- return HTML_TEMPLATE_FLEXY_TOKEN_ERROR;
- }
- /**
- * return text
- *
- * Used mostly by the ignore HTML code. - really a macro :)
- *
- * @return int token ok.
- * @access public
- */
- function returnSimple()
- {
- $this->value = $this->createToken('TextSimple');
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
- }
- /**
- * Create a token based on the value of $this->options['token_call']
- *
- *
- * @return Object some kind of token..
- * @access public
- */
- function createToken($token, $value = false, $line = false, $charPos = false)
- {
- if ($value === false) {
- $value = $this->yytext();
- }
- if ($line === false) {
- $line = $this->yyline;
- }
- if ($charPos === false) {
- $charPos = $this->yy_buffer_start;
- }
- return call_user_func_array($this->options['token_factory'],array($token,$value,$line,$charPos));
- }
-
-
- var $yy_reader;
- var $yy_buffer_index;
- var $yy_buffer_read;
- var $yy_buffer_start;
- var $yy_buffer_end;
- var $yy_buffer;
- var $yychar;
- var $yyline;
- var $yyEndOfLine;
- var $yy_at_bol;
- var $yy_lexical_state;
-
- function HTML_Template_Flexy_Tokenizer($data)
- {
- $this->yy_buffer = $data;
- $this->yy_buffer_read = strlen($data);
- $this->yy_buffer_index = 0;
- $this->yy_buffer_start = 0;
- $this->yy_buffer_end = 0;
- $this->yychar = 0;
- $this->yyline = 0;
- $this->yy_at_bol = true;
- $this->yy_lexical_state = YYINITIAL;
- }
-
- var $yy_state_dtrans = array (
- 0,
- 227,
- 35,
- 134,
- 251,
- 252,
- 253,
- 254,
- 54,
- 65,
- 262,
- 264,
- 286,
- 300,
- 301,
- 309,
- 83,
- 85,
- 87
- );
-
-
- function yybegin ($state)
- {
- $this->yy_lexical_state = $state;
- }
-
-
-
- function yy_advance ()
- {
- if ($this->yy_buffer_index < $this->yy_buffer_read) {
- return ord($this->yy_buffer{$this->yy_buffer_index++});
- }
- return YY_EOF;
- }
-
-
- function yy_move_end ()
- {
- if ($this->yy_buffer_end > $this->yy_buffer_start &&
- '\n' == $this->yy_buffer{$this->yy_buffer_end-1})
- {
- $this->yy_buffer_end--;
- }
- if ($this->yy_buffer_end > $this->yy_buffer_start &&
- '\r' == $this->yy_buffer{$this->yy_buffer_end-1})
- {
- $this->yy_buffer_end--;
- }
- }
-
-
- var $yy_last_was_cr=false;
-
-
- function yy_mark_start ()
- {
- for ($i = $this->yy_buffer_start; $i < $this->yy_buffer_index; $i++) {
- if ($this->yy_buffer{$i} == "\n" && !$this->yy_last_was_cr) {
- $this->yyline++; $this->yyEndOfLine = $this->yychar;
- }
- if ($this->yy_buffer{$i} == "\r") {
- $this->yyline++; $this->yyEndOfLine = $this->yychar;
- $this->yy_last_was_cr=true;
- } else {
- $this->yy_last_was_cr=false;
- }
- }
- $this->yychar = $this->yychar + $this->yy_buffer_index - $this->yy_buffer_start;
- $this->yy_buffer_start = $this->yy_buffer_index;
- }
-
-
- function yy_mark_end ()
- {
- $this->yy_buffer_end = $this->yy_buffer_index;
- }
-
-
- function yy_to_mark ()
- {
- $this->yy_buffer_index = $this->yy_buffer_end;
- $this->yy_at_bol = ($this->yy_buffer_end > $this->yy_buffer_start) &&
- ($this->yy_buffer{$this->yy_buffer_end-1} == '\r' ||
- $this->yy_buffer{$this->yy_buffer_end-1} == '\n');
- }
-
-
- function yytext()
- {
- return substr($this->yy_buffer,$this->yy_buffer_start,$this->yy_buffer_end - $this->yy_buffer_start);
- }
-
-
- function yylength ()
- {
- return $this->yy_buffer_end - $this->yy_buffer_start;
- }
-
-
- var $yy_error_string = array(
- "Error: Internal error.\n",
- "Error: Unmatched input.\n"
- );
-
-
- function yy_error ($code,$fatal)
- {
- if (method_exists($this,'raiseError')) {
- return $this->raiseError($code, $this->yy_error_string[$code], $fatal);
- }
- echo $this->yy_error_string[$code];
- if ($fatal) {
- exit;
- }
- }
-
-
- var $yy_acpt = array (
- /* 0 */ YY_NOT_ACCEPT,
- /* 1 */ YY_NO_ANCHOR,
- /* 2 */ YY_NO_ANCHOR,
- /* 3 */ YY_NO_ANCHOR,
- /* 4 */ YY_NO_ANCHOR,
- /* 5 */ YY_NO_ANCHOR,
- /* 6 */ YY_NO_ANCHOR,
- /* 7 */ YY_NO_ANCHOR,
- /* 8 */ YY_NO_ANCHOR,
- /* 9 */ YY_NO_ANCHOR,
- /* 10 */ YY_NO_ANCHOR,
- /* 11 */ YY_NO_ANCHOR,
- /* 12 */ YY_NO_ANCHOR,
- /* 13 */ YY_NO_ANCHOR,
- /* 14 */ YY_NO_ANCHOR,
- /* 15 */ YY_NO_ANCHOR,
- /* 16 */ YY_NO_ANCHOR,
- /* 17 */ YY_NO_ANCHOR,
- /* 18 */ YY_NO_ANCHOR,
- /* 19 */ YY_NO_ANCHOR,
- /* 20 */ YY_NO_ANCHOR,
- /* 21 */ YY_NO_ANCHOR,
- /* 22 */ YY_NO_ANCHOR,
- /* 23 */ YY_NO_ANCHOR,
- /* 24 */ YY_NO_ANCHOR,
- /* 25 */ YY_NO_ANCHOR,
- /* 26 */ YY_NO_ANCHOR,
- /* 27 */ YY_NO_ANCHOR,
- /* 28 */ YY_NO_ANCHOR,
- /* 29 */ YY_NO_ANCHOR,
- /* 30 */ YY_NO_ANCHOR,
- /* 31 */ YY_NO_ANCHOR,
- /* 32 */ YY_NO_ANCHOR,
- /* 33 */ YY_NO_ANCHOR,
- /* 34 */ YY_NO_ANCHOR,
- /* 35 */ YY_NO_ANCHOR,
- /* 36 */ YY_NO_ANCHOR,
- /* 37 */ YY_NO_ANCHOR,
- /* 38 */ YY_NO_ANCHOR,
- /* 39 */ YY_NO_ANCHOR,
- /* 40 */ YY_NO_ANCHOR,
- /* 41 */ YY_NO_ANCHOR,
- /* 42 */ YY_NO_ANCHOR,
- /* 43 */ YY_NO_ANCHOR,
- /* 44 */ YY_NO_ANCHOR,
- /* 45 */ YY_NO_ANCHOR,
- /* 46 */ YY_NO_ANCHOR,
- /* 47 */ YY_NO_ANCHOR,
- /* 48 */ YY_NO_ANCHOR,
- /* 49 */ YY_NO_ANCHOR,
- /* 50 */ YY_NO_ANCHOR,
- /* 51 */ YY_NO_ANCHOR,
- /* 52 */ YY_NO_ANCHOR,
- /* 53 */ YY_NO_ANCHOR,
- /* 54 */ YY_NO_ANCHOR,
- /* 55 */ YY_NO_ANCHOR,
- /* 56 */ YY_NO_ANCHOR,
- /* 57 */ YY_NO_ANCHOR,
- /* 58 */ YY_NO_ANCHOR,
- /* 59 */ YY_NO_ANCHOR,
- /* 60 */ YY_NO_ANCHOR,
- /* 61 */ YY_NO_ANCHOR,
- /* 62 */ YY_NO_ANCHOR,
- /* 63 */ YY_NO_ANCHOR,
- /* 64 */ YY_NO_ANCHOR,
- /* 65 */ YY_NO_ANCHOR,
- /* 66 */ YY_NO_ANCHOR,
- /* 67 */ YY_NO_ANCHOR,
- /* 68 */ YY_NO_ANCHOR,
- /* 69 */ YY_NO_ANCHOR,
- /* 70 */ YY_NO_ANCHOR,
- /* 71 */ YY_NO_ANCHOR,
- /* 72 */ YY_NO_ANCHOR,
- /* 73 */ YY_NO_ANCHOR,
- /* 74 */ YY_NO_ANCHOR,
- /* 75 */ YY_NO_ANCHOR,
- /* 76 */ YY_NO_ANCHOR,
- /* 77 */ YY_NO_ANCHOR,
- /* 78 */ YY_NO_ANCHOR,
- /* 79 */ YY_NO_ANCHOR,
- /* 80 */ YY_NO_ANCHOR,
- /* 81 */ YY_NO_ANCHOR,
- /* 82 */ YY_NO_ANCHOR,
- /* 83 */ YY_NO_ANCHOR,
- /* 84 */ YY_NO_ANCHOR,
- /* 85 */ YY_NO_ANCHOR,
- /* 86 */ YY_NO_ANCHOR,
- /* 87 */ YY_NO_ANCHOR,
- /* 88 */ YY_NO_ANCHOR,
- /* 89 */ YY_NO_ANCHOR,
- /* 90 */ YY_NO_ANCHOR,
- /* 91 */ YY_NO_ANCHOR,
- /* 92 */ YY_NOT_ACCEPT,
- /* 93 */ YY_NO_ANCHOR,
- /* 94 */ YY_NO_ANCHOR,
- /* 95 */ YY_NO_ANCHOR,
- /* 96 */ YY_NO_ANCHOR,
- /* 97 */ YY_NO_ANCHOR,
- /* 98 */ YY_NO_ANCHOR,
- /* 99 */ YY_NO_ANCHOR,
- /* 100 */ YY_NO_ANCHOR,
- /* 101 */ YY_NO_ANCHOR,
- /* 102 */ YY_NO_ANCHOR,
- /* 103 */ YY_NO_ANCHOR,
- /* 104 */ YY_NO_ANCHOR,
- /* 105 */ YY_NO_ANCHOR,
- /* 106 */ YY_NO_ANCHOR,
- /* 107 */ YY_NO_ANCHOR,
- /* 108 */ YY_NO_ANCHOR,
- /* 109 */ YY_NO_ANCHOR,
- /* 110 */ YY_NO_ANCHOR,
- /* 111 */ YY_NO_ANCHOR,
- /* 112 */ YY_NO_ANCHOR,
- /* 113 */ YY_NO_ANCHOR,
- /* 114 */ YY_NO_ANCHOR,
- /* 115 */ YY_NO_ANCHOR,
- /* 116 */ YY_NO_ANCHOR,
- /* 117 */ YY_NO_ANCHOR,
- /* 118 */ YY_NO_ANCHOR,
- /* 119 */ YY_NO_ANCHOR,
- /* 120 */ YY_NO_ANCHOR,
- /* 121 */ YY_NO_ANCHOR,
- /* 122 */ YY_NO_ANCHOR,
- /* 123 */ YY_NO_ANCHOR,
- /* 124 */ YY_NO_ANCHOR,
- /* 125 */ YY_NO_ANCHOR,
- /* 126 */ YY_NO_ANCHOR,
- /* 127 */ YY_NO_ANCHOR,
- /* 128 */ YY_NO_ANCHOR,
- /* 129 */ YY_NO_ANCHOR,
- /* 130 */ YY_NOT_ACCEPT,
- /* 131 */ YY_NO_ANCHOR,
- /* 132 */ YY_NO_ANCHOR,
- /* 133 */ YY_NO_ANCHOR,
- /* 134 */ YY_NO_ANCHOR,
- /* 135 */ YY_NO_ANCHOR,
- /* 136 */ YY_NO_ANCHOR,
- /* 137 */ YY_NO_ANCHOR,
- /* 138 */ YY_NO_ANCHOR,
- /* 139 */ YY_NO_ANCHOR,
- /* 140 */ YY_NO_ANCHOR,
- /* 141 */ YY_NO_ANCHOR,
- /* 142 */ YY_NOT_ACCEPT,
- /* 143 */ YY_NO_ANCHOR,
- /* 144 */ YY_NO_ANCHOR,
- /* 145 */ YY_NO_ANCHOR,
- /* 146 */ YY_NO_ANCHOR,
- /* 147 */ YY_NO_ANCHOR,
- /* 148 */ YY_NO_ANCHOR,
- /* 149 */ YY_NOT_ACCEPT,
- /* 150 */ YY_NO_ANCHOR,
- /* 151 */ YY_NO_ANCHOR,
- /* 152 */ YY_NOT_ACCEPT,
- /* 153 */ YY_NO_ANCHOR,
- /* 154 */ YY_NOT_ACCEPT,
- /* 155 */ YY_NO_ANCHOR,
- /* 156 */ YY_NOT_ACCEPT,
- /* 157 */ YY_NO_ANCHOR,
- /* 158 */ YY_NOT_ACCEPT,
- /* 159 */ YY_NO_ANCHOR,
- /* 160 */ YY_NOT_ACCEPT,
- /* 161 */ YY_NO_ANCHOR,
- /* 162 */ YY_NOT_ACCEPT,
- /* 163 */ YY_NO_ANCHOR,
- /* 164 */ YY_NOT_ACCEPT,
- /* 165 */ YY_NO_ANCHOR,
- /* 166 */ YY_NOT_ACCEPT,
- /* 167 */ YY_NO_ANCHOR,
- /* 168 */ YY_NOT_ACCEPT,
- /* 169 */ YY_NOT_ACCEPT,
- /* 170 */ YY_NOT_ACCEPT,
- /* 171 */ YY_NOT_ACCEPT,
- /* 172 */ YY_NOT_ACCEPT,
- /* 173 */ YY_NOT_ACCEPT,
- /* 174 */ YY_NOT_ACCEPT,
- /* 175 */ YY_NOT_ACCEPT,
- /* 176 */ YY_NOT_ACCEPT,
- /* 177 */ YY_NOT_ACCEPT,
- /* 178 */ YY_NOT_ACCEPT,
- /* 179 */ YY_NOT_ACCEPT,
- /* 180 */ YY_NOT_ACCEPT,
- /* 181 */ YY_NOT_ACCEPT,
- /* 182 */ YY_NOT_ACCEPT,
- /* 183 */ YY_NOT_ACCEPT,
- /* 184 */ YY_NOT_ACCEPT,
- /* 185 */ YY_NOT_ACCEPT,
- /* 186 */ YY_NOT_ACCEPT,
- /* 187 */ YY_NOT_ACCEPT,
- /* 188 */ YY_NOT_ACCEPT,
- /* 189 */ YY_NOT_ACCEPT,
- /* 190 */ YY_NOT_ACCEPT,
- /* 191 */ YY_NOT_ACCEPT,
- /* 192 */ YY_NOT_ACCEPT,
- /* 193 */ YY_NOT_ACCEPT,
- /* 194 */ YY_NOT_ACCEPT,
- /* 195 */ YY_NOT_ACCEPT,
- /* 196 */ YY_NOT_ACCEPT,
- /* 197 */ YY_NOT_ACCEPT,
- /* 198 */ YY_NOT_ACCEPT,
- /* 199 */ YY_NOT_ACCEPT,
- /* 200 */ YY_NOT_ACCEPT,
- /* 201 */ YY_NOT_ACCEPT,
- /* 202 */ YY_NOT_ACCEPT,
- /* 203 */ YY_NOT_ACCEPT,
- /* 204 */ YY_NOT_ACCEPT,
- /* 205 */ YY_NOT_ACCEPT,
- /* 206 */ YY_NOT_ACCEPT,
- /* 207 */ YY_NOT_ACCEPT,
- /* 208 */ YY_NOT_ACCEPT,
- /* 209 */ YY_NOT_ACCEPT,
- /* 210 */ YY_NOT_ACCEPT,
- /* 211 */ YY_NOT_ACCEPT,
- /* 212 */ YY_NOT_ACCEPT,
- /* 213 */ YY_NOT_ACCEPT,
- /* 214 */ YY_NOT_ACCEPT,
- /* 215 */ YY_NOT_ACCEPT,
- /* 216 */ YY_NOT_ACCEPT,
- /* 217 */ YY_NOT_ACCEPT,
- /* 218 */ YY_NOT_ACCEPT,
- /* 219 */ YY_NOT_ACCEPT,
- /* 220 */ YY_NOT_ACCEPT,
- /* 221 */ YY_NOT_ACCEPT,
- /* 222 */ YY_NOT_ACCEPT,
- /* 223 */ YY_NOT_ACCEPT,
- /* 224 */ YY_NOT_ACCEPT,
- /* 225 */ YY_NOT_ACCEPT,
- /* 226 */ YY_NOT_ACCEPT,
- /* 227 */ YY_NOT_ACCEPT,
- /* 228 */ YY_NOT_ACCEPT,
- /* 229 */ YY_NOT_ACCEPT,
- /* 230 */ YY_NOT_ACCEPT,
- /* 231 */ YY_NOT_ACCEPT,
- /* 232 */ YY_NOT_ACCEPT,
- /* 233 */ YY_NOT_ACCEPT,
- /* 234 */ YY_NOT_ACCEPT,
- /* 235 */ YY_NOT_ACCEPT,
- /* 236 */ YY_NOT_ACCEPT,
- /* 237 */ YY_NOT_ACCEPT,
- /* 238 */ YY_NOT_ACCEPT,
- /* 239 */ YY_NOT_ACCEPT,
- /* 240 */ YY_NOT_ACCEPT,
- /* 241 */ YY_NOT_ACCEPT,
- /* 242 */ YY_NOT_ACCEPT,
- /* 243 */ YY_NOT_ACCEPT,
- /* 244 */ YY_NOT_ACCEPT,
- /* 245 */ YY_NOT_ACCEPT,
- /* 246 */ YY_NOT_ACCEPT,
- /* 247 */ YY_NOT_ACCEPT,
- /* 248 */ YY_NOT_ACCEPT,
- /* 249 */ YY_NOT_ACCEPT,
- /* 250 */ YY_NOT_ACCEPT,
- /* 251 */ YY_NOT_ACCEPT,
- /* 252 */ YY_NOT_ACCEPT,
- /* 253 */ YY_NOT_ACCEPT,
- /* 254 */ YY_NOT_ACCEPT,
- /* 255 */ YY_NOT_ACCEPT,
- /* 256 */ YY_NOT_ACCEPT,
- /* 257 */ YY_NOT_ACCEPT,
- /* 258 */ YY_NOT_ACCEPT,
- /* 259 */ YY_NOT_ACCEPT,
- /* 260 */ YY_NOT_ACCEPT,
- /* 261 */ YY_NOT_ACCEPT,
- /* 262 */ YY_NOT_ACCEPT,
- /* 263 */ YY_NOT_ACCEPT,
- /* 264 */ YY_NOT_ACCEPT,
- /* 265 */ YY_NOT_ACCEPT,
- /* 266 */ YY_NOT_ACCEPT,
- /* 267 */ YY_NOT_ACCEPT,
- /* 268 */ YY_NOT_ACCEPT,
- /* 269 */ YY_NOT_ACCEPT,
- /* 270 */ YY_NOT_ACCEPT,
- /* 271 */ YY_NOT_ACCEPT,
- /* 272 */ YY_NOT_ACCEPT,
- /* 273 */ YY_NOT_ACCEPT,
- /* 274 */ YY_NOT_ACCEPT,
- /* 275 */ YY_NOT_ACCEPT,
- /* 276 */ YY_NOT_ACCEPT,
- /* 277 */ YY_NOT_ACCEPT,
- /* 278 */ YY_NOT_ACCEPT,
- /* 279 */ YY_NOT_ACCEPT,
- /* 280 */ YY_NOT_ACCEPT,
- /* 281 */ YY_NOT_ACCEPT,
- /* 282 */ YY_NOT_ACCEPT,
- /* 283 */ YY_NOT_ACCEPT,
- /* 284 */ YY_NOT_ACCEPT,
- /* 285 */ YY_NOT_ACCEPT,
- /* 286 */ YY_NOT_ACCEPT,
- /* 287 */ YY_NOT_ACCEPT,
- /* 288 */ YY_NOT_ACCEPT,
- /* 289 */ YY_NOT_ACCEPT,
- /* 290 */ YY_NOT_ACCEPT,
- /* 291 */ YY_NOT_ACCEPT,
- /* 292 */ YY_NOT_ACCEPT,
- /* 293 */ YY_NOT_ACCEPT,
- /* 294 */ YY_NOT_ACCEPT,
- /* 295 */ YY_NOT_ACCEPT,
- /* 296 */ YY_NOT_ACCEPT,
- /* 297 */ YY_NOT_ACCEPT,
- /* 298 */ YY_NOT_ACCEPT,
- /* 299 */ YY_NOT_ACCEPT,
- /* 300 */ YY_NOT_ACCEPT,
- /* 301 */ YY_NOT_ACCEPT,
- /* 302 */ YY_NOT_ACCEPT,
- /* 303 */ YY_NOT_ACCEPT,
- /* 304 */ YY_NOT_ACCEPT,
- /* 305 */ YY_NOT_ACCEPT,
- /* 306 */ YY_NOT_ACCEPT,
- /* 307 */ YY_NOT_ACCEPT,
- /* 308 */ YY_NOT_ACCEPT,
- /* 309 */ YY_NOT_ACCEPT,
- /* 310 */ YY_NOT_ACCEPT,
- /* 311 */ YY_NOT_ACCEPT,
- /* 312 */ YY_NOT_ACCEPT,
- /* 313 */ YY_NOT_ACCEPT,
- /* 314 */ YY_NOT_ACCEPT,
- /* 315 */ YY_NOT_ACCEPT,
- /* 316 */ YY_NOT_ACCEPT,
- /* 317 */ YY_NOT_ACCEPT,
- /* 318 */ YY_NOT_ACCEPT,
- /* 319 */ YY_NOT_ACCEPT,
- /* 320 */ YY_NOT_ACCEPT,
- /* 321 */ YY_NOT_ACCEPT,
- /* 322 */ YY_NOT_ACCEPT,
- /* 323 */ YY_NOT_ACCEPT,
- /* 324 */ YY_NOT_ACCEPT,
- /* 325 */ YY_NOT_ACCEPT,
- /* 326 */ YY_NOT_ACCEPT,
- /* 327 */ YY_NOT_ACCEPT,
- /* 328 */ YY_NOT_ACCEPT,
- /* 329 */ YY_NOT_ACCEPT,
- /* 330 */ YY_NOT_ACCEPT,
- /* 331 */ YY_NOT_ACCEPT,
- /* 332 */ YY_NOT_ACCEPT,
- /* 333 */ YY_NOT_ACCEPT,
- /* 334 */ YY_NOT_ACCEPT,
- /* 335 */ YY_NOT_ACCEPT,
- /* 336 */ YY_NOT_ACCEPT,
- /* 337 */ YY_NOT_ACCEPT,
- /* 338 */ YY_NOT_ACCEPT,
- /* 339 */ YY_NOT_ACCEPT,
- /* 340 */ YY_NOT_ACCEPT,
- /* 341 */ YY_NOT_ACCEPT,
- /* 342 */ YY_NOT_ACCEPT,
- /* 343 */ YY_NOT_ACCEPT,
- /* 344 */ YY_NOT_ACCEPT,
- /* 345 */ YY_NOT_ACCEPT,
- /* 346 */ YY_NOT_ACCEPT,
- /* 347 */ YY_NO_ANCHOR,
- /* 348 */ YY_NO_ANCHOR,
- /* 349 */ YY_NO_ANCHOR,
- /* 350 */ YY_NO_ANCHOR,
- /* 351 */ YY_NOT_ACCEPT,
- /* 352 */ YY_NOT_ACCEPT,
- /* 353 */ YY_NOT_ACCEPT,
- /* 354 */ YY_NOT_ACCEPT,
- /* 355 */ YY_NOT_ACCEPT,
- /* 356 */ YY_NOT_ACCEPT,
- /* 357 */ YY_NOT_ACCEPT,
- /* 358 */ YY_NOT_ACCEPT,
- /* 359 */ YY_NOT_ACCEPT,
- /* 360 */ YY_NOT_ACCEPT,
- /* 361 */ YY_NOT_ACCEPT,
- /* 362 */ YY_NOT_ACCEPT,
- /* 363 */ YY_NOT_ACCEPT,
- /* 364 */ YY_NOT_ACCEPT,
- /* 365 */ YY_NOT_ACCEPT,
- /* 366 */ YY_NOT_ACCEPT,
- /* 367 */ YY_NOT_ACCEPT,
- /* 368 */ YY_NOT_ACCEPT,
- /* 369 */ YY_NOT_ACCEPT,
- /* 370 */ YY_NOT_ACCEPT,
- /* 371 */ YY_NOT_ACCEPT,
- /* 372 */ YY_NOT_ACCEPT,
- /* 373 */ YY_NOT_ACCEPT,
- /* 374 */ YY_NOT_ACCEPT,
- /* 375 */ YY_NOT_ACCEPT,
- /* 376 */ YY_NOT_ACCEPT,
- /* 377 */ YY_NOT_ACCEPT,
- /* 378 */ YY_NOT_ACCEPT,
- /* 379 */ YY_NOT_ACCEPT,
- /* 380 */ YY_NOT_ACCEPT,
- /* 381 */ YY_NOT_ACCEPT,
- /* 382 */ YY_NOT_ACCEPT,
- /* 383 */ YY_NOT_ACCEPT,
- /* 384 */ YY_NOT_ACCEPT,
- /* 385 */ YY_NOT_ACCEPT,
- /* 386 */ YY_NOT_ACCEPT,
- /* 387 */ YY_NOT_ACCEPT,
- /* 388 */ YY_NOT_ACCEPT,
- /* 389 */ YY_NOT_ACCEPT,
- /* 390 */ YY_NOT_ACCEPT,
- /* 391 */ YY_NOT_ACCEPT,
- /* 392 */ YY_NOT_ACCEPT,
- /* 393 */ YY_NOT_ACCEPT,
- /* 394 */ YY_NOT_ACCEPT,
- /* 395 */ YY_NOT_ACCEPT,
- /* 396 */ YY_NOT_ACCEPT,
- /* 397 */ YY_NOT_ACCEPT,
- /* 398 */ YY_NOT_ACCEPT,
- /* 399 */ YY_NOT_ACCEPT,
- /* 400 */ YY_NOT_ACCEPT,
- /* 401 */ YY_NOT_ACCEPT,
- /* 402 */ YY_NOT_ACCEPT,
- /* 403 */ YY_NOT_ACCEPT,
- /* 404 */ YY_NOT_ACCEPT,
- /* 405 */ YY_NOT_ACCEPT,
- /* 406 */ YY_NOT_ACCEPT,
- /* 407 */ YY_NOT_ACCEPT,
- /* 408 */ YY_NOT_ACCEPT,
- /* 409 */ YY_NOT_ACCEPT,
- /* 410 */ YY_NOT_ACCEPT,
- /* 411 */ YY_NOT_ACCEPT,
- /* 412 */ YY_NOT_ACCEPT,
- /* 413 */ YY_NOT_ACCEPT,
- /* 414 */ YY_NOT_ACCEPT,
- /* 415 */ YY_NOT_ACCEPT,
- /* 416 */ YY_NOT_ACCEPT,
- /* 417 */ YY_NOT_ACCEPT,
- /* 418 */ YY_NOT_ACCEPT
- );
-
-
- var $yy_cmap = array(
- 31, 31, 31, 31, 31, 31, 31, 31,
- 31, 11, 5, 31, 31, 12, 31, 31,
- 31, 31, 31, 31, 31, 31, 31, 31,
- 31, 31, 31, 31, 31, 31, 31, 31,
- 11, 14, 30, 2, 32, 25, 1, 29,
- 33, 21, 32, 32, 52, 15, 7, 9,
- 3, 3, 3, 3, 3, 44, 3, 55,
- 3, 3, 10, 4, 8, 28, 13, 24,
- 31, 19, 45, 17, 18, 6, 6, 6,
- 6, 40, 6, 6, 6, 6, 6, 6,
- 42, 6, 39, 35, 20, 6, 6, 6,
- 6, 6, 6, 16, 26, 22, 31, 27,
- 31, 50, 45, 37, 46, 49, 47, 6,
- 51, 41, 6, 6, 54, 6, 53, 48,
- 42, 6, 38, 36, 43, 6, 6, 6,
- 6, 6, 6, 23, 31, 34, 31, 31,
- 31, 31, 31, 31, 31, 31, 31, 31,
- 31, 31, 31, 31, 31, 31, 31, 31,
- 31, 31, 31, 31, 31, 31, 31, 31,
- 31, 31, 31, 31, 31, 31, 31, 31,
- 31, 31, 31, 31, 31, 31, 31, 31,
- 31, 31, 31, 31, 31, 31, 31, 31,
- 31, 31, 31, 31, 31, 31, 31, 31,
- 31, 31, 31, 31, 31, 31, 31, 31,
- 31, 31, 31, 31, 31, 31, 31, 31,
- 31, 31, 31, 31, 31, 31, 31, 31,
- 31, 31, 31, 31, 31, 31, 31, 31,
- 31, 31, 31, 31, 31, 31, 31, 31,
- 31, 31, 31, 31, 31, 31, 31, 31,
- 31, 31, 31, 31, 31, 31, 31, 31,
- 31, 31, 31, 31, 31, 31, 31, 31,
- 31, 31, 31, 31, 31, 31, 31, 31,
- 31, 0, 0
- );
-
-
- var $yy_rmap = array(
- 0, 1, 2, 3, 4, 5, 1, 6,
- 7, 8, 9, 1, 10, 1, 11, 12,
- 1, 3, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 13,
- 1, 1, 1, 14, 1, 1, 15, 16,
- 17, 1, 1, 18, 19, 18, 1, 1,
- 1, 20, 1, 1, 21, 1, 22, 1,
- 23, 24, 25, 1, 1, 26, 27, 28,
- 29, 30, 1, 1, 31, 32, 1, 33,
- 1, 1, 1, 34, 1, 1, 1, 35,
- 1, 36, 1, 37, 1, 38, 1, 39,
- 40, 1, 1, 1, 41, 42, 43, 1,
- 44, 45, 1, 1, 46, 47, 48, 49,
- 50, 51, 18, 52, 53, 54, 55, 56,
- 57, 58, 59, 60, 61, 62, 1, 63,
- 64, 1, 65, 66, 67, 68, 69, 40,
- 70, 71, 72, 73, 74, 75, 76, 77,
- 75, 78, 79, 1, 80, 81, 82, 1,
- 83, 1, 1, 84, 85, 86, 87, 88,
- 89, 90, 91, 92, 93, 94, 95, 96,
- 97, 98, 99, 100, 101, 102, 103, 104,
- 105, 106, 107, 108, 109, 110, 111, 112,
- 113, 114, 115, 116, 117, 118, 119, 120,
- 121, 122, 123, 124, 125, 126, 127, 128,
- 129, 130, 131, 132, 133, 134, 135, 136,
- 137, 138, 139, 140, 141, 142, 143, 144,
- 145, 146, 147, 148, 149, 150, 151, 152,
- 153, 154, 155, 156, 157, 158, 159, 160,
- 161, 162, 163, 164, 73, 165, 166, 167,
- 168, 169, 170, 171, 172, 173, 174, 175,
- 176, 177, 178, 179, 180, 181, 182, 183,
- 184, 185, 16, 186, 187, 188, 189, 90,
- 190, 78, 84, 191, 192, 64, 193, 194,
- 195, 92, 94, 196, 96, 197, 198, 199,
- 200, 201, 202, 203, 204, 205, 206, 207,
- 208, 209, 210, 211, 212, 213, 214, 100,
- 215, 216, 217, 218, 219, 220, 221, 222,
- 223, 224, 225, 226, 227, 228, 229, 230,
- 231, 232, 233, 234, 235, 236, 237, 238,
- 239, 240, 241, 242, 243, 244, 245, 246,
- 247, 248, 249, 250, 251, 252, 253, 254,
- 255, 256, 257, 40, 258, 259, 260, 71,
- 261, 262, 263, 264, 265, 266, 267, 268,
- 269, 270, 271, 272, 77, 273, 274, 275,
- 117, 276, 277, 278, 279, 280, 281, 129,
- 282, 283, 284, 285, 138, 286, 287, 288,
- 150, 289, 154, 290, 170, 291, 177, 292,
- 198, 293, 205, 294, 216, 295, 222, 296,
- 239, 297, 243, 298, 260, 299, 264, 300,
- 301, 302, 303, 304, 305, 306, 307, 308,
- 309, 310, 311, 312, 313, 314, 315, 316,
- 317, 318, 319, 320, 321, 322, 323, 324,
- 325, 326, 327
- );
-
-
- var $yy_nxt = array(
- array( 1, 2, 3, 3, 3, 3, 3, 3,
- 93, 3, 3, 3, 3, 3, 3, 3,
- 3, 3, 3, 3, 3, 94, 347, 132,
- 3, 3, 3, 3, 3, 3, 3, 3,
- 3, 3, 3, 3, 3, 3, 3, 3,
- 3, 3, 3, 3, 3, 3, 3, 3,
- 3, 3, 3, 3, 3, 3, 3, 3 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, 92, 3, 3, 3, 4, 3,
- -1, 3, 3, 3, 3, 3, 3, 3,
- 3, 4, 4, 4, 4, 3, 3, 3,
- 3, 3, 3, 3, 3, 3, 3, 3,
- 3, 3, 3, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 3, 4, 4, 4,
- 4, 4, 4, 4, 3, 4, 4, 3 ),
- array( -1, 130, 3, 3, 3, 3, 3, 3,
- 142, 3, 3, 3, 3, 3, 3, 3,
- 3, 3, 3, 3, 3, -1, 3, -1,
- 3, 3, 3, 3, 3, 3, 3, 3,
- 3, 3, 3, 3, 3, 3, 3, 3,
- 3, 3, 3, 3, 3, 3, 3, 3,
- 3, 3, 3, 3, 3, 3, 3, 3 ),
- array( -1, -1, -1, 4, 95, 95, 4, 4,
- -1, -1, -1, -1, -1, -1, -1, 4,
- -1, 4, 4, 4, 4, -1, -1, -1,
- -1, -1, -1, 4, -1, -1, -1, -1,
- -1, -1, -1, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, -1, 4, 4, 4 ),
- array( -1, -1, -1, 5, -1, 96, 5, 5,
- -1, -1, 5, 96, 96, -1, -1, 5,
- -1, 5, 5, 5, 5, -1, -1, -1,
- -1, -1, -1, 5, -1, -1, -1, -1,
- -1, -1, -1, 5, 5, 5, 5, 5,
- 5, 5, 5, 5, 5, 5, 5, 5,
- 5, 5, 5, 5, -1, 5, 5, 5 ),
- array( -1, -1, -1, -1, -1, 97, 15, -1,
- -1, -1, -1, 97, 97, -1, -1, -1,
- -1, 15, 15, 15, 15, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, 15, 15, 15, 15, 15,
- 15, 15, 15, 15, -1, 15, 15, 15,
- 15, 15, 15, 15, -1, 15, 15, -1 ),
- array( -1, -1, -1, 8, 98, 98, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, 8, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, 8 ),
- array( -1, -1, -1, 9, 99, 99, 9, 9,
- -1, -1, -1, -1, -1, -1, -1, 9,
- -1, 9, 9, 9, 9, -1, -1, -1,
- -1, -1, -1, 9, -1, -1, -1, -1,
- -1, -1, -1, 9, 9, 9, 9, 9,
- 9, 9, 9, 9, 9, 9, 9, 9,
- 9, 9, 9, 9, -1, 9, 9, 9 ),
- array( -1, -1, -1, 10, -1, 100, 10, 10,
- -1, 162, 10, 100, 100, -1, -1, 10,
- -1, 10, 10, 10, 10, -1, -1, -1,
- -1, -1, -1, 10, -1, -1, -1, -1,
- -1, -1, -1, 10, 10, 10, 10, 10,
- 10, 10, 10, 10, 10, 10, 10, 10,
- 10, 10, 10, 10, -1, 10, 10, 10 ),
- array( -1, -1, -1, 12, -1, 101, 12, 12,
- -1, -1, -1, 101, 101, -1, -1, 12,
- -1, 12, 12, 12, 12, -1, -1, -1,
- -1, -1, -1, 12, -1, -1, -1, -1,
- -1, -1, -1, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, -1, 12, 12, 12 ),
- array( -1, -1, -1, -1, -1, 102, -1, -1,
- -1, -1, -1, 102, 102, -1, -1, -1,
- -1, 172, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, 15, -1, 103, 15, 15,
- -1, -1, -1, 103, 103, -1, -1, 15,
- -1, 15, 15, 15, 15, -1, -1, -1,
- -1, -1, -1, 15, -1, -1, -1, -1,
- -1, -1, -1, 15, 15, 15, 15, 15,
- 15, 15, 15, 15, 15, 15, 15, 15,
- 15, 15, 15, 15, -1, 15, 15, 15 ),
- array( -1, 31, 31, 31, 31, 31, 31, 31,
- 31, 31, 31, 31, 31, 31, 31, 31,
- 31, 31, 31, 31, 31, 31, 31, -1,
- 31, -1, 228, 31, 31, -1, 31, 31,
- 31, 31, 31, 31, 31, 31, 31, 31,
- 31, 31, 31, 31, 31, 31, 31, 31,
- 31, 31, 31, 31, 31, 31, 31, 31 ),
- array( 1, 143, 143, 143, 143, 105, 143, 143,
- 36, 143, 143, 105, 105, 37, 143, 143,
- 143, 143, 143, 143, 143, 143, 143, 143,
- 143, 143, 143, 143, 143, 143, 143, 143,
- 143, 143, 143, 143, 143, 143, 143, 143,
- 143, 143, 143, 143, 143, 143, 143, 143,
- 143, 143, 143, 143, 143, 143, 143, 143 ),
- array( -1, -1, -1, 38, -1, 107, 38, 38,
- -1, -1, 38, 107, 107, -1, -1, 38,
- -1, 38, 38, 38, 38, -1, -1, -1,
- -1, -1, -1, 38, 40, -1, -1, -1,
- -1, -1, -1, 38, 38, 38, 38, 38,
- 38, 38, 38, 38, 38, 38, 38, 38,
- 38, 38, 38, 38, -1, 38, 38, 38 ),
- array( -1, -1, -1, -1, -1, 250, -1, -1,
- -1, -1, -1, 250, 250, 41, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, 40, -1, -1,
- -1, -1, -1, 40, 40, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, 43, 43, 43, 43, 108, 43, 43,
- 43, 43, 43, 108, 108, -1, 43, 43,
- 43, 43, 43, 43, 43, 43, 43, 43,
- 43, 43, 43, 43, 43, -1, -1, 43,
- 43, 43, 43, 43, 43, 43, 43, 43,
- 43, 43, 43, 43, 43, 43, 43, 43,
- 43, 43, 43, 43, 43, 43, 43, 43 ),
- array( -1, 43, 43, 44, 43, 109, 44, 44,
- 43, 43, 43, 109, 109, -1, 43, 44,
- 43, 44, 44, 44, 44, 43, 43, 43,
- 43, 43, 43, 44, 43, -1, -1, 43,
- 43, 43, 43, 44, 44, 44, 44, 44,
- 44, 44, 44, 44, 44, 44, 44, 44,
- 44, 44, 44, 44, 43, 44, 44, 44 ),
- array( -1, -1, -1, -1, -1, 49, -1, -1,
- -1, -1, -1, 49, 49, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, 52, 52, 52, 52, 52, 52, 52,
- 52, 52, 52, 52, 52, 52, 52, 52,
- 52, 52, 52, 52, 52, 52, 52, -1,
- 52, -1, 255, 52, 52, 52, -1, 52,
- 52, 52, 52, 52, 52, 52, 52, 52,
- 52, 52, 52, 52, 52, 52, 52, 52,
- 52, 52, 52, 52, 52, 52, 52, 52 ),
- array( 1, 55, 55, 56, 55, 111, 57, 58,
- 55, 55, 55, 111, 111, 59, 55, 58,
- 60, 57, 57, 57, 57, 55, 55, 55,
- 55, 112, 55, 58, 55, 137, 147, 55,
- 55, 55, 55, 57, 57, 57, 57, 57,
- 57, 57, 57, 57, 56, 57, 57, 57,
- 57, 57, 57, 57, 55, 57, 57, 56 ),
- array( -1, -1, -1, 56, -1, 113, 61, 61,
- -1, -1, -1, 113, 113, -1, -1, 61,
- -1, 61, 61, 61, 61, -1, -1, -1,
- -1, -1, -1, 61, -1, -1, -1, -1,
- -1, -1, -1, 61, 61, 61, 61, 61,
- 61, 61, 61, 61, 56, 61, 61, 61,
- 61, 61, 61, 61, -1, 61, 61, 56 ),
- array( -1, -1, -1, 57, -1, 114, 57, 57,
- -1, -1, -1, 114, 114, -1, -1, 57,
- -1, 57, 57, 57, 57, -1, -1, -1,
- -1, -1, -1, 57, -1, -1, -1, -1,
- -1, -1, -1, 57, 57, 57, 57, 57,
- 57, 57, 57, 57, 57, 57, 57, 57,
- 57, 57, 57, 57, -1, 57, 57, 57 ),
- array( -1, -1, -1, 58, -1, 115, 58, 58,
- -1, -1, -1, 115, 115, -1, -1, 58,
- -1, 58, 58, 58, 58, -1, -1, -1,
- -1, -1, -1, 58, -1, -1, -1, -1,
- -1, -1, -1, 58, 58, 58, 58, 58,
- 58, 58, 58, 58, 58, 58, 58, 58,
- 58, 58, 58, 58, -1, 58, 58, 58 ),
- array( -1, -1, -1, 61, -1, 116, 61, 61,
- -1, -1, -1, 116, 116, -1, -1, 61,
- -1, 61, 61, 61, 61, -1, -1, -1,
- -1, -1, -1, 61, -1, -1, -1, -1,
- -1, -1, -1, 61, 61, 61, 61, 61,
- 61, 61, 61, 61, 61, 61, 61, 61,
- 61, 61, 61, 61, -1, 61, 61, 61 ),
- array( -1, -1, -1, -1, -1, 62, -1, -1,
- -1, -1, -1, 62, 62, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, 63, 117, 117, 63, 63,
- -1, -1, -1, 117, 117, -1, -1, 63,
- -1, 63, 63, 63, 63, -1, -1, -1,
- -1, -1, -1, 63, -1, -1, -1, -1,
- -1, -1, -1, 63, 63, 63, 63, 63,
- 63, 63, 63, 63, 63, 63, 63, 63,
- 63, 63, 63, 63, -1, 63, 63, 63 ),
- array( -1, -1, -1, -1, -1, 64, -1, -1,
- -1, -1, -1, 64, 64, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( 1, 119, 119, 119, 119, 119, 119, 119,
- 119, 119, 119, 119, 119, 119, 119, 151,
- 119, 119, 119, 119, 119, 119, 119, 119,
- 119, 119, 119, 119, 119, 119, 119, 119,
- 119, 119, 119, 119, 119, 119, 119, 119,
- 119, 119, 119, 119, 119, 119, 119, 119,
- 119, 119, 119, 119, 119, 119, 119, 119 ),
- array( -1, 68, 68, 68, 68, 68, 68, 68,
- 68, 68, 68, 68, 68, 68, 68, 68,
- 68, 68, 68, 68, 68, 68, -1, 68,
- 68, 68, 68, 68, 68, 68, 68, 68,
- 68, 68, 68, 68, 68, 68, 68, 68,
- 68, 68, 68, 68, 68, 68, 68, 68,
- 68, 68, 68, 68, 68, 68, 68, 68 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, 263, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, 121, -1, -1, -1 ),
- array( -1, -1, -1, 75, -1, -1, 75, 288,
- -1, -1, -1, -1, -1, -1, -1, -1,
- 289, 75, 75, 75, 75, -1, -1, -1,
- -1, 405, -1, 75, -1, -1, -1, -1,
- -1, -1, -1, 75, 75, 75, 75, 75,
- 75, 75, 75, 75, 75, 75, 75, 75,
- 75, 75, 75, 75, -1, 75, 75, 75 ),
- array( -1, 79, 79, 79, 79, 79, 79, 79,
- -1, 79, 79, 79, 79, 79, 79, 79,
- 79, 79, 79, 79, 79, 79, 79, 79,
- 79, 79, 79, 79, 79, 79, 79, 79,
- 79, 79, 79, 79, 79, 79, 79, 79,
- 79, 79, 79, 79, 79, 79, 79, 79,
- 79, 79, 79, 79, 79, 79, 79, 79 ),
- array( -1, 81, 81, 81, 81, 81, 81, 81,
- 81, 81, 81, 81, 81, 81, 81, 81,
- 81, 81, 81, 81, 81, 81, -1, -1,
- 81, 81, 81, 81, 81, 81, 81, 81,
- 81, 81, 81, 81, 81, 81, 81, 81,
- 81, 81, 81, 81, 81, 81, 81, 81,
- 81, 81, 81, 81, 81, 81, 81, 81 ),
- array( 1, 125, 125, 125, 125, 125, 125, 125,
- 125, 125, 125, 125, 125, 125, 125, 167,
- 125, 125, 125, 125, 125, 125, 125, 125,
- 125, 125, 125, 125, 125, 125, 125, 125,
- 125, 125, 125, 125, 125, 125, 125, 125,
- 125, 125, 125, 125, 125, 125, 125, 125,
- 125, 125, 125, 125, 125, 125, 125, 125 ),
- array( 1, 126, 126, 126, 126, 126, 126, 126,
- 126, 126, 126, 126, 126, 126, 126, 126,
- 126, 126, 126, 126, 126, 126, 126, 126,
- 328, 126, 126, 126, 126, 126, 126, 126,
- 126, 126, 126, 126, 126, 126, 126, 126,
- 126, 126, 126, 126, 126, 126, 126, 126,
- 126, 126, 126, 126, 126, 126, 126, 126 ),
- array( 1, 88, 88, 88, 88, 127, 88, 88,
- 88, 88, 88, 127, 127, 88, 88, 128,
- 88, 88, 88, 88, 88, 88, 88, 141,
- 88, 88, 88, 88, 88, 88, 88, 88,
- 88, 88, 88, 88, 88, 88, 88, 88,
- 88, 88, 88, 88, 88, 88, 88, 88,
- 88, 88, 88, 88, 88, 88, 88, 88 ),
- array( -1, 140, 140, 140, 140, 140, 140, 140,
- 140, 140, 140, 140, 140, 140, 140, -1,
- 140, 140, 140, 140, 140, 140, 140, 140,
- 140, 140, 140, 140, 140, 140, 140, 140,
- 140, 140, 140, 140, 140, 140, 140, 140,
- 140, 140, 140, 140, 140, 140, 140, 140,
- 140, 140, 140, 140, 140, 140, 140, 140 ),
- array( -1, -1, -1, 8, -1, -1, 9, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, 9, 9, 9, 9, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, 9, 9, 9, 9, 9,
- 9, 9, 9, 9, 8, 9, 9, 9,
- 9, 9, 9, 9, -1, 9, 9, 8 ),
- array( -1, -1, -1, -1, -1, 3, 5, -1,
- -1, 149, -1, 3, 3, 6, 152, -1,
- 3, 5, 5, 5, 5, -1, 3, 3,
- 7, -1, 3, 3, -1, -1, -1, 3,
- -1, -1, 3, 5, 5, 5, 5, 5,
- 5, 5, 5, 5, -1, 5, 5, 5,
- 5, 5, 5, 5, -1, 5, 5, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, 154, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, 96, -1, -1,
- -1, -1, -1, 96, 96, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, 97, -1, -1,
- -1, -1, -1, 97, 97, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, 100, -1, -1,
- -1, 162, -1, 100, 100, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, 101, -1, -1,
- -1, -1, -1, 101, 101, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, 102, -1, -1,
- -1, -1, -1, 102, 102, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, 103, -1, -1,
- -1, -1, -1, 103, 103, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, 229, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, 229, 229, 229, 229, -1, -1, -1,
- -1, -1, -1, 230, -1, -1, -1, -1,
- -1, -1, -1, 229, 229, 229, 229, 229,
- 229, 229, 229, 229, -1, 229, 229, 229,
- 229, 229, 229, 229, -1, 229, 229, -1 ),
- array( -1, -1, -1, -1, -1, 105, -1, -1,
- -1, -1, -1, 105, 105, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, 107, -1, -1,
- -1, -1, -1, 107, 107, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, 40, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, 108, -1, -1,
- -1, -1, -1, 108, 108, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, 109, -1, -1,
- -1, -1, -1, 109, 109, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, 229, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, 229, 229, 229, 229, -1, -1, -1,
- -1, -1, -1, 256, -1, -1, -1, -1,
- -1, -1, -1, 229, 229, 229, 229, 229,
- 229, 229, 229, 229, -1, 229, 229, 229,
- 229, 229, 229, 229, -1, 229, 229, -1 ),
- array( -1, -1, -1, -1, -1, 111, -1, -1,
- -1, -1, -1, 111, 111, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, 62, 63, -1,
- -1, -1, -1, 62, 62, -1, -1, -1,
- -1, 63, 63, 63, 63, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, 63, 63, 63, 63, 63,
- 63, 63, 63, 63, -1, 63, 63, 63,
- 63, 63, 63, 63, -1, 63, 63, -1 ),
- array( -1, -1, -1, -1, -1, 113, -1, -1,
- -1, -1, -1, 113, 113, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, 114, -1, -1,
- -1, -1, -1, 114, 114, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, 115, -1, -1,
- -1, -1, -1, 115, 115, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, 116, -1, -1,
- -1, -1, -1, 116, 116, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, 117, -1, -1,
- -1, -1, -1, 117, 117, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, 119, 119, 119, 119, 119, 119, 119,
- 119, 119, 119, 119, 119, 119, 119, 259,
- 119, 119, 119, 119, 119, 119, 119, 119,
- 119, 119, 119, 119, 119, 119, 119, 119,
- 119, 119, 119, 119, 119, 119, 119, 119,
- 119, 119, 119, 119, 119, 119, 119, 119,
- 119, 119, 119, 119, 119, 119, 119, 119 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, 67, -1, 261,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, 288,
- -1, -1, -1, -1, -1, -1, -1, -1,
- 289, -1, -1, -1, -1, -1, -1, -1,
- -1, 405, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, 302, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, 148, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, 125, 125, 125, 125, 125, 125, 125,
- 125, 125, 125, 125, 125, 125, 125, 326,
- 125, 125, 125, 125, 125, 125, 125, 125,
- 125, 125, 125, 125, 125, 125, 125, 125,
- 125, 125, 125, 125, 125, 125, 125, 125,
- 125, 125, 125, 125, 125, 125, 125, 125,
- 125, 125, 125, 125, 125, 125, 125, 125 ),
- array( -1, 126, 126, 126, 126, 126, 126, 126,
- 126, 126, 126, 126, 126, 126, 126, 126,
- 126, 126, 126, 126, 126, 126, 126, 126,
- -1, 126, 126, 126, 126, 126, 126, 126,
- 126, 126, 126, 126, 126, 126, 126, 126,
- 126, 126, 126, 126, 126, 126, 126, 126,
- 126, 126, 126, 126, 126, 126, 126, 126 ),
- array( -1, 140, 140, 140, 140, 140, 140, 140,
- 140, 140, 140, 140, 140, 140, 140, 329,
- 140, 140, 140, 140, 140, 140, 140, 140,
- 140, 140, 140, 140, 140, 140, 140, 140,
- 140, 140, 140, 140, 140, 140, 140, 140,
- 140, 140, 140, 140, 140, 140, 140, 140,
- 140, 140, 140, 140, 140, 140, 140, 140 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, 90, -1, 335,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, 3, 3, 3, -1, 3,
- -1, 3, 3, 3, 3, 3, 3, 3,
- 3, -1, -1, -1, -1, 3, 3, 3,
- 3, 3, 3, 3, 3, 3, 3, 3,
- 3, 3, 3, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, 3, -1, -1, -1,
- -1, -1, -1, -1, 3, -1, -1, 3 ),
- array( -1, 31, 31, 31, 31, 31, 31, 31,
- 31, 31, 31, 31, 31, 31, 31, 31,
- 31, 31, 31, 31, 31, 31, 31, 31,
- 31, 31, 31, 31, 31, -1, 31, 31,
- 31, 31, 31, 31, 31, 31, 31, 31,
- 31, 31, 31, 31, 31, 31, 31, 31,
- 31, 31, 31, 31, 31, 31, 31, 31 ),
- array( -1, -1, -1, -1, -1, -1, 156, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, 156, 156, 156, 156, -1, -1, -1,
- -1, -1, -1, 158, -1, -1, -1, -1,
- -1, -1, -1, 156, 156, 156, 156, 156,
- 156, 351, 156, 156, -1, 156, 156, 417,
- 156, 392, 156, 156, -1, 156, 156, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, 231 ),
- array( 1, 143, 143, 143, 143, 105, 38, 143,
- 36, 39, 143, 105, 105, 37, 143, 143,
- 143, 38, 38, 38, 38, 143, 143, 143,
- 150, 143, 143, 143, 143, 143, 143, 143,
- 143, 143, 143, 38, 38, 38, 38, 38,
- 38, 38, 38, 38, 143, 38, 38, 38,
- 38, 38, 38, 38, 143, 38, 38, 143 ),
- array( -1, 43, 43, 135, 43, 109, 135, 135,
- 43, 43, 43, 109, 109, -1, 43, 135,
- 43, 135, 135, 135, 135, 43, 43, 43,
- 43, 43, 43, 135, 43, -1, -1, 43,
- 43, 43, 43, 135, 135, 135, 135, 135,
- 135, 135, 135, 135, 135, 135, 135, 135,
- 135, 135, 135, 135, 43, 135, 135, 135 ),
- array( -1, 257, 257, 257, 257, 257, 257, 257,
- 257, 257, 257, 257, 257, 257, 257, 257,
- 257, 257, 257, 257, 257, 257, 257, 257,
- 257, 257, 257, 257, 257, 64, 257, 257,
- 257, 257, 257, 257, 257, 257, 257, 257,
- 257, 257, 257, 257, 257, 257, 257, 257,
- 257, 257, 257, 257, 257, 257, 257, 257 ),
- array( -1, -1, -1, -1, -1, -1, 310, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, 310, 310, 310, 310, -1, -1, -1,
- -1, -1, -1, 310, -1, -1, -1, -1,
- -1, -1, -1, 310, 310, 310, 310, 310,
- 310, 310, 310, 310, -1, 310, 310, 418,
- 310, 395, 310, 310, -1, 310, 310, -1 ),
- array( -1, 331, 331, 331, 331, 127, 331, 331,
- 331, 331, 331, 127, 127, 331, 331, 331,
- 331, 331, 331, 331, 331, 331, 331, -1,
- 331, 331, 331, 331, 331, 331, 331, 331,
- 331, 331, 331, 331, 331, 331, 331, 331,
- 331, 331, 331, 331, 331, 331, 331, 331,
- 331, 331, 331, 331, 331, 331, 331, 331 ),
- array( -1, -1, -1, -1, -1, -1, 330, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, 330, 330, 330, 330, -1, -1, -1,
- -1, -1, -1, 330, -1, -1, -1, -1,
- -1, -1, -1, 330, 330, 330, 330, 330,
- 330, 330, 330, 330, -1, 330, 330, 330,
- 330, 330, 330, 330, -1, 330, 330, -1 ),
- array( -1, -1, -1, -1, -1, 3, -1, -1,
- -1, -1, -1, 3, 3, -1, -1, -1,
- 3, -1, -1, -1, -1, -1, 3, 3,
- -1, -1, 3, 3, -1, -1, -1, 3,
- -1, -1, 3, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, 130, 3, 3, 3, 3, 3, 3,
- 142, 3, 3, 3, 3, 17, 3, 3,
- 3, 3, 3, 3, 3, -1, 3, -1,
- 3, 3, 3, 3, 3, 3, 3, 3,
- 3, 3, 3, 3, 3, 3, 3, 3,
- 3, 3, 3, 3, 3, 3, 3, 3,
- 3, 3, 3, 3, 3, 3, 3, 3 ),
- array( -1, 258, 258, 258, 258, 258, 258, 258,
- 258, 258, 258, 258, 258, 258, 258, 258,
- 258, 258, 258, 258, 258, 258, 258, 258,
- 258, 258, 258, 258, 258, 258, 118, 258,
- 258, 258, 258, 258, 258, 258, 258, 258,
- 258, 258, 258, 258, 258, 258, 258, 258,
- 258, 258, 258, 258, 258, 258, 258, 258 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, 82, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, 160, 10, -1,
- -1, 162, -1, 160, 160, 11, -1, -1,
- -1, 10, 10, 10, 10, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, 10, 10, 10, 10, 10,
- 10, 10, 10, 10, -1, 10, 10, 10,
- 10, 10, 10, 10, -1, 10, 10, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, 42, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, 119, 119, 119, 119, 119, 119, 119,
- 119, 119, 119, 119, 119, 119, 119, 260,
- 119, 119, 119, 119, 119, 119, 119, 119,
- 119, 119, 119, 119, 119, 119, 119, 119,
- 119, 119, 119, 119, 119, 119, 119, 119,
- 119, 119, 119, 119, 119, 119, 119, 119,
- 119, 119, 119, 119, 119, 119, 119, 119 ),
- array( -1, -1, -1, -1, -1, -1, 12, -1,
- -1, -1, -1, -1, -1, 13, -1, 164,
- 14, 12, 12, 12, 12, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, -1, 12, 12, 12,
- 12, 12, 12, 12, -1, 12, 12, -1 ),
- array( -1, 52, 52, 52, 52, 52, 52, 52,
- 52, 52, 52, 52, 52, 52, 52, 52,
- 52, 52, 52, 52, 52, 52, 52, 52,
- 52, 52, -1, 52, 52, 52, -1, 52,
- 52, 52, 52, 52, 52, 52, 52, 52,
- 52, 52, 52, 52, 52, 52, 52, 52,
- 52, 52, 52, 52, 52, 52, 52, 52 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, 16, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, 265, 71, 265, 265, 265, 265, 265,
- 265, 265, 265, 265, 265, 265, 265, 265,
- 265, 265, 265, 265, 265, 265, 265, 265,
- 265, 265, 265, 265, 265, 265, 265, 265,
- 265, 265, 265, 265, 265, 265, 265, 265,
- 265, 265, 265, 265, 265, 265, 265, 265,
- 265, 265, 265, 265, 265, 265, 265, 265 ),
- array( -1, -1, -1, 156, -1, -1, 156, 166,
- -1, -1, 168, -1, -1, -1, -1, -1,
- 169, 156, 156, 156, 156, -1, -1, -1,
- -1, 170, -1, 156, -1, -1, -1, -1,
- -1, 18, 19, 156, 156, 156, 156, 156,
- 156, 156, 156, 156, 156, 156, 156, 156,
- 156, 156, 156, 156, -1, 156, 156, 156 ),
- array( -1, -1, -1, 266, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, 267, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, 266, -1, -1, -1,
- -1, -1, -1, -1, 72, -1, -1, 266 ),
- array( -1, -1, -1, 156, -1, -1, 156, 166,
- -1, -1, 168, -1, -1, -1, -1, -1,
- 169, 156, 156, 156, 156, -1, -1, -1,
- -1, 170, -1, 156, -1, -1, -1, -1,
- -1, 20, 19, 156, 156, 156, 156, 156,
- 156, 156, 156, 156, 156, 156, 156, 156,
- 156, 156, 156, 156, -1, 156, 156, 156 ),
- array( -1, -1, -1, 268, -1, -1, 268, 269,
- -1, -1, -1, -1, -1, -1, -1, -1,
- 270, 268, 268, 268, 268, 271, -1, -1,
- -1, 403, -1, 268, -1, -1, -1, -1,
- -1, -1, -1, 268, 268, 268, 268, 268,
- 268, 268, 268, 268, 268, 268, 268, 268,
- 268, 268, 268, 268, 73, 268, 268, 268 ),
- array( -1, -1, -1, -1, -1, 160, -1, -1,
- -1, 162, -1, 160, 160, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, 272, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, 74, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- 21, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, 287, 76, 287, 287, 287, 287, 287,
- 287, 287, 287, 287, 287, 287, 287, 287,
- 287, 287, 287, 287, 287, 287, 287, 287,
- 287, 287, 287, 287, 287, 287, 287, 287,
- 287, 287, 287, 287, 287, 287, 287, 287,
- 287, 287, 287, 287, 287, 287, 287, 287,
- 287, 287, 287, 287, 287, 287, 287, 287 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, 22,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, 290, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, 291, -1, -1, -1, -1, -1, -1,
- -1, -1, 77, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, 173, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, 173, 173, 173, 173, -1, -1, -1,
- -1, -1, -1, 173, -1, -1, -1, -1,
- -1, -1, -1, 173, 173, 173, 173, 173,
- 173, 173, 173, 173, -1, 173, 173, 173,
- 173, 173, 173, 173, -1, 173, 173, -1 ),
- array( -1, 125, 125, 125, 125, 125, 125, 125,
- 125, 125, 125, 125, 125, 125, 125, 327,
- 125, 125, 125, 125, 125, 125, 125, 125,
- 125, 125, 125, 125, 125, 125, 125, 125,
- 125, 125, 125, 125, 125, 125, 125, 125,
- 125, 125, 125, 125, 125, 125, 125, 125,
- 125, 125, 125, 125, 125, 125, 125, 125 ),
- array( -1, -1, -1, -1, -1, -1, 174, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, 174, 174, 174, 174, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, 174, 174, 174, 174, 174,
- 174, 174, 174, 174, -1, 174, 174, 174,
- 174, 174, 174, 174, -1, 174, 174, -1 ),
- array( -1, -1, -1, 175, -1, -1, 175, -1,
- -1, -1, -1, -1, -1, -1, -1, 175,
- -1, 175, 175, 175, 175, -1, -1, -1,
- -1, -1, -1, 175, -1, -1, -1, -1,
- -1, -1, -1, 175, 175, 175, 175, 175,
- 175, 175, 175, 175, 175, 175, 175, 175,
- 175, 175, 175, 175, -1, 175, 175, 175 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, 176, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, 156, -1, -1, 156, 166,
- -1, -1, 177, -1, -1, -1, -1, -1,
- 169, 156, 156, 156, 156, -1, -1, -1,
- -1, 170, -1, 156, -1, -1, -1, -1,
- -1, 18, 19, 156, 156, 156, 156, 156,
- 156, 156, 156, 156, 156, 156, 156, 156,
- 156, 156, 156, 156, -1, 156, 156, 156 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, 179, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, 173, -1, -1, 173, 166,
- -1, -1, 168, -1, -1, -1, -1, -1,
- 180, 173, 173, 173, 173, -1, -1, -1,
- -1, 181, -1, 173, -1, -1, -1, -1,
- -1, 18, 19, 173, 173, 173, 173, 173,
- 173, 173, 173, 173, 173, 173, 173, 173,
- 173, 173, 173, 173, -1, 173, 173, 173 ),
- array( -1, -1, -1, -1, -1, -1, 174, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, 174, 174, 174, 174, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, 19, 174, 174, 174, 174, 174,
- 174, 174, 174, 174, -1, 174, 174, 174,
- 174, 174, 174, 174, -1, 174, 174, -1 ),
- array( -1, -1, -1, 175, -1, -1, 175, -1,
- -1, -1, -1, -1, -1, -1, -1, 175,
- -1, 175, 175, 175, 175, -1, 182, -1,
- -1, 183, -1, 175, -1, -1, -1, -1,
- -1, -1, -1, 175, 175, 175, 175, 175,
- 175, 175, 175, 175, 175, 175, 175, 175,
- 175, 175, 175, 175, -1, 175, 175, 175 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, 169, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, 184, -1,
- -1, -1, -1, -1, -1, -1, 185, -1,
- -1, 184, 184, 184, 184, -1, -1, -1,
- -1, -1, -1, 184, -1, -1, -1, -1,
- -1, -1, -1, 184, 184, 184, 184, 184,
- 184, 184, 184, 184, -1, 184, 184, 184,
- 184, 184, 184, 184, -1, 184, 184, -1 ),
- array( -1, -1, -1, 156, -1, -1, 156, 166,
- -1, -1, 186, -1, -1, -1, -1, -1,
- 169, 156, 156, 156, 156, -1, -1, -1,
- -1, 170, -1, 156, -1, -1, -1, -1,
- -1, 18, 19, 156, 156, 156, 156, 156,
- 156, 156, 156, 156, 156, 156, 156, 156,
- 156, 156, 156, 156, -1, 156, 156, 156 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, 188, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, 189, -1, -1, 189, -1,
- -1, -1, -1, -1, -1, -1, -1, 189,
- -1, 189, 189, 189, 189, -1, -1, -1,
- -1, -1, -1, 189, -1, -1, -1, -1,
- -1, -1, -1, 189, 189, 189, 189, 189,
- 189, 189, 189, 189, 189, 189, 189, 189,
- 189, 189, 189, 189, -1, 189, 189, 189 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, 353, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, 166,
- -1, -1, 168, -1, -1, -1, -1, -1,
- 169, -1, -1, -1, -1, -1, -1, -1,
- -1, 170, -1, -1, -1, -1, -1, -1,
- -1, -1, 19, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, 190, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, 184, -1, -1, 184, 191,
- -1, -1, -1, -1, -1, -1, -1, -1,
- 192, 184, 184, 184, 184, -1, -1, -1,
- -1, 393, -1, 184, -1, -1, -1, -1,
- -1, 23, 24, 184, 184, 184, 184, 184,
- 184, 184, 184, 184, 184, 184, 184, 184,
- 184, 184, 184, 184, -1, 184, 184, 184 ),
- array( -1, -1, -1, -1, -1, -1, 184, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, 184, 184, 184, 184, -1, -1, -1,
- -1, -1, -1, 184, -1, -1, -1, -1,
- -1, -1, -1, 184, 184, 184, 184, 184,
- 184, 184, 184, 184, -1, 184, 184, 184,
- 184, 184, 184, 184, -1, 184, 184, -1 ),
- array( -1, -1, -1, -1, -1, -1, 174, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, 174, 174, 174, 174, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, 25, 174, 174, 174, 174, 174,
- 174, 174, 174, 174, -1, 174, 174, 174,
- 174, 174, 174, 174, -1, 174, 174, -1 ),
- array( -1, -1, -1, 156, -1, -1, 156, 166,
- -1, -1, 193, -1, -1, -1, -1, -1,
- 169, 156, 156, 156, 156, -1, -1, -1,
- -1, 170, -1, 156, -1, -1, -1, -1,
- -1, 18, 19, 156, 156, 156, 156, 156,
- 156, 156, 156, 156, 156, 156, 156, 156,
- 156, 156, 156, 156, -1, 156, 156, 156 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, 194, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, 189, -1, -1, 189, -1,
- -1, -1, -1, -1, -1, -1, -1, 189,
- -1, 189, 189, 189, 189, -1, 195, -1,
- -1, 196, -1, 189, -1, -1, -1, -1,
- -1, -1, -1, 189, 189, 189, 189, 189,
- 189, 189, 189, 189, 189, 189, 189, 189,
- 189, 189, 189, 189, -1, 189, 189, 189 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, 182, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, 182, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, 197, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, 197, 197, 197, 197, -1, -1, -1,
- -1, -1, -1, 197, -1, -1, -1, -1,
- -1, -1, -1, 197, 197, 197, 197, 197,
- 197, 197, 197, 197, -1, 197, 197, 197,
- 197, 197, 197, 197, -1, 197, 197, -1 ),
- array( -1, -1, -1, 198, -1, -1, 198, -1,
- -1, -1, -1, -1, -1, -1, -1, 198,
- -1, 198, 198, 198, 198, -1, -1, -1,
- -1, -1, -1, 198, -1, -1, -1, -1,
- -1, -1, -1, 198, 198, 198, 198, 198,
- 198, 198, 198, 198, 198, 198, 198, 198,
- 198, 198, 198, 198, -1, 198, 198, 198 ),
- array( -1, -1, -1, -1, -1, -1, 174, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, 174, 174, 174, 174, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, 26, 174, 174, 174, 174, 174,
- 174, 174, 174, 174, -1, 174, 174, 174,
- 174, 174, 174, 174, -1, 174, 174, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, 199, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, 166,
- -1, -1, 168, -1, -1, -1, -1, -1,
- 180, -1, -1, -1, -1, -1, -1, -1,
- -1, 181, -1, -1, -1, -1, -1, -1,
- -1, -1, 19, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, 200, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, 197, -1, -1, 197, 191,
- -1, -1, -1, -1, -1, -1, -1, -1,
- 201, 197, 197, 197, 197, -1, -1, -1,
- -1, 397, -1, 197, -1, -1, -1, -1,
- -1, 23, 24, 197, 197, 197, 197, 197,
- 197, 197, 197, 197, 197, 197, 197, 197,
- 197, 197, 197, 197, -1, 197, 197, 197 ),
- array( -1, -1, -1, 198, -1, -1, 198, -1,
- -1, -1, -1, -1, -1, -1, -1, 198,
- -1, 198, 198, 198, 198, -1, 202, -1,
- -1, 203, -1, 198, -1, -1, -1, -1,
- -1, -1, -1, 198, 198, 198, 198, 198,
- 198, 198, 198, 198, 198, 198, 198, 198,
- 198, 198, 198, 198, -1, 198, 198, 198 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- 27, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, 195, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, 195, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, 205, -1, -1, 205, -1,
- -1, -1, -1, -1, -1, -1, -1, 205,
- -1, 205, 205, 205, 205, -1, -1, -1,
- -1, -1, -1, 205, -1, -1, -1, -1,
- -1, -1, -1, 205, 205, 205, 205, 205,
- 205, 205, 205, 205, 205, 205, 205, 205,
- 205, 205, 205, 205, -1, 205, 205, 205 ),
- array( -1, -1, -1, -1, -1, -1, -1, 191,
- -1, -1, -1, -1, -1, -1, -1, -1,
- 192, -1, -1, -1, -1, -1, -1, -1,
- -1, 393, -1, -1, -1, -1, -1, -1,
- -1, 23, 24, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, 206, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, 156, -1, -1, 156, 166,
- -1, -1, 207, -1, -1, -1, -1, -1,
- 169, 156, 156, 156, 156, -1, -1, -1,
- -1, 170, -1, 156, -1, -1, -1, -1,
- -1, 18, 19, 156, 156, 156, 156, 156,
- 156, 156, 156, 156, 156, 156, 156, 156,
- 156, 156, 156, 156, -1, 156, 156, 156 ),
- array( -1, -1, -1, 205, -1, -1, 205, -1,
- -1, -1, -1, -1, -1, -1, -1, 205,
- -1, 205, 205, 205, 205, -1, 208, -1,
- -1, 209, -1, 205, -1, -1, -1, -1,
- -1, -1, -1, 205, 205, 205, 205, 205,
- 205, 205, 205, 205, 205, 205, 205, 205,
- 205, 205, 205, 205, -1, 205, 205, 205 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, 202, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, 202, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, 210, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, 210, 210, 210, 210, -1, -1, -1,
- -1, -1, -1, 210, -1, -1, -1, -1,
- -1, -1, -1, 210, 210, 210, 210, 210,
- 210, 210, 210, 210, -1, 210, 210, 210,
- 210, 210, 210, 210, -1, 210, 210, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, 191,
- -1, -1, -1, -1, -1, -1, -1, -1,
- 201, -1, -1, -1, -1, -1, -1, -1,
- -1, 397, -1, -1, -1, -1, -1, -1,
- -1, 23, 24, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, 211, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, 210, -1, -1, 210, 212,
- -1, -1, -1, -1, -1, -1, -1, -1,
- 213, 210, 210, 210, 210, -1, -1, -1,
- -1, 400, -1, 210, -1, -1, -1, -1,
- -1, -1, 28, 210, 210, 210, 210, 210,
- 210, 210, 210, 210, 210, 210, 210, 210,
- 210, 210, 210, 210, 354, 210, 210, 210 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, 208, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, 208, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, 214, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, 214, 214, 214, 214, -1, -1, -1,
- -1, -1, -1, 214, -1, -1, -1, -1,
- -1, -1, -1, 214, 214, 214, 214, 214,
- 214, 214, 214, 214, -1, 214, 214, 214,
- 214, 214, 214, 214, -1, 214, 214, -1 ),
- array( -1, -1, -1, 215, -1, -1, 215, -1,
- -1, -1, -1, -1, -1, -1, -1, 215,
- -1, 215, 215, 215, 215, -1, -1, -1,
- -1, -1, -1, 215, -1, -1, -1, -1,
- -1, -1, -1, 215, 215, 215, 215, 215,
- 215, 215, 215, 215, 215, 215, 215, 215,
- 215, 215, 215, 215, -1, 215, 215, 215 ),
- array( -1, -1, -1, 214, -1, -1, 214, 212,
- -1, -1, -1, -1, -1, -1, -1, -1,
- 217, 214, 214, 214, 214, -1, -1, -1,
- -1, 402, -1, 214, -1, -1, -1, -1,
- -1, -1, 28, 214, 214, 214, 214, 214,
- 214, 214, 214, 214, 214, 214, 214, 214,
- 214, 214, 214, 214, 354, 214, 214, 214 ),
- array( -1, -1, -1, 215, -1, -1, 215, -1,
- -1, -1, -1, -1, -1, -1, -1, 215,
- -1, 215, 215, 215, 215, -1, 218, -1,
- -1, 219, -1, 215, -1, -1, -1, -1,
- -1, -1, -1, 215, 215, 215, 215, 215,
- 215, 215, 215, 215, 215, 215, 215, 215,
- 215, 215, 215, 215, -1, 215, 215, 215 ),
- array( -1, -1, -1, 216, -1, -1, 216, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, 216, 216, 216, 216, -1, -1, -1,
- -1, -1, -1, 216, -1, -1, -1, -1,
- -1, -1, 29, 216, 216, 216, 216, 216,
- 216, 216, 216, 216, 216, 216, 216, 216,
- 216, 216, 216, 216, 220, 216, 216, 216 ),
- array( -1, -1, -1, 221, -1, -1, 221, -1,
- -1, -1, -1, -1, -1, -1, -1, 221,
- -1, 221, 221, 221, 221, -1, -1, -1,
- -1, -1, -1, 221, -1, -1, -1, -1,
- -1, -1, -1, 221, 221, 221, 221, 221,
- 221, 221, 221, 221, 221, 221, 221, 221,
- 221, 221, 221, 221, -1, 221, 221, 221 ),
- array( -1, -1, -1, -1, -1, -1, -1, 212,
- -1, -1, -1, -1, -1, -1, -1, -1,
- 213, -1, -1, -1, -1, -1, -1, -1,
- -1, 400, -1, -1, -1, -1, -1, -1,
- -1, -1, 28, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, 354, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, 222, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, 223, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, 223, 223, 223, 223, -1, -1, -1,
- -1, -1, -1, 223, -1, -1, -1, -1,
- -1, -1, -1, 223, 223, 223, 223, 223,
- 223, 223, 223, 223, -1, 223, 223, 223,
- 223, 223, 223, 223, -1, 223, 223, -1 ),
- array( -1, -1, -1, 221, -1, -1, 221, -1,
- -1, -1, -1, -1, -1, -1, -1, 221,
- -1, 221, 221, 221, 221, -1, 224, -1,
- -1, 225, -1, 221, -1, -1, -1, -1,
- -1, -1, -1, 221, 221, 221, 221, 221,
- 221, 221, 221, 221, 221, 221, 221, 221,
- 221, 221, 221, 221, -1, 221, 221, 221 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, 218, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, 218, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, 223, -1, -1, 223, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, 223, 223, 223, 223, -1, -1, -1,
- -1, -1, -1, 223, -1, -1, -1, -1,
- -1, -1, 30, 223, 223, 223, 223, 223,
- 223, 223, 223, 223, 223, 223, 223, 223,
- 223, 223, 223, 223, -1, 223, 223, 223 ),
- array( -1, -1, -1, -1, -1, -1, -1, 212,
- -1, -1, -1, -1, -1, -1, -1, -1,
- 217, -1, -1, -1, -1, -1, -1, -1,
- -1, 402, -1, -1, -1, -1, -1, -1,
- -1, -1, 28, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, 354, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, 226, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, 224, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, 224, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( 1, 31, 31, 31, 31, 31, 31, 31,
- 31, 31, 31, 31, 31, 31, 31, 31,
- 31, 31, 31, 31, 31, 31, 31, 104,
- 31, 133, 131, 31, 31, 32, 31, 31,
- 31, 31, 31, 31, 31, 31, 31, 31,
- 31, 31, 31, 31, 31, 31, 31, 31,
- 31, 31, 31, 31, 31, 31, 31, 31 ),
- array( -1, -1, -1, 229, -1, -1, 229, 232,
- -1, -1, 233, -1, -1, -1, -1, -1,
- 234, 229, 229, 229, 229, -1, -1, -1,
- -1, 235, -1, 229, -1, -1, -1, -1,
- -1, 33, 34, 229, 229, 229, 229, 229,
- 229, 229, 229, 229, 229, 229, 229, 229,
- 229, 229, 229, 229, -1, 229, 229, 229 ),
- array( -1, -1, -1, 229, -1, -1, 229, 232,
- -1, -1, 233, -1, -1, -1, -1, -1,
- 234, 229, 229, 229, 229, -1, -1, -1,
- -1, 235, -1, 229, -1, -1, -1, -1,
- -1, 145, 34, 229, 229, 229, 229, 229,
- 229, 229, 229, 229, 229, 229, 229, 229,
- 229, 229, 229, 229, -1, 229, 229, 229 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, 236, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, 237, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, 237, 237, 237, 237, -1, -1, -1,
- -1, -1, -1, 237, -1, -1, -1, -1,
- -1, -1, -1, 237, 237, 237, 237, 237,
- 237, 237, 237, 237, -1, 237, 237, 237,
- 237, 237, 237, 237, -1, 237, 237, -1 ),
- array( -1, -1, -1, -1, -1, -1, 238, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, 238, 238, 238, 238, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, 238, 238, 238, 238, 238,
- 238, 238, 238, 238, -1, 238, 238, 238,
- 238, 238, 238, 238, -1, 238, 238, -1 ),
- array( -1, -1, -1, 239, -1, -1, 239, -1,
- -1, -1, -1, -1, -1, -1, -1, 239,
- -1, 239, 239, 239, 239, -1, -1, -1,
- -1, -1, -1, 239, -1, -1, -1, -1,
- -1, -1, -1, 239, 239, 239, 239, 239,
- 239, 239, 239, 239, 239, 239, 239, 239,
- 239, 239, 239, 239, -1, 239, 239, 239 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, 373, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, 240 ),
- array( -1, -1, -1, -1, -1, -1, 229, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, 229, 229, 229, 229, -1, -1, -1,
- -1, -1, -1, 229, -1, -1, -1, -1,
- -1, -1, -1, 229, 229, 229, 229, 229,
- 229, 229, 229, 229, -1, 229, 229, 229,
- 229, 229, 229, 229, -1, 229, 229, -1 ),
- array( -1, -1, -1, 237, -1, -1, 237, 232,
- -1, -1, 233, -1, -1, -1, -1, -1,
- 241, 237, 237, 237, 237, -1, -1, -1,
- -1, 394, -1, 237, -1, -1, -1, -1,
- -1, 33, 34, 237, 237, 237, 237, 237,
- 237, 237, 237, 237, 237, 237, 237, 237,
- 237, 237, 237, 237, -1, 237, 237, 237 ),
- array( -1, -1, -1, -1, -1, -1, 238, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, 238, 238, 238, 238, -1, -1, -1,
- -1, 242, -1, -1, -1, -1, -1, -1,
- -1, -1, 34, 238, 238, 238, 238, 238,
- 238, 238, 238, 238, -1, 238, 238, 238,
- 238, 238, 238, 238, -1, 238, 238, -1 ),
- array( -1, -1, -1, 239, -1, -1, 239, -1,
- -1, -1, -1, -1, -1, -1, -1, 239,
- -1, 239, 239, 239, 239, -1, 243, -1,
- -1, 244, -1, 239, -1, -1, -1, -1,
- -1, -1, -1, 239, 239, 239, 239, 239,
- 239, 239, 239, 239, 239, 239, 239, 239,
- 239, 239, 239, 239, -1, 239, 239, 239 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, 34, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, 34, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, 245, -1, -1, 245, -1,
- -1, -1, -1, -1, -1, -1, -1, 245,
- -1, 245, 245, 245, 245, -1, -1, -1,
- -1, -1, -1, 245, -1, -1, -1, -1,
- -1, -1, -1, 245, 245, 245, 245, 245,
- 245, 245, 245, 245, 245, 245, 245, 245,
- 245, 245, 245, 245, -1, 245, 245, 245 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, 240 ),
- array( -1, -1, -1, -1, -1, -1, -1, 232,
- -1, -1, 233, -1, -1, -1, -1, -1,
- 234, -1, -1, -1, -1, -1, -1, -1,
- -1, 235, -1, -1, -1, -1, -1, -1,
- -1, -1, 34, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, 246, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, 245, -1, -1, 245, -1,
- -1, -1, -1, -1, -1, -1, -1, 245,
- -1, 245, 245, 245, 245, -1, 247, -1,
- -1, 248, -1, 245, -1, -1, -1, -1,
- -1, -1, -1, 245, 245, 245, 245, 245,
- 245, 245, 245, 245, 245, 245, 245, 245,
- 245, 245, 245, 245, -1, 245, 245, 245 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, 243, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, 243, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, 232,
- -1, -1, 233, -1, -1, -1, -1, -1,
- 241, -1, -1, -1, -1, -1, -1, -1,
- -1, 394, -1, -1, -1, -1, -1, -1,
- -1, -1, 34, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, 249, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, 247, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, 247, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( 1, 43, 43, 44, 43, -1, 348, 348,
- 106, 45, 43, 143, -1, 46, 43, 348,
- 43, 348, 348, 348, 348, 43, 43, 43,
- 43, 43, 43, 348, 43, 47, 48, 43,
- 43, 43, 43, 348, 348, 348, 348, 348,
- 348, 348, 348, 348, 44, 348, 348, 348,
- 348, 348, 348, 348, 43, 348, 348, 44 ),
- array( 1, 143, 143, 143, 143, 49, 143, 143,
- 143, 143, 143, 49, 49, 143, 143, 143,
- 143, 143, 143, 143, 143, 143, 143, 143,
- 143, 143, 143, 143, 143, 143, 143, 143,
- 143, 143, 143, 143, 143, 143, 143, 143,
- 143, 143, 143, 143, 143, 143, 143, 143,
- 143, 143, 143, 143, 143, 143, 143, 143 ),
- array( 1, 50, 50, 50, 50, -1, 50, 50,
- 50, 50, 50, 50, -1, 51, 50, 50,
- 50, 50, 50, 50, 50, 50, 50, 50,
- 50, 50, 50, 50, 50, 50, 50, 50,
- 50, 50, 50, 50, 50, 50, 50, 50,
- 50, 50, 50, 50, 50, 50, 50, 50,
- 50, 50, 50, 50, 50, 50, 50, 50 ),
- array( 1, 52, 52, 52, 52, 52, 52, 52,
- 52, 52, 52, 52, 52, 52, 52, 52,
- 52, 52, 52, 52, 52, 52, 52, 110,
- 52, 136, 153, 52, 52, 52, 53, 52,
- 52, 52, 52, 52, 52, 52, 52, 52,
- 52, 52, 52, 52, 52, 52, 52, 52,
- 52, 52, 52, 52, 52, 52, 52, 52 ),
- array( -1, -1, -1, 229, -1, -1, 229, 232,
- -1, -1, 233, -1, -1, -1, -1, -1,
- 234, 229, 229, 229, 229, -1, -1, -1,
- -1, 235, -1, 229, -1, -1, -1, -1,
- -1, 146, 34, 229, 229, 229, 229, 229,
- 229, 229, 229, 229, 229, 229, 229, 229,
- 229, 229, 229, 229, -1, 229, 229, 229 ),
- array( -1, 119, 119, 119, 119, 119, 119, 119,
- 119, 119, 119, 119, 119, 119, 119, -1,
- 119, 119, 119, 119, 119, 119, 119, 119,
- 119, 119, 119, 119, 119, 119, 119, 119,
- 119, 119, 119, 119, 119, 119, 119, 119,
- 119, 119, 119, 119, 119, 119, 119, 119,
- 119, 119, 119, 119, 119, 119, 119, 119 ),
- array( -1, 66, 66, 66, 66, 66, 66, 66,
- 66, 66, 66, 66, 66, 67, 66, 120,
- 66, 66, 66, 66, 66, 66, 66, 66,
- 66, 66, 66, 66, 66, 66, 66, 66,
- 66, 66, 66, 66, 66, 66, 66, 66,
- 66, 66, 66, 66, 66, 66, 66, 66,
- 66, 66, 66, 66, 66, 66, 66, 66 ),
- array( 1, 68, 68, 68, 68, 68, 68, 68,
- 68, 68, 68, 68, 68, 68, 68, 68,
- 68, 68, 68, 68, 68, 68, 69, 68,
- 68, 68, 68, 68, 68, 68, 68, 68,
- 68, 68, 68, 68, 68, 68, 68, 68,
- 68, 68, 68, 68, 68, 68, 68, 68,
- 68, 68, 68, 68, 68, 68, 68, 68 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, 70, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( 1, 143, 155, 157, 143, -1, 159, 143,
- 143, 143, 143, 143, -1, 143, 143, 143,
- 143, 159, 159, 159, 159, 161, 143, 143,
- 143, 143, 143, 159, 143, 143, 143, 143,
- 143, 143, 143, 159, 159, 159, 159, 159,
- 159, 159, 159, 159, 157, 159, 159, 159,
- 159, 159, 159, 159, 143, 159, 159, 157 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, 355, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, 72, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, 273, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, 273, 273, 273, 273, -1, -1, -1,
- -1, -1, -1, 273, -1, -1, -1, -1,
- -1, -1, -1, 273, 273, 273, 273, 273,
- 273, 273, 273, 273, -1, 273, 273, 273,
- 273, 273, 273, 273, -1, 273, 273, -1 ),
- array( -1, -1, -1, 274, -1, -1, 274, -1,
- -1, -1, -1, -1, -1, -1, -1, 274,
- -1, 274, 274, 274, 274, -1, -1, -1,
- -1, -1, -1, 274, -1, -1, -1, -1,
- -1, -1, -1, 274, 274, 274, 274, 274,
- 274, 274, 274, 274, 274, 274, 274, 274,
- 274, 274, 274, 274, -1, 274, 274, 274 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, 361, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, 73, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, 275, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, 275, 275, 275, 275, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, 275, 275, 275, 275, 275,
- 275, 275, 275, 275, -1, 275, 275, 275,
- 275, 275, 275, 275, -1, 275, 275, -1 ),
- array( -1, -1, -1, 273, -1, -1, 273, 269,
- -1, -1, -1, -1, -1, -1, -1, -1,
- 277, 273, 273, 273, 273, 271, -1, -1,
- -1, 404, -1, 273, -1, -1, -1, -1,
- -1, -1, -1, 273, 273, 273, 273, 273,
- 273, 273, 273, 273, 273, 273, 273, 273,
- 273, 273, 273, 273, 73, 273, 273, 273 ),
- array( -1, -1, -1, 274, -1, -1, 274, -1,
- -1, -1, -1, -1, -1, -1, -1, 274,
- -1, 274, 274, 274, 274, -1, 278, -1,
- -1, 279, -1, 274, -1, -1, -1, -1,
- -1, -1, -1, 274, 274, 274, 274, 274,
- 274, 274, 274, 274, 274, 274, 274, 274,
- 274, 274, 274, 274, -1, 274, 274, 274 ),
- array( -1, -1, -1, -1, -1, -1, 275, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, 275, 275, 275, 275, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, 74, 275, 275, 275, 275, 275,
- 275, 275, 275, 275, -1, 275, 275, 275,
- 275, 275, 275, 275, -1, 275, 275, -1 ),
- array( -1, -1, -1, -1, -1, -1, 276, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, 276, 276, 276, 276, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, 72, 276, 276, 276, 276, 276,
- 276, 276, 276, 276, -1, 276, 276, 276,
- 276, 276, 276, 276, -1, 276, 276, -1 ),
- array( -1, -1, -1, 281, -1, -1, 281, -1,
- -1, -1, -1, -1, -1, -1, -1, 281,
- -1, 281, 281, 281, 281, -1, -1, -1,
- -1, -1, -1, 281, -1, -1, -1, -1,
- -1, -1, -1, 281, 281, 281, 281, 281,
- 281, 281, 281, 281, 281, 281, 281, 281,
- 281, 281, 281, 281, -1, 281, 281, 281 ),
- array( -1, -1, -1, -1, -1, -1, -1, 269,
- -1, -1, -1, -1, -1, -1, -1, -1,
- 270, -1, -1, -1, -1, 271, -1, -1,
- -1, 403, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, 73, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, 282, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, 280, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, 280, 280, 280, 280, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, 73, 280, 280, 280, 280, 280,
- 280, 280, 280, 280, -1, 280, 280, 280,
- 280, 280, 280, 280, -1, 280, 280, -1 ),
- array( -1, -1, -1, 281, -1, -1, 281, -1,
- -1, -1, -1, -1, -1, -1, -1, 281,
- -1, 281, 281, 281, 281, -1, 283, -1,
- -1, 284, -1, 281, -1, -1, -1, -1,
- -1, -1, -1, 281, 281, 281, 281, 281,
- 281, 281, 281, 281, 281, 281, 281, 281,
- 281, 281, 281, 281, -1, 281, 281, 281 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, 278, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, 278, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, 269,
- -1, -1, -1, -1, -1, -1, -1, -1,
- 277, -1, -1, -1, -1, 271, -1, -1,
- -1, 404, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, 73, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, 285, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, 283, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, 283, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( 1, 143, 163, 143, 143, -1, 75, 143,
- 143, 143, 143, 143, -1, 143, 143, 143,
- 143, 75, 75, 75, 75, 165, 143, 143,
- 143, 143, 143, 75, 143, 143, 143, 143,
- 143, 143, 143, 75, 75, 75, 75, 75,
- 75, 75, 75, 75, 143, 75, 75, 75,
- 75, 75, 75, 75, 143, 75, 75, 143 ),
- array( -1, -1, -1, -1, -1, -1, 349, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, 349, 349, 349, 349, -1, -1, -1,
- -1, -1, -1, 349, -1, -1, -1, -1,
- -1, -1, -1, 349, 349, 349, 349, 349,
- 349, 349, 349, 349, -1, 349, 349, 349,
- 349, 349, 349, 349, -1, 349, 349, -1 ),
- array( -1, -1, -1, 292, -1, -1, 292, -1,
- -1, -1, -1, -1, -1, -1, -1, 292,
- -1, 292, 292, 292, 292, -1, -1, -1,
- -1, -1, -1, 292, -1, -1, -1, -1,
- -1, -1, -1, 292, 292, 292, 292, 292,
- 292, 292, 292, 292, 292, 292, 292, 292,
- 292, 292, 292, 292, -1, 292, 292, 292 ),
- array( -1, -1, -1, -1, -1, -1, 293, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, 293, 293, 293, 293, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, 293, 293, 293, 293, 293,
- 293, 293, 293, 293, -1, 293, 293, 293,
- 293, 293, 293, 293, -1, 293, 293, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, 294 ),
- array( -1, -1, -1, 292, -1, -1, 292, -1,
- -1, -1, -1, -1, -1, -1, -1, 292,
- -1, 292, 292, 292, 292, -1, 122, -1,
- -1, 296, -1, 292, -1, -1, -1, -1,
- -1, -1, -1, 292, 292, 292, 292, 292,
- 292, 292, 292, 292, 292, 292, 292, 292,
- 292, 292, 292, 292, -1, 292, 292, 292 ),
- array( -1, -1, -1, -1, -1, -1, 293, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, 293, 293, 293, 293, -1, -1, -1,
- -1, 291, -1, -1, -1, -1, -1, -1,
- -1, -1, 77, 293, 293, 293, 293, 293,
- 293, 293, 293, 293, -1, 293, 293, 293,
- 293, 293, 293, 293, -1, 293, 293, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, 77, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, 77, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, 297, -1, -1, 297, -1,
- -1, -1, -1, -1, -1, -1, -1, 297,
- -1, 297, 297, 297, 297, -1, -1, -1,
- -1, -1, -1, 297, -1, -1, -1, -1,
- -1, -1, -1, 297, 297, 297, 297, 297,
- 297, 297, 297, 297, 297, 297, 297, 297,
- 297, 297, 297, 297, -1, 297, 297, 297 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, 298, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, 297, -1, -1, 297, -1,
- -1, -1, -1, -1, -1, -1, -1, 297,
- -1, 297, 297, 297, 297, -1, 350, -1,
- -1, 299, -1, 297, -1, -1, -1, -1,
- -1, -1, -1, 297, 297, 297, 297, 297,
- 297, 297, 297, 297, 297, 297, 297, 297,
- 297, 297, 297, 297, -1, 297, 297, 297 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, 122, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, 122, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, 356, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( 1, 143, 143, 143, 143, -1, 143, 143,
- 143, 143, 143, 143, -1, 143, 143, 143,
- 143, 143, 143, 143, 143, 165, 143, 143,
- 143, 143, 143, 143, 143, 143, 143, 143,
- 143, 143, 143, 143, 143, 143, 143, 143,
- 143, 143, 143, 143, 143, 143, 143, 143,
- 143, 143, 143, 143, 78, 143, 143, 143 ),
- array( 1, 79, 79, 79, 79, 79, 79, 79,
- 123, 79, 79, 79, 79, 79, 79, 79,
- 79, 79, 79, 79, 79, 79, 79, 79,
- 79, 79, 79, 79, 79, 79, 79, 79,
- 79, 79, 79, 79, 79, 79, 79, 79,
- 79, 79, 79, 79, 79, 79, 79, 79,
- 79, 79, 79, 79, 79, 79, 79, 79 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, 303, 303, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, 304, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, 304, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, 305, 305,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- 306, 306, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, 307, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, 308, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, 308, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, 80, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( 1, 81, 81, 81, 81, 81, 81, 81,
- 81, 81, 81, 81, 81, 81, 81, 81,
- 81, 81, 81, 81, 81, 81, 124, 138,
- 81, 81, 81, 81, 81, 81, 81, 81,
- 81, 81, 81, 81, 81, 81, 81, 81,
- 81, 81, 81, 81, 81, 81, 81, 81,
- 81, 81, 81, 81, 81, 81, 81, 81 ),
- array( -1, -1, -1, 310, -1, -1, 310, 311,
- -1, -1, 168, -1, -1, -1, -1, -1,
- 312, 310, 310, 310, 310, -1, -1, -1,
- -1, 407, -1, 310, -1, -1, -1, -1,
- -1, -1, 19, 310, 310, 310, 310, 310,
- 310, 310, 310, 310, 310, 310, 310, 310,
- 310, 310, 310, 310, -1, 310, 310, 310 ),
- array( -1, -1, -1, -1, -1, -1, 313, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, 313, 313, 313, 313, -1, -1, -1,
- -1, -1, -1, 313, -1, -1, -1, -1,
- -1, -1, -1, 313, 313, 313, 313, 313,
- 313, 313, 313, 313, -1, 313, 313, 313,
- 313, 313, 313, 313, -1, 313, 313, -1 ),
- array( -1, -1, -1, 314, -1, -1, 314, -1,
- -1, -1, -1, -1, -1, -1, -1, 314,
- -1, 314, 314, 314, 314, -1, -1, -1,
- -1, -1, -1, 314, -1, -1, -1, -1,
- -1, -1, -1, 314, 314, 314, 314, 314,
- 314, 314, 314, 314, 314, 314, 314, 314,
- 314, 314, 314, 314, -1, 314, 314, 314 ),
- array( -1, -1, -1, 313, -1, -1, 313, 311,
- -1, -1, 168, -1, -1, -1, -1, -1,
- 316, 313, 313, 313, 313, -1, -1, -1,
- -1, 408, -1, 313, -1, -1, -1, -1,
- -1, -1, 19, 313, 313, 313, 313, 313,
- 313, 313, 313, 313, 313, 313, 313, 313,
- 313, 313, 313, 313, -1, 313, 313, 313 ),
- array( -1, -1, -1, 314, -1, -1, 314, -1,
- -1, -1, -1, -1, -1, -1, -1, 314,
- -1, 314, 314, 314, 314, -1, 317, -1,
- -1, 318, -1, 314, -1, -1, -1, -1,
- -1, -1, -1, 314, 314, 314, 314, 314,
- 314, 314, 314, 314, 314, 314, 314, 314,
- 314, 314, 314, 314, -1, 314, 314, 314 ),
- array( -1, -1, -1, 310, -1, -1, 310, 311,
- -1, -1, 186, -1, -1, -1, -1, -1,
- 312, 310, 310, 310, 310, -1, -1, -1,
- -1, 407, -1, 310, -1, -1, -1, -1,
- -1, -1, 19, 310, 310, 310, 310, 310,
- 310, 310, 310, 310, 310, 310, 310, 310,
- 310, 310, 310, 310, -1, 310, 310, 310 ),
- array( -1, -1, -1, 320, -1, -1, 320, -1,
- -1, -1, -1, -1, -1, -1, -1, 320,
- -1, 320, 320, 320, 320, -1, -1, -1,
- -1, -1, -1, 320, -1, -1, -1, -1,
- -1, -1, -1, 320, 320, 320, 320, 320,
- 320, 320, 320, 320, 320, 320, 320, 320,
- 320, 320, 320, 320, -1, 320, 320, 320 ),
- array( -1, -1, -1, -1, -1, -1, -1, 311,
- -1, -1, 168, -1, -1, -1, -1, -1,
- 312, -1, -1, -1, -1, -1, -1, -1,
- -1, 407, -1, -1, -1, -1, -1, -1,
- -1, -1, 19, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, 321, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, 310, -1, -1, 310, 311,
- -1, -1, 193, -1, -1, -1, -1, -1,
- 312, 310, 310, 310, 310, -1, -1, -1,
- -1, 407, -1, 310, -1, -1, -1, -1,
- -1, -1, 19, 310, 310, 310, 310, 310,
- 310, 310, 310, 310, 310, 310, 310, 310,
- 310, 310, 310, 310, -1, 310, 310, 310 ),
- array( -1, -1, -1, 320, -1, -1, 320, -1,
- -1, -1, -1, -1, -1, -1, -1, 320,
- -1, 320, 320, 320, 320, -1, 322, -1,
- -1, 323, -1, 320, -1, -1, -1, -1,
- -1, -1, -1, 320, 320, 320, 320, 320,
- 320, 320, 320, 320, 320, 320, 320, 320,
- 320, 320, 320, 320, -1, 320, 320, 320 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, 317, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, 317, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, 311,
- -1, -1, 168, -1, -1, -1, -1, -1,
- 316, -1, -1, -1, -1, -1, -1, -1,
- -1, 408, -1, -1, -1, -1, -1, -1,
- -1, -1, 19, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, 324, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, 322, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, 322, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, 310, -1, -1, 310, 311,
- -1, -1, 207, -1, -1, -1, -1, -1,
- 312, 310, 310, 310, 310, -1, -1, -1,
- -1, 407, -1, 310, -1, -1, -1, -1,
- -1, -1, 19, 310, 310, 310, 310, 310,
- 310, 310, 310, 310, 310, 310, 310, 310,
- 310, 310, 310, 310, -1, 310, 310, 310 ),
- array( -1, 125, 125, 125, 125, 125, 125, 125,
- 125, 125, 125, 125, 125, 125, 125, -1,
- 125, 125, 125, 125, 125, 125, 125, 125,
- 125, 125, 125, 125, 125, 125, 125, 125,
- 125, 125, 125, 125, 125, 125, 125, 125,
- 125, 125, 125, 125, 125, 125, 125, 125,
- 125, 125, 125, 125, 125, 125, 125, 125 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, 84, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, 139, 139, 139, 139, 139, 139, 139,
- 139, 139, 139, 139, 139, 86, 139, 139,
- 139, 139, 139, 139, 139, 139, 139, 139,
- 139, 139, 139, 139, 139, 139, 139, 139,
- 139, 139, 139, 139, 139, 139, 139, 139,
- 139, 139, 139, 139, 139, 139, 139, 139,
- 139, 139, 139, 139, 139, 139, 139, 139 ),
- array( -1, 89, 89, 89, 89, 89, 89, 89,
- 89, 89, 89, 89, 89, 90, 89, 129,
- 89, 89, 89, 89, 89, 89, 89, 89,
- 89, 89, 89, 89, 89, 89, 89, 89,
- 89, 89, 89, 89, 89, 89, 89, 89,
- 89, 89, 89, 89, 89, 89, 89, 89,
- 89, 89, 89, 89, 89, 89, 89, 89 ),
- array( -1, -1, -1, 330, -1, -1, 330, 332,
- -1, -1, 333, -1, -1, -1, -1, -1,
- 334, 330, 330, 330, 330, -1, -1, -1,
- -1, 409, -1, 330, -1, -1, -1, -1,
- -1, -1, 91, 330, 330, 330, 330, 330,
- 330, 330, 330, 330, 330, 330, 330, 330,
- 330, 330, 330, 330, -1, 330, 330, 330 ),
- array( -1, -1, -1, -1, -1, -1, 336, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, 336, 336, 336, 336, -1, -1, -1,
- -1, -1, -1, 336, -1, -1, -1, -1,
- -1, -1, -1, 336, 336, 336, 336, 336,
- 336, 336, 336, 336, -1, 336, 336, 336,
- 336, 336, 336, 336, -1, 336, 336, -1 ),
- array( -1, -1, -1, -1, -1, -1, 337, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, 337, 337, 337, 337, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, 337, 337, 337, 337, 337,
- 337, 337, 337, 337, -1, 337, 337, 337,
- 337, 337, 337, 337, -1, 337, 337, -1 ),
- array( -1, -1, -1, 338, -1, -1, 338, -1,
- -1, -1, -1, -1, -1, -1, -1, 338,
- -1, 338, 338, 338, 338, -1, -1, -1,
- -1, -1, -1, 338, -1, -1, -1, -1,
- -1, -1, -1, 338, 338, 338, 338, 338,
- 338, 338, 338, 338, 338, 338, 338, 338,
- 338, 338, 338, 338, -1, 338, 338, 338 ),
- array( -1, -1, -1, 336, -1, -1, 336, 332,
- -1, -1, 333, -1, -1, -1, -1, -1,
- 339, 336, 336, 336, 336, -1, -1, -1,
- -1, 410, -1, 336, -1, -1, -1, -1,
- -1, -1, 91, 336, 336, 336, 336, 336,
- 336, 336, 336, 336, 336, 336, 336, 336,
- 336, 336, 336, 336, -1, 336, 336, 336 ),
- array( -1, -1, -1, -1, -1, -1, 337, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, 337, 337, 337, 337, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, 91, 337, 337, 337, 337, 337,
- 337, 337, 337, 337, -1, 337, 337, 337,
- 337, 337, 337, 337, -1, 337, 337, -1 ),
- array( -1, -1, -1, 338, -1, -1, 338, -1,
- -1, -1, -1, -1, -1, -1, -1, 338,
- -1, 338, 338, 338, 338, -1, 340, -1,
- -1, 341, -1, 338, -1, -1, -1, -1,
- -1, -1, -1, 338, 338, 338, 338, 338,
- 338, 338, 338, 338, 338, 338, 338, 338,
- 338, 338, 338, 338, -1, 338, 338, 338 ),
- array( -1, -1, -1, 342, -1, -1, 342, -1,
- -1, -1, -1, -1, -1, -1, -1, 342,
- -1, 342, 342, 342, 342, -1, -1, -1,
- -1, -1, -1, 342, -1, -1, -1, -1,
- -1, -1, -1, 342, 342, 342, 342, 342,
- 342, 342, 342, 342, 342, 342, 342, 342,
- 342, 342, 342, 342, -1, 342, 342, 342 ),
- array( -1, -1, -1, -1, -1, -1, -1, 332,
- -1, -1, 333, -1, -1, -1, -1, -1,
- 334, -1, -1, -1, -1, -1, -1, -1,
- -1, 409, -1, -1, -1, -1, -1, -1,
- -1, -1, 91, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, 343, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, 342, -1, -1, 342, -1,
- -1, -1, -1, -1, -1, -1, -1, 342,
- -1, 342, 342, 342, 342, -1, 344, -1,
- -1, 345, -1, 342, -1, -1, -1, -1,
- -1, -1, -1, 342, 342, 342, 342, 342,
- 342, 342, 342, 342, 342, 342, 342, 342,
- 342, 342, 342, 342, -1, 342, 342, 342 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, 340, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, 340, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, 332,
- -1, -1, 333, -1, -1, -1, -1, -1,
- 339, -1, -1, -1, -1, -1, -1, -1,
- -1, 410, -1, -1, -1, -1, -1, -1,
- -1, -1, 91, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, 346, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, 344, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, 344, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, 130, 3, 3, 3, 3, 3, 3,
- 142, 3, 3, 3, 3, 3, 3, 3,
- 3, 3, 3, 3, 3, -1, 144, -1,
- 3, 3, 3, 3, 3, 3, 3, 3,
- 3, 3, 3, 3, 3, 3, 3, 3,
- 3, 3, 3, 3, 3, 3, 3, 3,
- 3, 3, 3, 3, 3, 3, 3, 3 ),
- array( -1, -1, -1, 349, -1, -1, 349, 288,
- -1, -1, -1, -1, -1, -1, -1, -1,
- 295, 349, 349, 349, 349, -1, -1, -1,
- -1, 406, -1, 349, -1, -1, -1, -1,
- -1, -1, -1, 349, 349, 349, 349, 349,
- 349, 349, 349, 349, 349, 349, 349, 349,
- 349, 349, 349, 349, -1, 349, 349, 349 ),
- array( -1, -1, -1, -1, -1, -1, -1, 288,
- -1, -1, -1, -1, -1, -1, -1, -1,
- 295, -1, -1, -1, -1, -1, -1, -1,
- -1, 406, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, 156, -1, -1, 156, 166,
- -1, -1, 168, -1, -1, -1, -1, -1,
- 169, 156, 156, 156, 156, -1, -1, -1,
- -1, 170, -1, 156, -1, -1, -1, -1,
- -1, 18, 19, 156, 156, 156, 156, 156,
- 156, 156, 156, 156, 156, 156, 156, 171,
- 156, 156, 156, 156, -1, 156, 156, 156 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, 352, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, 216, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, 216, 216, 216, 216, -1, -1, -1,
- -1, -1, -1, 216, -1, -1, -1, -1,
- -1, -1, -1, 216, 216, 216, 216, 216,
- 216, 216, 216, 216, -1, 216, 216, 216,
- 216, 216, 216, 216, -1, 216, 216, -1 ),
- array( -1, -1, -1, -1, -1, -1, 276, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, 276, 276, 276, 276, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, 276, 276, 276, 276, 276,
- 276, 276, 276, 276, -1, 276, 276, 276,
- 276, 276, 276, 276, -1, 276, 276, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, 350, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, 350, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, 310, -1, -1, 310, 311,
- -1, -1, 168, -1, -1, -1, -1, -1,
- 312, 310, 310, 310, 310, -1, -1, -1,
- -1, 407, -1, 310, -1, -1, -1, -1,
- -1, -1, 19, 310, 310, 310, 310, 310,
- 310, 310, 310, 310, 310, 310, 315, 310,
- 310, 310, 310, 310, -1, 310, 310, 310 ),
- array( -1, -1, -1, 156, -1, -1, 156, 166,
- -1, -1, 168, -1, -1, -1, -1, -1,
- 169, 156, 156, 156, 156, -1, -1, -1,
- -1, 170, -1, 156, -1, -1, -1, -1,
- -1, 18, 19, 156, 156, 156, 156, 156,
- 156, 156, 156, 156, 156, 156, 178, 156,
- 156, 156, 156, 156, -1, 156, 156, 156 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, 359, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, 280, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, 280, 280, 280, 280, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, 280, 280, 280, 280, 280,
- 280, 280, 280, 280, -1, 280, 280, 280,
- 280, 280, 280, 280, -1, 280, 280, -1 ),
- array( -1, -1, -1, 310, -1, -1, 310, 311,
- -1, -1, 168, -1, -1, -1, -1, -1,
- 312, 310, 310, 310, 310, -1, -1, -1,
- -1, 407, -1, 310, -1, -1, -1, -1,
- -1, -1, 19, 310, 310, 310, 310, 310,
- 310, 310, 310, 310, 310, 310, 310, 310,
- 310, 319, 310, 310, -1, 310, 310, 310 ),
- array( -1, -1, -1, 156, -1, -1, 156, 166,
- -1, -1, 168, -1, -1, -1, -1, -1,
- 169, 156, 156, 156, 156, -1, -1, -1,
- -1, 170, -1, 156, -1, -1, -1, -1,
- -1, 18, 19, 156, 156, 156, 156, 156,
- 156, 156, 156, 156, 156, 156, 156, 156,
- 156, 187, 156, 156, -1, 156, 156, 156 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, 364, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, 310, -1, -1, 310, 311,
- -1, -1, 168, -1, -1, -1, -1, -1,
- 312, 310, 310, 310, 310, -1, -1, -1,
- -1, 407, -1, 310, -1, -1, -1, -1,
- -1, -1, 19, 310, 310, 310, 310, 310,
- 310, 310, 310, 310, 310, 310, 310, 310,
- 310, 310, 310, 325, -1, 310, 310, 310 ),
- array( -1, -1, -1, 156, -1, -1, 156, 166,
- -1, -1, 168, -1, -1, -1, -1, -1,
- 169, 156, 156, 156, 156, -1, -1, -1,
- -1, 170, -1, 156, -1, -1, -1, -1,
- -1, 18, 19, 156, 156, 156, 156, 156,
- 156, 156, 156, 156, 156, 156, 156, 156,
- 156, 156, 156, 204, -1, 156, 156, 156 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, 368, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, 370, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, 372, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, 374, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, 376, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, 378, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, 380, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, 382, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, 384, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, 386, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, 388, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, 390, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, 156, -1, -1, 156, 166,
- -1, -1, 168, -1, -1, -1, -1, -1,
- 169, 156, 156, 156, 156, -1, -1, -1,
- -1, 170, -1, 156, -1, -1, -1, -1,
- -1, 18, 19, 156, 156, 156, 156, 156,
- 156, 156, 156, 156, 156, 156, 156, 156,
- 156, 156, 156, 156, -1, 358, 396, 156 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, 360, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, 375, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, 240 ),
- array( -1, -1, -1, 310, -1, -1, 310, 311,
- -1, -1, 168, -1, -1, -1, -1, -1,
- 312, 310, 310, 310, 310, -1, -1, -1,
- -1, 407, -1, 310, -1, -1, -1, -1,
- -1, -1, 19, 310, 310, 310, 310, 310,
- 310, 310, 310, 310, 310, 310, 310, 310,
- 310, 310, 310, 310, -1, 357, 398, 310 ),
- array( -1, -1, -1, 156, -1, -1, 156, 166,
- -1, -1, 168, -1, -1, -1, -1, -1,
- 169, 156, 156, 156, 156, -1, -1, -1,
- -1, 170, -1, 156, -1, -1, -1, -1,
- -1, 18, 19, 156, 363, 156, 156, 156,
- 156, 156, 156, 156, 156, 156, 156, 156,
- 156, 156, 156, 156, -1, 156, 156, 156 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, 365, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, 310, -1, -1, 310, 311,
- -1, -1, 168, -1, -1, -1, -1, -1,
- 312, 310, 310, 310, 310, -1, -1, -1,
- -1, 407, -1, 310, -1, -1, -1, -1,
- -1, -1, 19, 310, 362, 310, 310, 310,
- 310, 310, 310, 310, 310, 310, 310, 310,
- 310, 310, 310, 310, -1, 310, 310, 310 ),
- array( -1, -1, -1, 156, -1, -1, 156, 166,
- -1, -1, 168, -1, -1, -1, -1, -1,
- 169, 156, 156, 156, 156, -1, -1, -1,
- -1, 170, -1, 156, -1, -1, -1, -1,
- -1, 18, 19, 156, 156, 367, 156, 156,
- 156, 156, 156, 156, 156, 156, 156, 156,
- 156, 156, 156, 156, -1, 156, 156, 156 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, 369, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, 310, -1, -1, 310, 311,
- -1, -1, 168, -1, -1, -1, -1, -1,
- 312, 310, 310, 310, 310, -1, -1, -1,
- -1, 407, -1, 310, -1, -1, -1, -1,
- -1, -1, 19, 310, 310, 366, 310, 310,
- 310, 310, 310, 310, 310, 310, 310, 310,
- 310, 310, 310, 310, -1, 310, 310, 310 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, 371, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, 377, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, 379, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, 381, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, 383, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, 385, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, 387, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, 389, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, 391, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1 ),
- array( -1, -1, -1, 156, -1, -1, 156, 166,
- -1, -1, 168, -1, -1, -1, -1, -1,
- 169, 156, 156, 156, 156, -1, -1, -1,
- -1, 170, -1, 156, -1, -1, -1, -1,
- -1, 18, 19, 156, 156, 156, 156, 156,
- 156, 156, 156, 156, 156, 156, 156, 156,
- 156, 156, 399, 156, -1, 156, 156, 156 ),
- array( -1, -1, -1, 310, -1, -1, 310, 311,
- -1, -1, 168, -1, -1, -1, -1, -1,
- 312, 310, 310, 310, 310, -1, -1, -1,
- -1, 407, -1, 310, -1, -1, -1, -1,
- -1, -1, 19, 310, 310, 310, 310, 310,
- 310, 310, 310, 310, 310, 310, 310, 310,
- 310, 310, 401, 310, -1, 310, 310, 310 ),
- array( -1, -1, -1, 156, -1, -1, 156, 166,
- -1, -1, 168, -1, -1, -1, -1, -1,
- 169, 156, 156, 156, 156, -1, -1, -1,
- -1, 170, -1, 156, -1, -1, -1, -1,
- -1, 18, 19, 156, 156, 156, 156, 156,
- 156, 156, 156, 156, 156, 156, 156, 156,
- 156, 411, 156, 156, -1, 156, 156, 156 ),
- array( -1, -1, -1, 310, -1, -1, 310, 311,
- -1, -1, 168, -1, -1, -1, -1, -1,
- 312, 310, 310, 310, 310, -1, -1, -1,
- -1, 407, -1, 310, -1, -1, -1, -1,
- -1, -1, 19, 310, 310, 310, 310, 310,
- 310, 310, 310, 310, 310, 310, 310, 310,
- 310, 412, 310, 310, -1, 310, 310, 310 ),
- array( -1, -1, -1, 156, -1, -1, 156, 166,
- -1, -1, 168, -1, -1, -1, -1, -1,
- 169, 156, 156, 156, 156, -1, -1, -1,
- -1, 170, -1, 156, -1, -1, -1, -1,
- -1, 18, 19, 156, 156, 156, 413, 156,
- 156, 156, 156, 156, 156, 156, 156, 156,
- 156, 156, 156, 156, -1, 156, 156, 156 ),
- array( -1, -1, -1, 310, -1, -1, 310, 311,
- -1, -1, 168, -1, -1, -1, -1, -1,
- 312, 310, 310, 310, 310, -1, -1, -1,
- -1, 407, -1, 310, -1, -1, -1, -1,
- -1, -1, 19, 310, 310, 310, 414, 310,
- 310, 310, 310, 310, 310, 310, 310, 310,
- 310, 310, 310, 310, -1, 310, 310, 310 ),
- array( -1, -1, -1, 156, -1, -1, 156, 166,
- -1, -1, 168, -1, -1, -1, -1, -1,
- 169, 156, 156, 156, 156, -1, -1, -1,
- -1, 170, -1, 156, -1, -1, -1, -1,
- -1, 18, 19, 156, 156, 156, 156, 156,
- 156, 156, 156, 156, 156, 156, 156, 156,
- 415, 156, 156, 156, -1, 156, 156, 156 ),
- array( -1, -1, -1, 310, -1, -1, 310, 311,
- -1, -1, 168, -1, -1, -1, -1, -1,
- 312, 310, 310, 310, 310, -1, -1, -1,
- -1, 407, -1, 310, -1, -1, -1, -1,
- -1, -1, 19, 310, 310, 310, 310, 310,
- 310, 310, 310, 310, 310, 310, 310, 310,
- 416, 310, 310, 310, -1, 310, 310, 310 )
- );
-
-
- function yylex()
- {
- $yy_lookahead = '';
- $yy_anchor = YY_NO_ANCHOR;
- $yy_state = $this->yy_state_dtrans[$this->yy_lexical_state];
- $yy_next_state = YY_NO_STATE;
- $yy_last_accept_state = YY_NO_STATE;
- $yy_initial = true;
- $yy_this_accept = 0;
-
- $this->yy_mark_start();
- $yy_this_accept = $this->yy_acpt[$yy_state];
- if (YY_NOT_ACCEPT != $yy_this_accept) {
- $yy_last_accept_state = $yy_state;
- $this->yy_buffer_end = $this->yy_buffer_index;
- }
- while (true) {
- if ($yy_initial && $this->yy_at_bol) {
- $yy_lookahead = YY_BOL;
- } else {
- $yy_lookahead = $this->yy_advance();
- }
- $yy_next_state = $this->yy_nxt[$this->yy_rmap[$yy_state]][$this->yy_cmap[$yy_lookahead]];
- if (YY_EOF == $yy_lookahead && $yy_initial) {
- return false; }
- if (YY_F != $yy_next_state) {
- $yy_state = $yy_next_state;
- $yy_initial = false;
- $yy_this_accept = $this->yy_acpt[$yy_state];
- if (YY_NOT_ACCEPT != $yy_this_accept) {
- $yy_last_accept_state = $yy_state;
- $this->yy_buffer_end = $this->yy_buffer_index;
- }
- } else {
- if (YY_NO_STATE == $yy_last_accept_state) {
- $this->yy_error(1,1);
- } else {
- $yy_anchor = $this->yy_acpt[$yy_last_accept_state];
- if (0 != (YY_END & $yy_anchor)) {
- $this->yy_move_end();
- }
- $this->yy_to_mark();
- if ($yy_last_accept_state < 0) {
- if ($yy_last_accept_state < 419) {
- $this->yy_error(YY_E_INTERNAL, false);
- }
- } else {
-
- switch ($yy_last_accept_state) {
-case 2:
-{
- return $this->raiseError("unexpected something: (".$this->yytext() .") character: 0x" . dechex(ord($this->yytext())));
-}
-case 3:
-{
- //abcd -- data characters
- // { and ) added for flexy
- $this->value = $this->createToken('Text');
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 4:
-{
- // &abc;
- $this->value = $this->createToken('Text');
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 5:
-{
- //<name -- start tag */
- if ($this->options['ignore_html']) {
- return $this->returnSimple();
- }
- $this->tagName = trim(substr($this->yytext(),1));
- $this->tokenName = 'Tag';
- $this->value = '';
- $this->attributes = array();
- $this->yybegin(IN_ATTR);
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 6:
-{
- // <> -- empty start tag */
- if ($this->options['ignore_html']) {
- return $this->returnSimple();
- }
- return $this->raiseError("empty tag");
-}
-case 7:
-{
- /* <? php start.. */
- //echo "STARTING PHP?\n";
- $this->yyPhpBegin = $this->yy_buffer_start;
- $this->yybegin(IN_PHP);
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 8:
-{
- // {
- $this->value = $this->createToken('Text');
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 9:
-{
- // &#abc;
- $this->value = $this->createToken('Text');
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 10:
-{
- /* </title> -- end tag */
- if ($this->options['ignore_html']) {
- return $this->returnSimple();
- }
- if ($this->inStyle) {
- $this->inStyle = false;
- }
- $this->tagName = trim(substr($this->yytext(),1));
- $this->tokenName = 'EndTag';
- $this->yybegin(IN_ENDTAG);
- $this->value = '';
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 11:
-{
- /* </> -- empty end tag */
- if ($this->options['ignore_html']) {
- return $this->returnSimple();
- }
- return $this->raiseError("empty end tag not handled");
-}
-case 12:
-{
- /* <!DOCTYPE -- markup declaration */
- if ($this->options['ignore_html']) {
- return $this->returnSimple();
- }
- $this->value = $this->createToken('Doctype');
- $this->yybegin(IN_MD);
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 13:
-{
- /* <!> */
- if ($this->options['ignore_html']) {
- return $this->returnSimple();
- }
- return $this->raiseError("empty markup tag not handled");
-}
-case 14:
-{
- /* <![ -- marked section */
- return $this->returnSimple();
-}
-case 15:
-{
- /* eg. <?xml-stylesheet, <?php ... */
- $t = $this->yytext();
- $tagname = trim(strtoupper(substr($t,2)));
- // echo "STARTING XML? $t:$tagname\n";
- if ($tagname == 'PHP') {
- $this->yyPhpBegin = $this->yy_buffer_start;
- $this->yybegin(IN_PHP);
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
- }
- // not php - it's xlm or something...
- // we treat this like a tag???
- // we are going to have to escape it eventually...!!!
- $this->tagName = trim(substr($t,1));
- $this->tokenName = 'Tag';
- $this->value = '';
- $this->attributes = array();
- $this->yybegin(IN_ATTR);
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 16:
-{
- $this->value = $this->createToken('GetTextEnd','');
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 17:
-{
- /* ]]> -- marked section end */
- return $this->returnSimple();
-}
-case 18:
-{
- $this->value = '';
- $this->flexyMethod = substr($this->yytext(),1,-1);
- $this->flexyArgs = array();
- $this->yybegin(IN_FLEXYMETHOD);
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 19:
-{
- $t = $this->yytext();
- $t = substr($t,1,-1);
- $this->value = $this->createToken('Var' , $t);
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 20:
-{
- $this->value = $this->createToken('GetTextStart','');
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 21:
-{
- if ($this->options['ignore_html']) {
- return $this->returnSimple();
- }
- /* </name < -- unclosed end tag */
- return $this->raiseError("Unclosed end tag");
-}
-case 22:
-{
- /* <!-- -- comment declaration */
- if ($this->options['ignore_html']) {
- return $this->returnSimple();
- }
- if ($this->inStyle) {
- $this->value = $this->createToken('Comment');
- $this->yybegin(IN_COMSTYLE);
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
- }
- $this->yyCommentBegin = $this->yy_buffer_end;
- //$this->value = $this->createToken('Comment',$this->yytext(),$this->yyline);
- $this->yybegin(IN_COM);
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 23:
-{
- $this->value = '';
- $this->flexyMethod = substr($this->yytext(),1,-1);
- $this->flexyArgs = array();
- $this->yybegin(IN_FLEXYMETHOD);
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 24:
-{
- $this->value = $this->createToken('If',substr($this->yytext(),4,-1));
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 25:
-{
- $this->value = $this->createToken('End', '');
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 26:
-{
- $this->value = $this->createToken('Else', '');
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 27:
-{
- /* <![ -- marked section */
- $this->value = $this->createToken('Cdata',$this->yytext(), $this->yyline);
- $this->yybegin(IN_CDATA);
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 28:
-{
- return $this->raiseError('invalid syntax for Foreach','',true);
-}
-case 29:
-{
- $this->value = $this->createToken('Foreach', explode(',',substr($this->yytext(),9,-1)));
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 30:
-{
- $this->value = $this->createToken('Foreach', explode(',',substr($this->yytext(),9,-1)));
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 31:
-{
- $this->attrVal[] = $this->yytext();
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 32:
-{
- $this->attrVal[] = "'";
- //var_dump($this->attrVal);
- $s = "";
- foreach($this->attrVal as $v) {
- if (!is_string($v)) {
- $this->attributes[$this->attrKey] = $this->attrVal;
- $this->yybegin(IN_ATTR);
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
- }
- $s .= $v;
- }
- $this->attributes[$this->attrKey] = $s;
- $this->yybegin(IN_ATTR);
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 33:
-{
- $this->value = '';
- $n = $this->yytext();
- if ($n{0} != "{") {
- $n = substr($n,2);
- }
- $this->flexyMethod = substr($n,1,-1);
- $this->flexyArgs = array();
- $this->flexyMethodState = $this->yy_lexical_state;
- $this->yybegin(IN_FLEXYMETHODQUOTED);
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 34:
-{
- $n = $this->yytext();
- if ($n{0} != '{') {
- $n = substr($n,3);
- } else {
- $n = substr($n,1);
- }
- if ($n{strlen($n)-1} != '}') {
- $n = substr($n,0,-3);
- } else {
- $n = substr($n,0,-1);
- }
- $this->attrVal[] = $this->createToken('Var' , $n);
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 35:
-{
- $this->value = '';
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 36:
-{
- // <foo^<bar> -- unclosed start tag */
- return $this->raiseError("Unclosed tags not supported");
-}
-case 37:
-{
- $this->value = $this->createToken($this->tokenName, array($this->tagName,$this->attributes));
- if (strtoupper($this->tagName) == 'SCRIPT') {
- $this->yybegin(IN_SCRIPT);
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
- }
- if (strtoupper($this->tagName) == 'STYLE') {
- $this->inStyle = true;
- } else {
- $this->inStyle = false;
- }
- $this->yybegin(YYINITIAL);
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 38:
-{
- // <img src="xxx" ...ismap...> the ismap */
- $this->attributes[trim($this->yytext())] = true;
- $this->value = '';
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 39:
-{
- // <em^/ -- NET tag */
- $this->yybegin(IN_NETDATA);
- $this->attributes["/"] = true;
- $this->value = '';
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 40:
-{
- // <a ^href = "xxx"> -- attribute name
- $this->attrKey = substr(trim($this->yytext()),0,-1);
- $this->yybegin(IN_ATTRVAL);
- $this->value = '';
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 41:
-{
- // <em^/ -- NET tag */
- $this->attributes["/"] = true;
- $this->value = $this->createToken($this->tokenName, array($this->tagName,$this->attributes));
- $this->yybegin(YYINITIAL);
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 42:
-{
- // <em^/ -- NET tag */
- $this->attributes["?"] = true;
- $this->value = $this->createToken($this->tokenName, array($this->tagName,$this->attributes));
- $this->yybegin(YYINITIAL);
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 43:
-{
- // <a href = ^http://foo/> -- unquoted literal HACK */
- $this->attributes[$this->attrKey] = trim($this->yytext());
- $this->yybegin(IN_ATTR);
- // $this->raiseError("attribute value needs quotes");
- $this->value = '';
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 44:
-{
- // <a name = ^12pt> -- number token */
- $this->attributes[$this->attrKey] = trim($this->yytext());
- $this->yybegin(IN_ATTR);
- $this->value = '';
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 45:
-{
- // <em^/ -- NET tag */
- return $this->raiseError("attribute value missing");
-}
-case 46:
-{
- return $this->raiseError("Tag close found where attribute value expected");
-}
-case 47:
-{
- //echo "STARTING SINGLEQUOTE";
- $this->attrVal = array( "'");
- $this->yybegin(IN_SINGLEQUOTE);
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 48:
-{
- //echo "START QUOTE";
- $this->attrVal =array("\"");
- $this->yybegin(IN_DOUBLEQUOTE);
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 49:
-{
- // whitespace switch back to IN_ATTR MODE.
- $this->value = '';
- $this->yybegin(IN_ATTR);
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 50:
-{
- return $this->raiseError("extraneous character in end tag");
-}
-case 51:
-{
- $this->value = $this->createToken($this->tokenName, array($this->tagName));
- array($this->tagName);
- $this->yybegin(YYINITIAL);
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 52:
-{
- //echo "GOT DATA:".$this->yytext();
- $this->attrVal[] = $this->yytext();
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 53:
-{
- //echo "GOT END DATA:".$this->yytext();
- $this->attrVal[] = "\"";
- $s = "";
- foreach($this->attrVal as $v) {
- if (!is_string($v)) {
- $this->attributes[$this->attrKey] = $this->attrVal;
- $this->yybegin(IN_ATTR);
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
- }
- $s .= $v;
- }
- $this->attributes[$this->attrKey] = $s;
- $this->yybegin(IN_ATTR);
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 54:
-{
- $this->value = $this->createToken('WhiteSpace');
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 55:
-{
- return $this->raiseError("illegal character in markup declaration (0x".dechex(ord($this->yytext())).')');
-}
-case 56:
-{
- $this->value = $this->createToken('Number');
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 57:
-{
- $this->value = $this->createToken('Name');
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 58:
-{
- $this->value = $this->createToken('NameT');
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 59:
-{
- $this->value = $this->createToken('CloseTag');
- $this->yybegin(YYINITIAL);
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 60:
-{
- // <!doctype foo ^[ -- declaration subset */
- $this->value = $this->createToken('BeginDS');
- $this->yybegin(IN_DS);
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 61:
-{
- $this->value = $this->createToken('NumberT');
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 62:
-{
- // <!entity ^% foo system "..." ...> -- parameter entity definition */
- $this->value = $this->createToken('EntityPar');
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 63:
-{
- // <!doctype ^%foo;> -- parameter entity reference */
- $this->value = $this->createToken('EntityRef');
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 64:
-{
- $this->value = $this->createToken('Literal');
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 65:
-{
- // inside a comment (not - or not --
- // <!^--...--> -- comment */
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 66:
-{
- // inside comment -- without a >
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 67:
-{
- $this->value = $this->createToken('Comment',
- '<!--'. substr($this->yy_buffer,$this->yyCommentBegin ,$this->yy_buffer_end - $this->yyCommentBegin),
- $this->yyline,$this->yyCommentBegin
- );
- $this->yybegin(YYINITIAL);
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 68:
-{
- $this->value = $this->createToken('Declaration');
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 69:
-{
- // ] -- declaration subset close */
- $this->value = $this->createToken('DSEndSubset');
- $this->yybegin(IN_DSCOM);
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 70:
-{
- // ]]> -- marked section end */
- $this->value = $this->createToken('DSEnd');
- $this->yybegin(YYINITIAL);
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 71:
-{
- $t = $this->yytext();
- if ($t{strlen($t)-1} == ",") {
- // add argument
- $this->flexyArgs[] = substr($t,0,-1);
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
- }
- $this->flexyArgs[] = $t;
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 72:
-{
- $t = $this->yytext();
- if ($t{strlen($t)-1} == ",") {
- // add argument
- $this->flexyArgs[] = '#' . substr($t,0,-1) . '#';
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
- }
- if ($c = strpos($t,':')) {
- $this->flexyMethod .= substr($t,$c,-1);
- $t = '#' . substr($t,0,$c-1) . '#';
- } else {
- $t = '#' . substr($t,0,-2) . '#';
- }
- $this->flexyArgs[] = $t;
- $this->value = $this->createToken('Method', array($this->flexyMethod,$this->flexyArgs));
- $this->yybegin(YYINITIAL);
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 73:
-{
- $t = $this->yytext();
- if ($t{strlen($t)-1} == ",") {
- // add argument
- $this->flexyArgs[] = substr($t,0,-1);
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
- }
- if ($c = strpos($t,':')) {
- $this->flexyMethod .= substr($t,$c,-1);
- $t = substr($t,0,$c-1);
- } else {
- $t = substr($t,0,-2);
- }
- $this->flexyArgs[] = $t;
- $this->value = $this->createToken('Method' , array($this->flexyMethod,$this->flexyArgs));
- $this->yybegin(YYINITIAL);
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 74:
-{
- $t = $this->yytext();
- if ($t{1} == ':') {
- $this->flexyMethod .= substr($t,1,-1);
- }
- $this->value = $this->createToken('Method' , array($this->flexyMethod,$this->flexyArgs));
- $this->yybegin(YYINITIAL);
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 75:
-{
- $t = $this->yytext();
- // add argument
- $this->flexyArgs[] = $t;
- $this->yybegin(IN_FLEXYMETHODQUOTED_END);
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 76:
-{
- $t = $this->yytext();
- $this->flexyArgs[] =$t;
- $this->yybegin(IN_FLEXYMETHODQUOTED_END);
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 77:
-{
- $t = $this->yytext();
- if ($p = strpos($t,':')) {
- $this->flexyMethod .= substr($t,$p,-1);
- }
- $this->attrVal[] = $this->createToken('Method' , array($this->flexyMethod,$this->flexyArgs));
- $this->yybegin($this->flexyMethodState);
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 78:
-{
- $this->yybegin(IN_FLEXYMETHODQUOTED);
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 79:
-{
- // general text in script..
- $this->value = $this->createToken('Text');
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 80:
-{
- // </script>
- $this->value = $this->createToken('EndTag', array('/script'));
- $this->yybegin(YYINITIAL);
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 81:
-{
- $this->value = $this->createToken('Cdata',$this->yytext(), $this->yyline);
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 82:
-{
- /* ]]> -- marked section end */
- $this->value = $this->createToken('Cdata',$this->yytext(), $this->yyline);
- $this->yybegin(YYINITIAL);
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 83:
-{
- // inside a comment (not - or not --
- // <!^--...--> -- comment */
- $this->value = $this->createToken('DSComment');
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 84:
-{
- $this->value = $this->createToken('DSEnd');
- $this->yybegin(YYINITIAL);
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 85:
-{
- /* anything inside of php tags */
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 86:
-{
- /* php end */
- $this->value = $this->createToken('Php',
- substr($this->yy_buffer,$this->yyPhpBegin ,$this->yy_buffer_end - $this->yyPhpBegin ),
- $this->yyline,$this->yyPhpBegin);
- $this->yybegin(YYINITIAL);
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 87:
-{
- // inside a style comment (not - or not --
- // <!^--...--> -- comment */
- $this->value = $this->createToken('Comment');
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 88:
-{
- // we allow anything inside of comstyle!!!
- $this->value = $this->createToken('Comment');
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 89:
-{
- // inside style comment -- without a >
- $this->value = $this->createToken('Comment');
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 90:
-{
- // --> inside a style tag.
- $this->value = $this->createToken('Comment');
- $this->yybegin(YYINITIAL);
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 91:
-{
- // var in commented out style bit..
- $t = $this->yytext();
- $t = substr($t,1,-1);
- $this->value = $this->createToken('Var', $t);
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 93:
-{
- return $this->raiseError("unexpected something: (".$this->yytext() .") character: 0x" . dechex(ord($this->yytext())));
-}
-case 94:
-{
- //abcd -- data characters
- // { and ) added for flexy
- $this->value = $this->createToken('Text');
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 95:
-{
- // &abc;
- $this->value = $this->createToken('Text');
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 96:
-{
- //<name -- start tag */
- if ($this->options['ignore_html']) {
- return $this->returnSimple();
- }
- $this->tagName = trim(substr($this->yytext(),1));
- $this->tokenName = 'Tag';
- $this->value = '';
- $this->attributes = array();
- $this->yybegin(IN_ATTR);
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 97:
-{
- /* <? php start.. */
- //echo "STARTING PHP?\n";
- $this->yyPhpBegin = $this->yy_buffer_start;
- $this->yybegin(IN_PHP);
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 98:
-{
- // {
- $this->value = $this->createToken('Text');
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 99:
-{
- // &#abc;
- $this->value = $this->createToken('Text');
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 100:
-{
- /* </title> -- end tag */
- if ($this->options['ignore_html']) {
- return $this->returnSimple();
- }
- if ($this->inStyle) {
- $this->inStyle = false;
- }
- $this->tagName = trim(substr($this->yytext(),1));
- $this->tokenName = 'EndTag';
- $this->yybegin(IN_ENDTAG);
- $this->value = '';
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 101:
-{
- /* <!DOCTYPE -- markup declaration */
- if ($this->options['ignore_html']) {
- return $this->returnSimple();
- }
- $this->value = $this->createToken('Doctype');
- $this->yybegin(IN_MD);
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 102:
-{
- /* <![ -- marked section */
- return $this->returnSimple();
-}
-case 103:
-{
- /* eg. <?xml-stylesheet, <?php ... */
- $t = $this->yytext();
- $tagname = trim(strtoupper(substr($t,2)));
- // echo "STARTING XML? $t:$tagname\n";
- if ($tagname == 'PHP') {
- $this->yyPhpBegin = $this->yy_buffer_start;
- $this->yybegin(IN_PHP);
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
- }
- // not php - it's xlm or something...
- // we treat this like a tag???
- // we are going to have to escape it eventually...!!!
- $this->tagName = trim(substr($t,1));
- $this->tokenName = 'Tag';
- $this->value = '';
- $this->attributes = array();
- $this->yybegin(IN_ATTR);
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 104:
-{
- $this->attrVal[] = $this->yytext();
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 105:
-{
- $this->value = '';
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 106:
-{
- // <foo^<bar> -- unclosed start tag */
- return $this->raiseError("Unclosed tags not supported");
-}
-case 107:
-{
- // <img src="xxx" ...ismap...> the ismap */
- $this->attributes[trim($this->yytext())] = true;
- $this->value = '';
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 108:
-{
- // <a href = ^http://foo/> -- unquoted literal HACK */
- $this->attributes[$this->attrKey] = trim($this->yytext());
- $this->yybegin(IN_ATTR);
- // $this->raiseError("attribute value needs quotes");
- $this->value = '';
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 109:
-{
- // <a name = ^12pt> -- number token */
- $this->attributes[$this->attrKey] = trim($this->yytext());
- $this->yybegin(IN_ATTR);
- $this->value = '';
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 110:
-{
- //echo "GOT DATA:".$this->yytext();
- $this->attrVal[] = $this->yytext();
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 111:
-{
- $this->value = $this->createToken('WhiteSpace');
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 112:
-{
- return $this->raiseError("illegal character in markup declaration (0x".dechex(ord($this->yytext())).')');
-}
-case 113:
-{
- $this->value = $this->createToken('Number');
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 114:
-{
- $this->value = $this->createToken('Name');
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 115:
-{
- $this->value = $this->createToken('NameT');
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 116:
-{
- $this->value = $this->createToken('NumberT');
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 117:
-{
- // <!doctype ^%foo;> -- parameter entity reference */
- $this->value = $this->createToken('EntityRef');
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 118:
-{
- $this->value = $this->createToken('Literal');
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 119:
-{
- // inside a comment (not - or not --
- // <!^--...--> -- comment */
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 120:
-{
- // inside comment -- without a >
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 121:
-{
- $t = $this->yytext();
- if ($t{strlen($t)-1} == ",") {
- // add argument
- $this->flexyArgs[] = substr($t,0,-1);
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
- }
- $this->flexyArgs[] = $t;
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 122:
-{
- $t = $this->yytext();
- // add argument
- $this->flexyArgs[] = $t;
- $this->yybegin(IN_FLEXYMETHODQUOTED_END);
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 123:
-{
- // general text in script..
- $this->value = $this->createToken('Text');
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 124:
-{
- $this->value = $this->createToken('Cdata',$this->yytext(), $this->yyline);
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 125:
-{
- // inside a comment (not - or not --
- // <!^--...--> -- comment */
- $this->value = $this->createToken('DSComment');
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 126:
-{
- /* anything inside of php tags */
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 127:
-{
- // inside a style comment (not - or not --
- // <!^--...--> -- comment */
- $this->value = $this->createToken('Comment');
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 128:
-{
- // we allow anything inside of comstyle!!!
- $this->value = $this->createToken('Comment');
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 129:
-{
- // inside style comment -- without a >
- $this->value = $this->createToken('Comment');
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 131:
-{
- return $this->raiseError("unexpected something: (".$this->yytext() .") character: 0x" . dechex(ord($this->yytext())));
-}
-case 132:
-{
- //abcd -- data characters
- // { and ) added for flexy
- $this->value = $this->createToken('Text');
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 133:
-{
- $this->attrVal[] = $this->yytext();
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 134:
-{
- $this->value = '';
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 135:
-{
- // <a name = ^12pt> -- number token */
- $this->attributes[$this->attrKey] = trim($this->yytext());
- $this->yybegin(IN_ATTR);
- $this->value = '';
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 136:
-{
- //echo "GOT DATA:".$this->yytext();
- $this->attrVal[] = $this->yytext();
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 137:
-{
- return $this->raiseError("illegal character in markup declaration (0x".dechex(ord($this->yytext())).')');
-}
-case 138:
-{
- $this->value = $this->createToken('Cdata',$this->yytext(), $this->yyline);
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 139:
-{
- /* anything inside of php tags */
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 140:
-{
- // inside a style comment (not - or not --
- // <!^--...--> -- comment */
- $this->value = $this->createToken('Comment');
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 141:
-{
- // we allow anything inside of comstyle!!!
- $this->value = $this->createToken('Comment');
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 143:
-{
- return $this->raiseError("unexpected something: (".$this->yytext() .") character: 0x" . dechex(ord($this->yytext())));
-}
-case 144:
-{
- //abcd -- data characters
- // { and ) added for flexy
- $this->value = $this->createToken('Text');
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 145:
-{
- $this->attrVal[] = $this->yytext();
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 146:
-{
- //echo "GOT DATA:".$this->yytext();
- $this->attrVal[] = $this->yytext();
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 147:
-{
- return $this->raiseError("illegal character in markup declaration (0x".dechex(ord($this->yytext())).')');
-}
-case 148:
-{
- $this->value = $this->createToken('Cdata',$this->yytext(), $this->yyline);
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 150:
-{
- return $this->raiseError("unexpected something: (".$this->yytext() .") character: 0x" . dechex(ord($this->yytext())));
-}
-case 151:
-{
- return $this->raiseError("illegal character in markup declaration (0x".dechex(ord($this->yytext())).')');
-}
-case 153:
-{
- return $this->raiseError("unexpected something: (".$this->yytext() .") character: 0x" . dechex(ord($this->yytext())));
-}
-case 155:
-{
- return $this->raiseError("unexpected something: (".$this->yytext() .") character: 0x" . dechex(ord($this->yytext())));
-}
-case 157:
-{
- return $this->raiseError("unexpected something: (".$this->yytext() .") character: 0x" . dechex(ord($this->yytext())));
-}
-case 159:
-{
- return $this->raiseError("unexpected something: (".$this->yytext() .") character: 0x" . dechex(ord($this->yytext())));
-}
-case 161:
-{
- return $this->raiseError("unexpected something: (".$this->yytext() .") character: 0x" . dechex(ord($this->yytext())));
-}
-case 163:
-{
- return $this->raiseError("unexpected something: (".$this->yytext() .") character: 0x" . dechex(ord($this->yytext())));
-}
-case 165:
-{
- return $this->raiseError("unexpected something: (".$this->yytext() .") character: 0x" . dechex(ord($this->yytext())));
-}
-case 167:
-{
- return $this->raiseError("unexpected something: (".$this->yytext() .") character: 0x" . dechex(ord($this->yytext())));
-}
-case 347:
-{
- //abcd -- data characters
- // { and ) added for flexy
- $this->value = $this->createToken('Text');
- return HTML_TEMPLATE_FLEXY_TOKEN_OK;
-}
-case 348:
-{
- // <a name = ^12pt> -- number token */
- $this->attributes[$this->attrKey] = trim($this->yytext());
- $this->yybegin(IN_ATTR);
- $this->value = '';
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 349:
-{
- $t = $this->yytext();
- // add argument
- $this->flexyArgs[] = $t;
- $this->yybegin(IN_FLEXYMETHODQUOTED_END);
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-case 350:
-{
- $t = $this->yytext();
- // add argument
- $this->flexyArgs[] = $t;
- $this->yybegin(IN_FLEXYMETHODQUOTED_END);
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
-}
-
- }
- }
- $yy_initial = true;
- $yy_state = $this->yy_state_dtrans[$this->yy_lexical_state];
- $yy_next_state = YY_NO_STATE;
- $yy_last_accept_state = YY_NO_STATE;
- $this->yy_mark_start();
- $yy_this_accept = $this->yy_acpt[$yy_state];
- if (YY_NOT_ACCEPT != $yy_this_accept) {
- $yy_last_accept_state = $yy_state;
- $this->yy_buffer_end = $this->yy_buffer_index;
- }
- }
- }
- }
- return HTML_TEMPLATE_FLEXY_TOKEN_NONE;
- }
-}
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: nobody <nobody@localhost> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Translator.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-//
-// Controller Type Class providing translation faciliites
-//
-
-/*
-
-usage :
-
-$t = new HTML_Template_Flexy_Translator(array(
- 'baseLang' => 'en',
- 'targetLangs' => array('es','fr','zh'),
- 'appURL' => '/admin/translate.php',
-
-));
-$t->process(isset($_GET ? $_GET : array(),isset($_POST ? $_POST : array()); // read data.. etc.
-// you can replace this pretty easily with your own templates..
-$t->outputDefautTemplate();
-
-*/
-
-class HTML_Template_Flexy_Translator {
-
- /**
- * Options for Translator tool.
- *
- * @var array
- * @access public
- */
- var $options = array(
- 'baseLang' => 'en', // the language the templates are in.
- 'targetLangs' => array('fr'), // the language the templates are being translated to.
- 'templateDir' => '', // these are read from global config if not set.
- 'compileDir' => '',
- 'url_rewrite' => '', // for image rewriting.. -- needs better thinking through!
- 'appURL' => '', // url to translation too : eg. /admin/translator.php
- 'Translation2' => array(
- 'driver' => 'dataobjectsimple',
- 'options' => 'translations'
- ),
-
- );
- /**
- * app URL (copied from above)
- *
- * @var string
- * @access public
- */
- var $appURL;
- var $languages = array();
- /**
- * Array of templates and the words found in each one.
- *
- * @var array
- * @access public
- */
- var $words= array();
- /**
- * Array of objects with name, md5's, has it been set, the translation etc.
- *
- * @var array
- * @access public
- */
- var $status = array();
- /**
- * The current language
- *
- * @var array
- * @access public
- */
- var $translate = ''; // language being displayed /edited.
-
-
- /**
- * constructor
- *
- * Just set options (no checking done)
- *
- *
- * @param array see options array in file.
- * @return none
- * @access public
- */
-
- function HTML_Template_Flexy_Translator($options= array()) {
- foreach($options as $k=>$v) {
- $this->options[$k] = $v;
- }
- if (!in_array($this->options['baseLang'], $this->options['targetLangs'])) {
- $this->options['targetLangs'][] = $this->options['baseLang'];
- }
- $o = PEAR::getStaticProperty('HTML_Template_Flexy','options');
- if (!strlen($this->options['templateDir'])) {
- $this->options['templateDir'] = $o['templateDir'];
- }
- if (!strlen($this->options['compileDir'])) {
- $this->options['compileDir'] = $o['compileDir'];
- }
- if (!strlen($this->options['url_rewrite'])) {
- $this->options['url_rewrite'] = $o['url_rewrite'];
- }
- if (empty($this->options['Translation2'])) {
- $this->options['Translation2'] = $o['Translation2'];
- }
- $this->appURL = $this->options['appURL'];
- $this->languages = $this->options['targetLangs'];
- }
-
-
- /**
- * process the input
- *
- *
- * @param array $_GET; (translate = en)
- * @param array $_POST; (translate = en, en[{md5}] = translation)
-
- * @return none
- * @access public
- */
-
-
- function process($get,$post)
- {
- //DB_DataObject::debugLevel(1);
-
- $displayLang = isset($get['translate']) ? $get['translate'] :
- (isset($post['translate']) ? $post['translate'] : false);
-
- if ($displayLang === false) {
- return;
- }
- require_once 'Translation2/Admin.php';
-
- $driver = $this->options['Translation2']['driver'];
- $options = $this->options['Translation2']['options'];
- $usingGT = ($driver == 'gettext');
- $usingDO = ($driver == 'dataobjectsimple');
- $trd = &Translation2_Admin::factory($driver, $options);
-
-
-
- //$trd->setDecoratedLang('en');
- foreach($this->options['targetLangs'] as $l) {
- $trd->addLang(array(
- 'lang_id' => $l
- ));
- }
-
- // back to parent if no language selected..
-
- if (!in_array($displayLang, $this->options['targetLangs'] )) {
- require_once 'PEAR.php';
- return PEAR::raiseError('Unknown Language :' .$displayLang);
- }
-
- $this->translate = $displayLang;
-
-
- if (isset($post['_apply'])) {
- $this->clearTemplateCache($displayLang);
-
- }
- $t = explode(' ',microtime()); $start= $t[0] + $t[1];
-
- require_once 'Translation2.php';
- $tr = &Translation2::factory($driver, $options);
- $tr->setLang($displayLang);
-
- if (!$usingDO) {
- $suggestions = &Translation2::factory($driver, $options);
- $suggestions->setLang($displayLang);
- }
-
- $this->compileAll();
-
- //$tr->setPageID('test.html');
- // delete them after we have compiled them!!
- if (isset($post['_apply'])) {
- $this->clearTemplateCache($displayLang);
- }
- //DB_DataObject::debugLevel(1);
- if ($usingDO) {
- $this->loadTranslations();
- $this->loadTranslations($displayLang);
- }
-
- $all = array();
-
- if ($usingGT) {
- $trd->storage->begin();
- }
- $displayLangClean = str_replace('.', '_', $displayLang);
-
- foreach($this->words as $page=>$words) {
- $status[$page] = array();
- $tr->setPageID($page);
- // pages....
- if (isset($post['_clear']) && !PEAR::isError($p = $trd->getPage($page, $displayLang))) {
- $diff = array_diff(array_keys($p), $words);
- if (count($diff)) {
- foreach ($diff as $string) {
- $trd->remove($string, $page);
- }
- }
- }
-
- foreach ($words as $word) {
-
- if (!strlen(trim($word))) {
- continue;
- }
-
- $md5 = md5($page.':'.$word);
-
- $value = $usingDO ? $this->getTranslation($page,$word,$displayLang) : $tr->get($word);
-
- // we posted something..
- if (isset($post[$displayLangClean][$md5])) {
- // eak we shouldnt really deal with magic_quotes!!!
- $nval = str_replace("\r\n", "\n",
- get_magic_quotes_gpc() ?
- stripslashes($post[$displayLangClean][$md5]) :
- $post[$displayLangClean][$md5]);
-
- if ($value != $nval) {
- $trd->add($word,$page,array($displayLang=>$nval));
- $value = $nval;
- }
- }
-
- if ($value == '') {
- // try the old gettext...
- if (isset($old[addslashes($word)])) {
- $trd->add($word,$page,array($displayLang=>$old[addslashes($word)]));
- $value = $old[addslashes($word)];
- }
-
-
- }
-
- $add = new StdClass;
-
- $add->from = $word;
- $add->to = $value;
- if (!$add->to || ($add->from == $add->to)) {
- $add->untranslated = true;
-
- if ($usingDO) {
- $add->suggest = implode(', ', $this->getSuggestions($word, $displayLang));
- } else {
- $suggest = $suggestions->get($word);
- if ($suggest && ($suggest != $word)) {
- $add->suggest = $suggest;
- }
- }
-
-
- }
-
- $add->md5 = $md5;
- // show big or small text entry..
- $add->short = (bool) (strlen($add->from) < 30 && strstr($add->from, "\n") === false);
-
- $status[$page][] = $add;
-
-
- }
-
- }
- if ($usingGT) {
- $trd->storage->commit();
- }
- $t = explode(' ',microtime()); $total= $t[0] + $t[1] - $start;
- //printf("Built All in %0.2fs<BR>",$total);
- $this->status = $status;
-
-
-
- }
- var $translations = array();
- var $translationMap = array();
-
- /**
- * LoadTranslations - load all the translations from the database
- * into $this->translations[{lang}][{id}] = $translation;
- *
- *
- * @param string Language
- * @access public
- */
- function loadTranslations ($lang= false) {
- $d = DB_DataObject::factory('translations');
- $d->lang = ($lang == false) ? '-' : $lang;
- $d->find();
- $this->translations[$d->lang] = array();
- while ($d->fetch()) {
- $this->translations[$d->lang][$d->string_id] = $d->translation;
- if ($lang == false) {
- $this->translationMap[$d->page][$d->translation] = $d->string_id;
- }
- // suggestions:?
-
- }
- }
-
- function getSuggestions($string,$lang) {
- $ids = array();
- //echo '<PRE>';print_r($this->translationMap);
- foreach($this->translationMap as $page=>$map) {
- if (isset($map[$string])) {
- $ids[] = $map[$string];
- }
- }
- //echo '<PRE>';print_r(array($string,$lang,$ids,$this->translations[$lang]));
-
- //exit;
- if (!$ids) {
- return array();
- }
- $ret = array();
- foreach($ids as $id) {
- if (isset($this->translations[$lang][$id])) {
- $ret[] = $this->translations[$lang][$id];
- }
- }
- // echo '<PRE>';print_r($ret);
- return $ret;
- }
-
- function getTranslation($page,$word,$lang)
- {
-
- if (!isset($this->translationMap[$page][$word])) {
- //echo "No string id for $page : $word\n";
- return false;
- }
- if (!isset($this->translations[$lang][$this->translationMap[$page][$word]])) {
-
- return false;
- }
- return $this->translations[$lang][$this->translationMap[$page][$word]];
- }
- /**
- * compile all the templates in a specified folder.
- *
- *
- * @param string subdirectory of templateDir or empty
- * @return none
- * @access public
- */
-
- function compileAll($d='') {
- set_time_limit(0); // this could take quite a while!!!
-
- $words = array();
- $dname = $d ? $this->options['templateDir'] .'/'.$d : $this->options['templateDir'];
- //echo "Open $dname<BR>";
- $dh = opendir( $dname);
- require_once 'HTML/Template/Flexy.php';
- $o = $this->options;
- $o['fatalError'] = PEAR_ERROR_RETURN;
- $o['locale'] = 'en';
- while (($name = readdir($dh)) !== false) {
- $fname = $d ? $d .'/'. $name : $name;
-
- if ($name{0} == '.') {
- continue;
- }
-
- if (is_dir($this->options['templateDir'] . '/'. $fname)) {
- $this->compileAll($fname);
- continue;
- }
-
-
- if (!preg_match('/\.html$/',$name)) {
- continue;
- }
-
- $oo = $o;// $oo['debug'] = 1;
- $x = new HTML_Template_Flexy( $oo );
- $r = $x->compile($fname);
-
- //printf(" %0.3fs : $fname<BR>", $time);
- if (is_a($r,'PEAR_Error')) {
- echo "compile failed on $fname<BR>";
- echo $r->toString();
- continue;
- }
- $this->words[$fname] = file_exists($x->getTextStringsFile) ?
- unserialize(file_get_contents($x->getTextStringsFile)) :
- array();
- }
- //echo '<PRE>';print_R($words);exit;
-
- ksort($this->words);
- }
-
-
- /**
- * delete all the compiled templates in a specified language
- *
- *
- * @param string language
- * @param string subdirectory of templateDir or empty
- * @return none
- * @access public
- */
- function clearTemplateCache($lang='en',$d = '') {
-
- $dname = $d ? $this->options['templateDir'] .'/'.$d : $this->options['templateDir'];
-
- $dh = opendir($dname);
- while (($name = readdir($dh)) !== false) {
- $fname = $d ? $d .'/'. $name : $name;
-
- if ($name{0} == '.') {
- continue;
- }
-
- if (is_dir($this->options['templateDir'] . '/'. $fname)) {
- $this->clearTemplateCache($lang,$fname);
- continue;
- }
- if (!preg_match('/\.html$/',$name)) {
- continue;
- }
-
- $file = "{$this->options['compileDir']}/{$fname}.{$lang}.php";
-
- if (file_exists($file)) {
- // echo "DELETE $file?";
- unlink($file);
- }
- }
- clearstatcache();
- }
- /**
- * output the default template with the editing facilities.
- *
- * @return none
- * @access public
- */
- function outputDefaultTemplate() {
- $o = array(
- 'compileDir' => ini_get('session.save_path') . '/HTML_Template_Flexy_Translate',
- 'templateDir' => dirname(__FILE__).'/templates'
- );
- $x = new HTML_Template_Flexy( $o );
- $x->compile('translator.html');
- $x->outputObject($this);
- }
-
-
-
-}
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Alan Knowles <alan@akbkhome.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Tree.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-//
-// The Html Tree Component of Flexy
-// Designed to be used on it's own
-//
-//
-//
-// The concept:
-// - it builds a big tokens[] array :
-// - filters "Text with {placeholders}" into sprintf formated strings.
-// - matches closers to openers eg. token[4]->close = &token[5];
-// - it aliases the tokens into token[0] as children as a tree
-// - locates the base of the file. (flexy:startchildren.
-// returns a nice tree..
-
-
-class HTML_Template_Flexy_Tree {
-
- /**
- * Options for Tree:
- * 'ignore' => dont change {xxxX} into placeholders?
- * 'filename' => filename of file being parsed. (for error messages.)
- * 'ignore_html' => return <html> elements as strings.
- * 'ignore_php' => DELETE/DESTROY any php code in the original template.
- */
-
- var $options = array(
- 'ignore' => false, // was flexyIgnore
- 'filename' => false,
- 'ignore_html' => false,
- 'ignore_php' => true,
- );
-
-
- /**
- * Array of all tokens (eg. nodes / text / tags etc. )
- * All nodes have ID's
- *
- * eg.
- * <b>some text</b>
- * [0] => Token_Tag::
- * tagname = '<b>'
- * children = array( &tag[1] );
- close = &tag[2];
- * [1] => Token_Text::'some test'
- * [2] => Token_Tag::
- * tagname = '</b>';
- *
- *
- * under normal situations, the tree is built into node[0], the remaining nodes are referenced by alias.
- * if caching is used (the nodes > 0 will not exist, and everything will just be a child of node 0.
- *
- *
- *
- * @var array
- * @access public
- */
-
- var $tokens = array();
- var $strings = array();
-
-
-
-
-
-
- /**
- * Run a Tokenizer and Store its results and return the tree.
- * It should build a DOM Tree of the HTML
- *
- * @param string $data data to parse.
- * @param array $options see options array.
- *
- * @access public
- * @return base token (really a dummy token, which contains the tree)
- * @static
- */
-
- function construct($data,$options=array())
- {
-
- // local caching!
- $md5 = md5($data);
- if (isset($GLOBALS[__CLASS__]['cache'][$md5])) {
- return $GLOBALS[__CLASS__]['cache'][$md5];
- }
-
- $t = new HTML_Template_Flexy_Tree;
- $t->options = $t->options + $options;
- require_once 'HTML/Template/Flexy/Token.php';
- $t->tokens = array(new HTML_Template_Flexy_Token);
- $t->tokens[0]->id =0;
-
- // process
- if (is_a($r = $t->tokenize($data),'PEAR_Error')) {
- return $r;
- }
-
- $t->matchClosers();
- $t->buildChildren(0);
- //new Gtk_VarDump($_HTML_TEMPLATE_FLEXY_TOKEN['tokens'][0]);
-
- $GLOBALS[__CLASS__]['cache'][$md5] = $t->returnStart();
- return $GLOBALS[__CLASS__]['cache'][$md5];
-
- }
-
- /**
- * The core tokenizing part - runs the tokenizer on the data,
- * and stores the results in $this->tokens[]
- *
- * @param string Data to tokenize
- *
- * @return none | PEAR::Error
- * @access public|private
- * @see see also methods.....
- */
-
-
- function tokenize($data) {
- require_once 'HTML/Template/Flexy/Tokenizer.php';
- $tokenizer = &HTML_Template_Flexy_Tokenizer::construct($data,$this->options);
-
- // initialize state - this trys to make sure that
- // you dont do to many elses etc.
-
- //echo "RUNNING TOKENIZER";
- // step one just tokenize it.
- $i=1;
- while ($t = $tokenizer->yylex()) {
-
- if ($t == HTML_TEMPLATE_FLEXY_TOKEN_ERROR) {
- return HTML_Template_Flexy::raiseError(
- array(
- "HTML_Template_Flexy_Tree::Syntax error in File: %s (Line %s)\n".
- "Tokenizer Error: %s\n".
- "Context:\n\n%s\n\n >>>>>> %s\n",
- $this->options['filename'], $tokenizer->yyline ,
- $tokenizer->error,
- htmlspecialchars(substr($tokenizer->yy_buffer,0,$tokenizer->yy_buffer_end)),
- htmlspecialchars(substr($tokenizer->yy_buffer,$tokenizer->yy_buffer_end,100))
- )
- ,HTML_TEMPLATE_FLEXY_ERROR_SYNTAX ,HTML_TEMPLATE_FLEXY_ERROR_DIE);
- }
-
- if ($t == HTML_TEMPLATE_FLEXY_TOKEN_NONE) {
- continue;
- }
- if ($t->token == 'Php') {
- continue;
- }
- $i++;
- $this->tokens[$i] = $tokenizer->value;
- $this->tokens[$i]->id = $i;
-
-
-
- //print_r($_HTML_TEMPLATE_FLEXY_TOKEN['tokens'][$i]);
-
- }
- //echo "BUILT TOKENS";
- }
-
-
-
-
- /**
- * Match the opening and closing tags eg. </B> is the closer of <B>
- *
- * aliases the ->close to the tokens[{closeid}] element
- *
- * @return none
- * @access public
- */
-
- function matchClosers()
- {
- $res = &$this->tokens;
- $total = count($this->tokens);
- // connect open and close tags.
-
- // this is done by having a stack for each of the tag types..
- // then removing it when it finds the closing one
- // eg.
- // <a href=""><img src=""></a>
- // ends up with a stack for <a>'s and a stack for <img>'s
- //
- //
- //
-
-
- for($i=1;$i<$total;$i++) {
- //echo "Checking TAG $i\n";
- if (!isset($res[$i]->tag)) {
- continue;
- }
- $tag = strtoupper($res[$i]->tag);
- if ($tag{0} != '/') { // it's not a close tag..
-
-
- if (!isset($stack[$tag])) {
- $npos = $stack[$tag]['pos'] = 0;
- } else {
- $npos = ++$stack[$tag]['pos'];
- }
- $stack[$tag][$npos] = $i;
- continue;
- }
-
- //echo "GOT END TAG: {$res[$i]->tag}\n";
- $tag = substr($tag,1);
- if (!isset($stack[$tag]['pos'])) {
- continue; // unmatched
- }
-
- $npos = $stack[$tag]['pos'];
- if (!isset($stack[$tag][$npos])) {
- // stack is empty!!!
- continue;
- }
- // alias closer to opener..
- $this->tokens[$stack[$tag][$npos]]->close = &$this->tokens[$i];
- $stack[$tag]['pos']--;
- // take it off the stack so no one else uses it!!!
- unset($stack[$tag][$npos]);
- if ($stack[$tag]['pos'] < 0) {
- // too many closes - just ignore it..
- $stack[$tag]['pos'] = 0;
- }
- continue;
-
- // new entry on stack..
-
-
-
- }
-
- // create a dummy close for the end
- $i = $total;
- $this->tokens[$i] = new HTML_Template_Flexy_Token;
- $this->tokens[$i]->id = $total;
- $this->tokens[0]->close = &$this->tokens[$i];
-
- // now is it possible to connect children...
- // now we need to GLOBALIZE!! -
-
- }
-
- /**
- * Build the child array for each element.
- * RECURSIVE FUNCTION!!!!
- *
- * does not move tokens, just aliases the child nodes into the token array.
- *
- * @param int id of node to add children to.
- *
- * @access public
- */
- function buildChildren($id)
- {
-
-
- $base = &$this->tokens[$id];
- $base->children = array();
- $start = $base->id +1;
- $end = $base->close->id;
-
- for ($i=$start; $i<$end; $i++) {
- //echo "{$base->id}:{$base->tag} ADDING {$i}{$_HTML_TEMPLATE_FLEXY_TOKEN['tokens'][$i]->tag}<BR>";
- //if ($base->id == 1176) {
- // echo "<PRE>";print_r($_HTML_TEMPLATE_FLEXY_TOKEN['tokens'][$i]);
- // }
- $base->children[] = &$this->tokens[$i];
- if (isset($this->tokens[$i]->close)) {
-
- // if the close id is greater than my id - ignore it! -
- if ($this->tokens[$i]->close->id > $end) {
- continue;
- }
- $this->buildChildren($i);
- $i = $this->tokens[$i]->close->id;
- }
- }
- }
-
-
- /**
- * Locates Flexy:startchildren etc. if it is used.
- * and returns the base of the tree. (eg. otherwise token[0].
- *
- * @return HTML_Template_Flexy_Token (base of tree.)
- * @access public
- */
-
- function returnStart() {
-
- foreach(array_keys($this->tokens) as $i) {
- switch(true) {
- case isset($this->tokens[$i]->ucAttributes['FLEXYSTART']):
- case isset($this->tokens[$i]->ucAttributes['FLEXY:START']):
- $this->tokens[$i]->removeAttribute('FLEXY:START');
- $this->tokens[$i]->removeAttribute('FLEXYSTART');
- return $this->tokens[$i];
- case isset($this->tokens[$i]->ucAttributes['FLEXYSTARTCHILDREN']):
- case isset($this->tokens[$i]->ucAttributes['FLEXY:STARTCHILDREN']):
- $this->tokens[0]->children = $this->tokens[$i]->children;
- return $this->tokens[0];
- }
- }
- return $this->tokens[0];
-
-
- }
-
-}
\ No newline at end of file
+++ /dev/null
-#!/usr/bin/php -q
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Alan Knowles <alan@akbkhome.com>
-// +----------------------------------------------------------------------+
-//
-// $Id: compileAll.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-//
-
-@include 'HTML/Template/Flexy.php';
-if (!class_exists('HTML_Template_Flexy')) {
- ini_set('include_path',dirname(__FILE__).'/../../../');
- include 'HTML/Template/Flexy.php';
-}
-require_once 'PEAR.php';
-
-if (!ini_get('register_argc_argv')) {
- PEAR::raiseError("\nERROR: You must turn register_argc_argv On in you php.ini file for this to work\neg.\n\nregister_argc_argv = On\n\n", null, PEAR_ERROR_DIE);
- exit;
-}
-
-if (!@$_SERVER['argv'][1]) {
- PEAR::raiseError("\nERROR: compileAll.php usage:\n\nC:\php\pear\HTML\Template\Flexy\compileAll.php example.ini\n\n", null, PEAR_ERROR_DIE);
- exit;
-}
-
-$config = parse_ini_file($_SERVER['argv'][1], true);
-
-$options = &PEAR::getStaticProperty('HTML_Template_Flexy','options');
-$options = $config['HTML_Template_Flexy'];
-
-if (!$options) {
- PEAR::raiseError("\nERROR: could not read ini file\n\n", null, PEAR_ERROR_DIE);
- exit;
-}
-
-set_time_limit(0);
-//DB_DataObject::debugLevel(5);
-$flexy= new HTML_Template_Flexy;
-$flexy->compileAll();
-?>
+++ /dev/null
-;
-; To use config file with HTML_Template_Flexy
-; $config = parse_ini_file('example.ini',TRUE)
-; $options = &PEAR::getStaticProperty('HTML_Template_Flexy','options');
-; $options = $config['HTML_Template_Flexy'];
-;
-[HTML_Template_Flexy]
-
-compileDir = /home/me/Projects/myapplication/compiled_templates
- ; where the compiled templates go.
-
-templateDir = /home/me/Projects/myapplication/templates
- ; where the original templates are.
-
-;templateDir = /home/me/Projects/myapplication/english;/home/me/Projects/myapplication/spanish
- ; or use multiple paths..
-
-forceCompile = 0
- ; force compile template every time...
-
-filters = Php,SimpleTags,BodyOnly
- ; Order of Classes to use as filters.
-
-
-;url_rewrite = "/images/:/php_sharpsite/images/"
- ; rewrite src and href urls from /images/ to /php_sharpsite/images/
-
-;url_rewrite = "/abc/:/xyz/,/bbb/:/zzz/"
- ; rewrite src and href urls from /abc/ to /xyz/ and /bbb/ to /zzz/
- ; not it is only on the left of the url (not anywhere inside it)
-
-
-;flexyIgnore = 0
- ; this turns of the transformation of HTML form elements into
- ; HTML_Template_Flexy_Element's, either globally, or you
- ; can use it in a constructor to turn it off per template.
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head>
-
-
-
-
- <link type="text/css" rel="stylesheet" href="css/arms.css">
- <title>register2</title>
-</head><body flexy:startchildren="yes">
-
-
-<script type="text/javascript">
-
-
-function xbDetectBrowser()
-{
- var oldOnError = window.onerror;
- var element = null;
-
- window.onerror = null;
-
- // work around bug in xpcdom Mozilla 0.9.1
- window.saveNavigator = window.navigator;
-
- navigator.OS = '';
- navigator.version = parseFloat(navigator.appVersion);
- navigator.org = '';
- navigator.family = '';
-
- var platform;
- if (typeof(window.navigator.platform) != 'undefined') {
- platform = window.navigator.platform.toLowerCase();
- if (platform.indexOf('win') != -1) {
- navigator.OS = 'win';
- } else if (platform.indexOf('mac') != -1) {
- navigator.OS = 'mac';
- } else if (platform.indexOf('unix') != -1 || platform.indexOf('linux') != -1 || platform.indexOf('sun') != -1) {
- navigator.OS = 'nix';
- }
- }
-
- var i = 0;
- var ua = window.navigator.userAgent.toLowerCase();
- if (ua.indexOf('opera') != -1) {
- i = ua.indexOf('opera');
- navigator.family = 'opera';
- navigator.org = 'opera';
- navigator.version = parseFloat('0' + ua.substr(i+6), 10);
- } else if ((i = ua.indexOf('msie')) != -1) {
- navigator.org = 'microsoft';
- navigator.version = parseFloat('0' + ua.substr(i+5), 10);
-
- if (navigator.version < 4) {
- navigator.family = 'ie3';
- } else {
- navigator.family = 'ie4'
- }
- } else if (ua.indexOf('gecko') != -1) {
- navigator.family = 'gecko';
- var rvStart = navigator.userAgent.indexOf('rv:') + 3;
- var rvEnd = navigator.userAgent.indexOf(')', rvStart);
- var rv = navigator.userAgent.substring(rvStart, rvEnd);
- var decIndex = rv.indexOf('.');
- if (decIndex != -1) {
- rv = rv.replace(/\./g, '')
- rv = rv.substring(0, decIndex-1) + '.' + rv.substr(decIndex)
- }
- navigator.version = parseFloat(rv);
-
- if (ua.indexOf('netscape') != -1) {
- navigator.org = 'netscape';
- } else if (ua.indexOf('compuserve') != -1) {
- navigator.org = 'compuserve';
- } else {
- navigator.org = 'mozilla';
- }
- } else if ((ua.indexOf('mozilla') !=-1) &&
- (ua.indexOf('spoofer')==-1) &&
- (ua.indexOf('compatible') == -1) &&
- (ua.indexOf('opera')==-1) &&
- (ua.indexOf('webtv')==-1) &&
- (ua.indexOf('hotjava')==-1)) {
- var is_major = parseFloat(navigator.appVersion);
-
- if (is_major < 4) {
- navigator.version = is_major;
- } else {
- i = ua.lastIndexOf('/')
- navigator.version = parseFloat('0' + ua.substr(i+1), 10);
- }
- navigator.org = 'netscape';
- navigator.family = 'nn' + parseInt(navigator.appVersion);
- } else if ((i = ua.indexOf('aol')) != -1 ) {
- // aol
- navigator.family = 'aol';
- navigator.org = 'aol';
- navigator.version = parseFloat('0' + ua.substr(i+4), 10);
- } else if ((i = ua.indexOf('hotjava')) != -1 ) {
- // hotjava
- navigator.family = 'hotjava';
- navigator.org = 'sun';
- navigator.version = parseFloat(navigator.appVersion);
- }
-
- window.onerror = oldOnError;
-}
-
-xbDetectBrowser();
-
-
-
-
-
-
-
-
-
-
-
-function getTableNodeName(Node){
- return "pane" + Node;
-}
-
-
-function showNode(Node){
-
- switch(navigator.family){
- case 'nn4':
- // Nav 4.x code fork...
- var oTable = document.layers[getTableNodeName(Node)];
- break;
-
- case 'ie4':
- // IE 4/5 code fork...
- var oTable = document.all[getTableNodeName(Node)];
- break;
-
- case 'gecko':
- // Standards Compliant code fork...
- var oTable = document.getElementById(getTableNodeName(Node));
- break;
-
- }
- oTable.style.display = "block";
-}
-
-function hideNode(Node){
- switch(navigator.family){
- case 'nn4':
- // Nav 4.x code fork...
- var oTable = document.layers[getTableNodeName(Node)];
- break;
-
- case 'ie4':
- // IE 4/5 code fork...
- var oTable = document.all[getTableNodeName(Node)];
- break;
-
- case 'gecko':
- // Standards Compliant code fork...
- var oTable = document.getElementById(getTableNodeName(Node));
- break;
-
- }
- oTable.style.display = "none";
-}
-function toggleNodeVisibility(Node){
- if (nodeIsVisible(Node)){
- hideNode(Node);
- }else{
- showNode(Node);
- }
-}
-function nodeIsVisible(Node){
- switch(navigator.family){
- case 'nn4':
- // Nav 4.x code fork...
- var oTable = document.layers[getTableNodeName(Node)];
- break;
-
- case 'ie4':
- // IE 4/5 code fork...
- var oTable = document.all[getTableNodeName(Node)];
- break;
-
- case 'gecko':
- // Standards Compliant code fork...
- var oTable = document.getElementById(getTableNodeName(Node));
- break;
-
- }
- return (oTable && oTable.style.display == "block");
-}
-
-</script>
-
-
-
-Select a Language To Translate To : {foreach:languages,lang}
- <a href="{appURL}?translate={lang}">{lang}</a>
- {end:}
-
-
-
-
-
-
-
-
-<form method="post" flexy:ignoreonly="yes" action="{appURL}" flexy:if="translate">
-<input name="translate" value="{translate}" type="hidden" flexy:ignoreonly="yes">
-
-<h1>Language : {translate}
- <input flexy:ignoreonly="yes" value="save" name="_submit" type="submit">
- or
- <input flexy:ignoreonly="yes" value="Save And Make Live" name="_apply" type="submit">
- or
- <input flexy:ignoreonly="yes" value="Save And Clear Un-used Translations" name="_clear" type="submit">
-</h1>
-
-
-{foreach:status,page,items}
-
-<table border="0" cellspacing="2" cellpadding="2" width="600" align="center">
- <tbody>
- <tr>
- <td bgcolor="#cccccc" colspan="2" rowspan="1" valign="top" width="600">
- <a class="property" href="javascript:toggleNodeVisibility('{page}');">+
- Page:<b>{page} (in {translate})</b></a><br>
- </td>
- </tr>
-</table>
-
-<span id="pane{page}" style="display: none;">
- <table width="100%" border="0" cellspacing="2" cellpadding="2" width="600" align="center">
-
- <tr flexy:foreach="items,item">
-
- <td bgcolor="#eeeeee" vaslign="top" width="300">
- <a name="{item.md5}">
- {if:item.untranslated}
- <font color="#ff0000">{item.from}</font>
- {else:}{item.from}
- {end:}
- <br>
- <i>{item.suggest}</i><br>
- </a>
- </td>
- <td bgcolor="#ffffff" valign="top" width="300">
- <a href="#%7Bitem.md5%7D" flexy:if="item.already">See here</a>
- <span flexy:if="!item.already">
- <span flexy:if="item.short"><input
- flexy:ignoreonly="yes" value="{item.to}" name="{translate}[{item.md5}]" size="40"></span>
- <textarea cols="40" rows="5" flexy:if="!item.short" flexy:ignore="yes" name="{translate}[{item.md5}]" size="40">{item.to}</textarea>
- </span>
- </td>
- </tr>
- </table>
-</span>
-{end:}
-<br>
-
-<br>
-<!-- InstanceEndEditable --><br>
- </form>
-
-
-
-
-
-</body></html>
\ No newline at end of file
+++ /dev/null
-<?php
-//
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2005 Ulf Wendel, Pierre-Alain Joye |
-// +----------------------------------------------------------------------+
-// | This source file is subject to the New BSD license, That is bundled |
-// | with this package in the file LICENSE, and is available through |
-// | the world-wide-web at |
-// | http://www.opensource.org/licenses/bsd-license.php |
-// | If you did not receive a copy of the new BSDlicense and are unable |
-// | to obtain it through the world-wide-web, please send a note to |
-// | pajoye@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Ulf Wendel <ulf.wendel@phpdoc.de> |
-// | Pierre-Alain Joye <pajoye@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: IT.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-//
-
-require_once 'PEAR.php';
-
-define('IT_OK', 1);
-define('IT_ERROR', -1);
-define('IT_TPL_NOT_FOUND', -2);
-define('IT_BLOCK_NOT_FOUND', -3);
-define('IT_BLOCK_DUPLICATE', -4);
-define('IT_UNKNOWN_OPTION', -6);
-/**
- * Integrated Template - IT
- *
- * Well there's not much to say about it. I needed a template class that
- * supports a single template file with multiple (nested) blocks inside and
- * a simple block API.
- *
- * The Isotemplate API is somewhat tricky for a beginner although it is the best
- * one you can build. template::parse() [phplib template = Isotemplate] requests
- * you to name a source and a target where the current block gets parsed into.
- * Source and target can be block names or even handler names. This API gives you
- * a maximum of fexibility but you always have to know what you do which is
- * quite unusual for php skripter like me.
- *
- * I noticed that I do not any control on which block gets parsed into which one.
- * If all blocks are within one file, the script knows how they are nested and in
- * which way you have to parse them. IT knows that inner1 is a child of block2, there's
- * no need to tell him about this.
- *
- * <table border>
- * <tr>
- * <td colspan=2>
- * __global__
- * <p>
- * (hidden and automatically added)
- * </td>
- * </tr>
- * <tr>
- * <td>block1</td>
- * <td>
- * <table border>
- * <tr>
- * <td colspan=2>block2</td>
- * </tr>
- * <tr>
- * <td>inner1</td>
- * <td>inner2</td>
- * </tr>
- * </table>
- * </td>
- * </tr>
- * </table>
- *
- * To add content to block1 you simply type:
- * <code>$tpl->setCurrentBlock("block1");</code>
- * and repeat this as often as needed:
- * <code>
- * $tpl->setVariable(...);
- * $tpl->parseCurrentBlock();
- * </code>
- *
- * To add content to block2 you would type something like:
- * <code>
- * $tpl->setCurrentBlock("inner1");
- * $tpl->setVariable(...);
- * $tpl->parseCurrentBlock();
- *
- * $tpl->setVariable(...);
- * $tpl->parseCurrentBlock();
- *
- * $tpl->parse("block1");
- * </code>
- *
- * This will result in one repition of block1 which contains two repitions
- * of inner1. inner2 will be removed if $removeEmptyBlock is set to true which is the default.
- *
- * Usage:
- * <code>
- * $tpl = new HTML_Template_IT( [string filerootdir] );
- *
- * // load a template or set it with setTemplate()
- * $tpl->loadTemplatefile( string filename [, boolean removeUnknownVariables, boolean removeEmptyBlocks] )
- *
- * // set "global" Variables meaning variables not beeing within a (inner) block
- * $tpl->setVariable( string variablename, mixed value );
- *
- * // like with the Isotemplates there's a second way to use setVariable()
- * $tpl->setVariable( array ( string varname => mixed value ) );
- *
- * // Let's use any block, even a deeply nested one
- * $tpl->setCurrentBlock( string blockname );
- *
- * // repeat this as often as you need it.
- * $tpl->setVariable( array ( string varname => mixed value ) );
- * $tpl->parseCurrentBlock();
- *
- * // get the parsed template or print it: $tpl->show()
- * $tpl->get();
- * </code>
- *
- * @author Ulf Wendel <uw@netuse.de>
- * @version $Id: IT.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @access public
- * @package HTML_Template_IT
- */
-class HTML_Template_IT
-{
- /**
- * Contains the error objects
- * @var array
- * @access public
- * @see halt(), $printError, $haltOnError
- */
- var $err = array();
-
- /**
- * Clear cache on get()?
- * @var boolean
- */
- var $clearCache = false;
-
- /**
- * First character of a variable placeholder ( _{_VARIABLE} ).
- * @var string
- * @access public
- * @see $closingDelimiter, $blocknameRegExp, $variablenameRegExp
- */
- var $openingDelimiter = '{';
-
- /**
- * Last character of a variable placeholder ( {VARIABLE_}_ ).
- * @var string
- * @access public
- * @see $openingDelimiter, $blocknameRegExp, $variablenameRegExp
- */
- var $closingDelimiter = '}';
-
- /**
- * RegExp matching a block in the template.
- * Per default "sm" is used as the regexp modifier, "i" is missing.
- * That means a case sensitive search is done.
- * @var string
- * @access public
- * @see $variablenameRegExp, $openingDelimiter, $closingDelimiter
- */
- var $blocknameRegExp = '[\.0-9A-Za-z_-]+';
-
- /**
- * RegExp matching a variable placeholder in the template.
- * Per default "sm" is used as the regexp modifier, "i" is missing.
- * That means a case sensitive search is done.
- * @var string
- * @access public
- * @see $blocknameRegExp, $openingDelimiter, $closingDelimiter
- */
- var $variablenameRegExp = '[\.0-9A-Za-z_-]+';
-
- /**
- * RegExp used to find variable placeholder, filled by the constructor.
- * @var string Looks somewhat like @(delimiter varname delimiter)@
- * @access public
- * @see IntegratedTemplate()
- */
- var $variablesRegExp = '';
-
- /**
- * RegExp used to strip unused variable placeholder.
- * @brother $variablesRegExp
- */
- var $removeVariablesRegExp = '';
-
- /**
- * Controls the handling of unknown variables, default is remove.
- * @var boolean
- * @access public
- */
- var $removeUnknownVariables = true;
-
- /**
- * Controls the handling of empty blocks, default is remove.
- * @var boolean
- * @access public
- */
- var $removeEmptyBlocks = true;
-
- /**
- * RegExp used to find blocks an their content, filled by the constructor.
- * @var string
- * @see IntegratedTemplate()
- */
- var $blockRegExp = '';
-
- /**
- * Name of the current block.
- * @var string
- */
- var $currentBlock = '__global__';
-
- /**
- * Content of the template.
- * @var string
- */
- var $template = '';
-
- /**
- * Array of all blocks and their content.
- *
- * @var array
- * @see findBlocks()
- */
- var $blocklist = array();
-
- /**
- * Array with the parsed content of a block.
- *
- * @var array
- */
- var $blockdata = array();
-
- /**
- * Array of variables in a block.
- * @var array
- */
- var $blockvariables = array();
-
- /**
- * Array of inner blocks of a block.
- * @var array
- */
- var $blockinner = array();
-
- /**
- * List of blocks to preverse even if they are "empty".
- *
- * This is something special. Sometimes you have blocks that
- * should be preserved although they are empty (no placeholder replaced).
- * Think of a shopping basket. If it's empty you have to drop a message to
- * the user. If it's filled you have to show the contents of
- * the shopping baseket. Now where do you place the message that the basket
- * is empty? It's no good idea to place it in you applications as customers
- * tend to like unecessary minor text changes. Having another template file
- * for an empty basket means that it's very likely that one fine day
- * the filled and empty basket templates have different layout. I decided
- * to introduce blocks that to not contain any placeholder but only
- * text such as the message "Your shopping basked is empty".
- *
- * Now if there is no replacement done in such a block the block will
- * be recognized as "empty" and by default ($removeEmptyBlocks = true) be
- * stripped off. To avoid thisyou can now call touchBlock() to avoid this.
- *
- * The array $touchedBlocks stores a list of touched block which must not
- * be removed even if they are empty.
- *
- * @var array $touchedBlocks
- * @see touchBlock(), $removeEmptyBlocks
- */
- var $touchedBlocks = array();
-
- /**
- * List of blocks which should not be shown even if not "empty"
- * @var array $_hiddenBlocks
- * @see hideBlock(), $removeEmptyBlocks
- */
- var $_hiddenBlocks = array();
-
- /**
- * Variable cache.
- *
- * Variables get cached before any replacement is done.
- * Advantage: empty blocks can be removed automatically.
- * Disadvantage: might take some more memory
- *
- * @var array
- * @see setVariable(), $clearCacheOnParse
- */
- var $variableCache = array();
-
- /**
- * Clear the variable cache on parse?
- *
- * If you're not an expert just leave the default false.
- * True reduces memory consumption somewhat if you tend to
- * add lots of values for unknown placeholder.
- *
- * @var boolean
- */
- var $clearCacheOnParse = false;
-
- /**
- * Root directory for all file operations.
- * The string gets prefixed to all filenames given.
- * @var string
- * @see HTML_Template_IT(), setRoot()
- */
- var $fileRoot = '';
-
- /**
- * Internal flag indicating that a blockname was used multiple times.
- * @var boolean
- */
- var $flagBlocktrouble = false;
-
- /**
- * Flag indicating that the global block was parsed.
- * @var boolean
- */
- var $flagGlobalParsed = false;
-
- /**
- * EXPERIMENTAL! FIXME!
- * Flag indication that a template gets cached.
- *
- * Complex templates require some times to be preparsed
- * before the replacement can take place. Often I use
- * one template file over and over again but I don't know
- * before that I will use the same template file again.
- * Now IT could notice this and skip the preparse.
- *
- * @var boolean
- */
- var $flagCacheTemplatefile = true;
-
- /**
- * EXPERIMENTAL! FIXME!
- */
- var $lastTemplatefile = '';
-
- /**
- * $_options['preserve_data'] Whether to substitute variables and remove
- * empty placeholders in data passed through setVariable
- * (see also bugs #20199, #21951).
- * $_options['use_preg'] Whether to use preg_replace instead of
- * str_replace in parse()
- * (this is a backwards compatibility feature, see also bugs #21951, #20392)
- */
- var $_options = array(
- 'preserve_data' => false,
- 'use_preg' => true
- );
-
- /**
- * Builds some complex regular expressions and optinally sets the
- * file root directory.
- *
- * Make sure that you call this constructor if you derive your template
- * class from this one.
- *
- * @param string File root directory, prefix for all filenames
- * given to the object.
- * @see setRoot()
- */
- function HTML_Template_IT($root = '', $options = null)
- {
- if (!is_null($options)) {
- $this->setOptions($options);
- }
- $this->variablesRegExp = '@' . $this->openingDelimiter .
- '(' . $this->variablenameRegExp . ')' .
- $this->closingDelimiter . '@sm';
- $this->removeVariablesRegExp = '@' . $this->openingDelimiter .
- "\s*(" . $this->variablenameRegExp .
- ")\s*" . $this->closingDelimiter .'@sm';
-
- $this->blockRegExp = '@<!--\s+BEGIN\s+(' . $this->blocknameRegExp .
- ')\s+-->(.*)<!--\s+END\s+\1\s+-->@sm';
-
- $this->setRoot($root);
- } // end constructor
-
-
- /**
- * Sets the option for the template class
- *
- * @access public
- * @param string option name
- * @param mixed option value
- * @return mixed IT_OK on success, error object on failure
- */
- function setOption($option, $value)
- {
- if (array_key_exists($option, $this->_options)) {
- $this->_options[$option] = $value;
- return IT_OK;
- }
-
- return PEAR::raiseError(
- $this->errorMessage(IT_UNKNOWN_OPTION) . ": '{$option}'",
- IT_UNKNOWN_OPTION
- );
- }
-
- /**
- * Sets the options for the template class
- *
- * @access public
- * @param string options array of options
- * default value:
- * 'preserve_data' => false,
- * 'use_preg' => true
- * @param mixed option value
- * @return mixed IT_OK on success, error object on failure
- * @see $options
- */
- function setOptions($options)
- {
- if (is_array($options)) {
- foreach ($options as $option => $value) {
- $error = $this->setOption($option, $value);
- if (PEAR::isError($error)) {
- return $error;
- }
- }
- }
-
- return IT_OK;
- }
-
- /**
- * Print a certain block with all replacements done.
- * @brother get()
- */
- function show($block = '__global__')
- {
- print $this->get($block);
- } // end func show
-
- /**
- * Returns a block with all replacements done.
- *
- * @param string name of the block
- * @return string
- * @throws PEAR_Error
- * @access public
- * @see show()
- */
- function get($block = '__global__')
- {
- if ($block == '__global__' && !$this->flagGlobalParsed) {
- $this->parse('__global__');
- }
-
- if (!isset($this->blocklist[$block])) {
- $this->err[] = PEAR::raiseError(
- $this->errorMessage(IT_BLOCK_NOT_FOUND) .
- '"' . $block . "'",
- IT_BLOCK_NOT_FOUND
- );
- return '';
- }
-
- if (isset($this->blockdata[$block])) {
- $ret = $this->blockdata[$block];
- if ($this->clearCache) {
- unset($this->blockdata[$block]);
- }
- if ($this->_options['preserve_data']) {
- $ret = str_replace(
- $this->openingDelimiter .
- '%preserved%' . $this->closingDelimiter,
- $this->openingDelimiter,
- $ret
- );
- }
- return $ret;
- }
-
- return '';
- } // end func get()
-
- /**
- * Parses the given block.
- *
- * @param string name of the block to be parsed
- * @access public
- * @see parseCurrentBlock()
- * @throws PEAR_Error
- */
- function parse($block = '__global__', $flag_recursion = false)
- {
- static $regs, $values;
-
- if (!isset($this->blocklist[$block])) {
- return PEAR::raiseError(
- $this->errorMessage( IT_BLOCK_NOT_FOUND ) . '"' . $block . "'",
- IT_BLOCK_NOT_FOUND
- );
- }
-
- if ($block == '__global__') {
- $this->flagGlobalParsed = true;
- }
-
- if (!$flag_recursion) {
- $regs = array();
- $values = array();
- }
- $outer = $this->blocklist[$block];
- $empty = true;
-
- if ($this->clearCacheOnParse) {
- foreach ($this->variableCache as $name => $value) {
- $regs[] = $this->openingDelimiter .
- $name . $this->closingDelimiter;
- $values[] = $value;
- $empty = false;
- }
- $this->variableCache = array();
- } else {
- foreach ($this->blockvariables[$block] as $allowedvar => $v) {
-
- if (isset($this->variableCache[$allowedvar])) {
- $regs[] = $this->openingDelimiter .
- $allowedvar . $this->closingDelimiter;
- $values[] = $this->variableCache[$allowedvar];
- unset($this->variableCache[$allowedvar]);
- $empty = false;
- }
- }
- }
-
- if (isset($this->blockinner[$block])) {
- foreach ($this->blockinner[$block] as $k => $innerblock) {
-
- $this->parse($innerblock, true);
- if ($this->blockdata[$innerblock] != '') {
- $empty = false;
- }
-
- $placeholder = $this->openingDelimiter . "__" .
- $innerblock . "__" . $this->closingDelimiter;
- $outer = str_replace(
- $placeholder,
- $this->blockdata[$innerblock], $outer
- );
- $this->blockdata[$innerblock] = "";
- }
-
- }
-
- if (!$flag_recursion && 0 != count($values)) {
- if ($this->_options['use_preg']) {
- $regs = array_map(array(
- &$this, '_addPregDelimiters'),
- $regs
- );
- $funcReplace = 'preg_replace';
- } else {
- $funcReplace = 'str_replace';
- }
-
- if ($this->_options['preserve_data']) {
- $values = array_map(
- array(&$this, '_preserveOpeningDelimiter'), $values
- );
- }
-
- $outer = $funcReplace($regs, $values, $outer);
-
- if ($this->removeUnknownVariables) {
- $outer = preg_replace($this->removeVariablesRegExp, "", $outer);
- }
- }
-
- if ($empty) {
- if (!$this->removeEmptyBlocks) {
- $this->blockdata[$block ].= $outer;
- } else {
- if (isset($this->touchedBlocks[$block])) {
- $this->blockdata[$block] .= $outer;
- unset($this->touchedBlocks[$block]);
- }
- }
- } else {
- if (empty($this->blockdata[$block])) {
- $this->blockdata[$block] = $outer;
- } else {
- $this->blockdata[$block] .= $outer;
- }
- }
-
- return $empty;
- } // end func parse
-
- /**
- * Parses the current block
- * @see parse(), setCurrentBlock(), $currentBlock
- * @access public
- */
- function parseCurrentBlock()
- {
- return $this->parse($this->currentBlock);
- } // end func parseCurrentBlock
-
- /**
- * Sets a variable value.
- *
- * The function can be used eighter like setVariable( "varname", "value")
- * or with one array $variables["varname"] = "value"
- * given setVariable($variables) quite like phplib templates set_var().
- *
- * @param mixed string with the variable name or an array
- * %variables["varname"] = "value"
- * @param string value of the variable or empty if $variable
- * is an array.
- * @param string prefix for variable names
- * @access public
- */
- function setVariable($variable, $value = '')
- {
- if (is_array($variable)) {
- $this->variableCache = array_merge(
- $this->variableCache, $variable
- );
- } else {
- $this->variableCache[$variable] = $value;
- }
- } // end func setVariable
-
- /**
- * Sets the name of the current block that is the block where variables
- * are added.
- *
- * @param string name of the block
- * @return boolean false on failure, otherwise true
- * @throws PEAR_Error
- * @access public
- */
- function setCurrentBlock($block = '__global__')
- {
-
- if (!isset($this->blocklist[$block])) {
- return PEAR::raiseError(
- $this->errorMessage( IT_BLOCK_NOT_FOUND ) .
- '"' . $block . "'", IT_BLOCK_NOT_FOUND
- );
- }
-
- $this->currentBlock = $block;
-
- return true;
- } // end func setCurrentBlock
-
- /**
- * Preserves an empty block even if removeEmptyBlocks is true.
- *
- * @param string name of the block
- * @return boolean false on false, otherwise true
- * @throws PEAR_Error
- * @access public
- * @see $removeEmptyBlocks
- */
- function touchBlock($block)
- {
- if (!isset($this->blocklist[$block])) {
- return PEAR::raiseError(
- $this->errorMessage(IT_BLOCK_NOT_FOUND) .
- '"' . $block . "'", IT_BLOCK_NOT_FOUND);
- }
-
- $this->touchedBlocks[$block] = true;
-
- return true;
- } // end func touchBlock
-
- /**
- * Clears all datafields of the object and rebuild the internal blocklist
- *
- * LoadTemplatefile() and setTemplate() automatically call this function
- * when a new template is given. Don't use this function
- * unless you know what you're doing.
- *
- * @access public
- * @see free()
- */
- function init()
- {
- $this->free();
- $this->findBlocks($this->template);
- // we don't need it any more
- $this->template = '';
- $this->buildBlockvariablelist();
- } // end func init
-
- /**
- * Clears all datafields of the object.
- *
- * Don't use this function unless you know what you're doing.
- *
- * @access public
- * @see init()
- */
- function free()
- {
- $this->err = array();
-
- $this->currentBlock = '__global__';
-
- $this->variableCache = array();
- $this->blocklist = array();
- $this->touchedBlocks = array();
-
- $this->flagBlocktrouble = false;
- $this->flagGlobalParsed = false;
- } // end func free
-
- /**
- * Sets the template.
- *
- * You can eighter load a template file from disk with
- * LoadTemplatefile() or set the template manually using this function.
- *
- * @param string template content
- * @param boolean remove unknown/unused variables?
- * @param boolean remove empty blocks?
- * @see LoadTemplatefile(), $template
- * @access public
- * @return boolean
- */
- function setTemplate( $template, $removeUnknownVariables = true,
- $removeEmptyBlocks = true)
- {
- $this->removeUnknownVariables = $removeUnknownVariables;
- $this->removeEmptyBlocks = $removeEmptyBlocks;
-
- if ($template == '' && $this->flagCacheTemplatefile) {
- $this->variableCache = array();
- $this->blockdata = array();
- $this->touchedBlocks = array();
- $this->currentBlock = '__global__';
- } else {
- $this->template = '<!-- BEGIN __global__ -->' . $template .
- '<!-- END __global__ -->';
- $this->init();
- }
-
- if ($this->flagBlocktrouble) {
- return false;
- }
-
- return true;
- } // end func setTemplate
-
- /**
- * Reads a template file from the disk.
- *
- * @param string name of the template file
- * @param bool how to handle unknown variables.
- * @param bool how to handle empty blocks.
- * @access public
- * @return boolean false on failure, otherwise true
- * @see $template, setTemplate(), $removeUnknownVariables,
- * $removeEmptyBlocks
- */
- function loadTemplatefile( $filename,
- $removeUnknownVariables = true,
- $removeEmptyBlocks = true )
- {
- $template = '';
- if (!$this->flagCacheTemplatefile ||
- $this->lastTemplatefile != $filename
- ) {
- $template = $this->getFile($filename);
- }
- $this->lastTemplatefile = $filename;
-
- return $template != '' ?
- $this->setTemplate(
- $template,$removeUnknownVariables, $removeEmptyBlocks
- ) : false;
- } // end func LoadTemplatefile
-
- /**
- * Sets the file root. The file root gets prefixed to all filenames passed
- * to the object.
- *
- * Make sure that you override this function when using the class
- * on windows.
- *
- * @param string
- * @see HTML_Template_IT()
- * @access public
- */
- function setRoot($root)
- {
- if ($root != '' && substr($root, -1) != '/') {
- $root .= '/';
- }
-
- $this->fileRoot = $root;
- } // end func setRoot
-
- /**
- * Build a list of all variables within of a block
- */
- function buildBlockvariablelist()
- {
- foreach ($this->blocklist as $name => $content) {
- preg_match_all($this->variablesRegExp, $content, $regs);
-
- if (count($regs[1]) != 0) {
- foreach ($regs[1] as $k => $var) {
- $this->blockvariables[$name][$var] = true;
- }
- } else {
- $this->blockvariables[$name] = array();
- }
- }
- } // end func buildBlockvariablelist
-
- /**
- * Returns a list of all global variables
- */
- function getGlobalvariables()
- {
- $regs = array();
- $values = array();
-
- foreach ($this->blockvariables['__global__'] as $allowedvar => $v) {
- if (isset($this->variableCache[$allowedvar])) {
- $regs[] = '@' . $this->openingDelimiter .
- $allowedvar . $this->closingDelimiter . '@';
- $values[] = $this->variableCache[$allowedvar];
- unset($this->variableCache[$allowedvar]);
- }
- }
-
- return array($regs, $values);
- } // end func getGlobalvariables
-
- /**
- * Recusively builds a list of all blocks within the template.
- *
- * @param string string that gets scanned
- * @see $blocklist
- */
- function findBlocks($string)
- {
- $blocklist = array();
-
- if (preg_match_all($this->blockRegExp, $string, $regs, PREG_SET_ORDER)) {
- foreach ($regs as $k => $match) {
- $blockname = $match[1];
- $blockcontent = $match[2];
-
- if (isset($this->blocklist[$blockname])) {
- $this->err[] = PEAR::raiseError(
- $this->errorMessage(
- IT_BLOCK_DUPLICATE, $blockname),
- IT_BLOCK_DUPLICATE
- );
- $this->flagBlocktrouble = true;
- }
-
- $this->blocklist[$blockname] = $blockcontent;
- $this->blockdata[$blockname] = "";
-
- $blocklist[] = $blockname;
-
- $inner = $this->findBlocks($blockcontent);
- foreach ($inner as $k => $name) {
- $pattern = sprintf(
- '@<!--\s+BEGIN\s+%s\s+-->(.*)<!--\s+END\s+%s\s+-->@sm',
- $name,
- $name
- );
-
- $this->blocklist[$blockname] = preg_replace(
- $pattern,
- $this->openingDelimiter .
- '__' . $name . '__' .
- $this->closingDelimiter,
- $this->blocklist[$blockname]
- );
- $this->blockinner[$blockname][] = $name;
- $this->blockparents[$name] = $blockname;
- }
- }
- }
-
- return $blocklist;
- } // end func findBlocks
-
- /**
- * Reads a file from disk and returns its content.
- * @param string Filename
- * @return string Filecontent
- */
- function getFile($filename)
- {
- if ($filename{0} == '/' && substr($this->fileRoot, -1) == '/') {
- $filename = substr($filename, 1);
- }
-
- $filename = $this->fileRoot . $filename;
-
- if (!($fh = @fopen($filename, 'r'))) {
- $this->err[] = PEAR::raiseError(
- $this->errorMessage(IT_TPL_NOT_FOUND) .
- ': "' .$filename .'"',
- IT_TPL_NOT_FOUND
- );
- return "";
- }
-
- $fsize = filesize($filename);
- if ($fsize < 1) {
- fclose($fh);
- return '';
- }
-
- $content = fread($fh, $fsize);
- fclose($fh);
-
- return preg_replace(
- "#<!-- INCLUDE (.*) -->#ime", "\$this->getFile('\\1')", $content
- );
- } // end func getFile
-
- /**
- * Adds delimiters to a string, so it can be used as a pattern
- * in preg_* functions
- *
- * @param string
- * @return string
- */
- function _addPregDelimiters($str)
- {
- return '@' . $str . '@';
- }
-
- /**
- * Replaces an opening delimiter by a special string
- *
- * @param string
- * @return string
- */
- function _preserveOpeningDelimiter($str)
- {
- return (false === strpos($str, $this->openingDelimiter))?
- $str:
- str_replace(
- $this->openingDelimiter,
- $this->openingDelimiter .
- '%preserved%' . $this->closingDelimiter,
- $str
- );
- }
-
- /**
- * Return a textual error message for a IT error code
- *
- * @param integer $value error code
- *
- * @return string error message, or false if the error code was
- * not recognized
- */
- function errorMessage($value, $blockname = '')
- {
- static $errorMessages;
- if (!isset($errorMessages)) {
- $errorMessages = array(
- IT_OK => '',
- IT_ERROR => 'unknown error',
- IT_TPL_NOT_FOUND => 'Cannot read the template file',
- IT_BLOCK_NOT_FOUND => 'Cannot find this block',
- IT_BLOCK_DUPLICATE => 'The name of a block must be'.
- ' uniquewithin a template.'.
- ' Found "' . $blockname . '" twice.'.
- 'Unpredictable results '.
- 'may appear.',
- IT_UNKNOWN_OPTION => 'Unknown option'
- );
- }
-
- if (PEAR::isError($value)) {
- $value = $value->getCode();
- }
-
- return isset($errorMessages[$value]) ?
- $errorMessages[$value] : $errorMessages[IT_ERROR];
- }
-} // end class IntegratedTemplate
-?>
+++ /dev/null
-<?php
-//
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2005 Ulf Wendel, Pierre-Alain Joye |
-// +----------------------------------------------------------------------+
-// | This source file is subject to the New BSD license, That is bundled |
-// | with this package in the file LICENSE, and is available through |
-// | the world-wide-web at |
-// | http://www.opensource.org/licenses/bsd-license.php |
-// | If you did not receive a copy of the new BSD license and are unable |
-// | to obtain it through the world-wide-web, please send a note to |
-// | pajoye@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Ulf Wendel <ulf.wendel@phpdoc.de> |
-// | Pierre-Alain Joye <pajoye@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: ITX.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-//
-
-require_once 'HTML/Template/IT.php';
-require_once 'HTML/Template/IT_Error.php';
-
-/**
-* Integrated Template Extension - ITX
-*
-* With this class you get the full power of the phplib template class.
-* You may have one file with blocks in it but you have as well one main file
-* and multiple files one for each block. This is quite usefull when you have
-* user configurable websites. Using blocks not in the main template allows
-* you to modify some parts of your layout easily.
-*
-* Note that you can replace an existing block and add new blocks at runtime.
-* Adding new blocks means changing a variable placeholder to a block.
-*
-* @author Ulf Wendel <uw@netuse.de>
-* @access public
-* @version $Id: ITX.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-* @package HTML_Template_IT
-*/
-class HTML_Template_ITX extends HTML_Template_IT
-{
- /**
- * Array with all warnings.
- * @var array
- * @access public
- * @see $printWarning, $haltOnWarning, warning()
- */
- var $warn = array();
-
- /**
- * Print warnings?
- * @var array
- * @access public
- * @see $haltOnWarning, $warn, warning()
- */
- var $printWarning = false;
-
- /**
- * Call die() on warning?
- * @var boolean
- * @access public
- * @see $warn, $printWarning, warning()
- */
- var $haltOnWarning = false;
-
- /**
- * RegExp used to test for a valid blockname.
- * @var string
- */
- var $checkblocknameRegExp = '';
-
- /**
- * Functionnameprefix used when searching function calls in the template.
- * @var string
- */
- var $functionPrefix = 'func_';
-
- /**
- * Functionname RegExp.
- * @var string
- */
- var $functionnameRegExp = '[_a-zA-Z]+[A-Za-z_0-9]*';
-
- /**
- * RegExp used to grep function calls in the template.
- *
- * The variable gets set by the constructor.
- *
- * @var string
- * @see HTML_Template_IT()
- */
- var $functionRegExp = '';
-
- /**
- * List of functions found in the template.
- *
- * @var array
- */
- var $functions = array();
-
- /**
- * List of callback functions specified by the user.
- *
- * @var array
- */
- var $callback = array();
-
- /**
- * Builds some complex regexps and calls the constructor
- * of the parent class.
- *
- * Make sure that you call this constructor if you derive your own
- * template class from this one.
- *
- * @see HTML_Template_IT()
- */
- function HTML_Template_ITX($root = '')
- {
-
- $this->checkblocknameRegExp = '@' . $this->blocknameRegExp . '@';
- $this->functionRegExp = '@' . $this->functionPrefix . '(' .
- $this->functionnameRegExp . ')\s*\(@sm';
-
- $this->HTML_Template_IT($root);
- } // end func constructor
-
- function init()
- {
- $this->free();
- $this->buildFunctionlist();
- $this->findBlocks($this->template);
- // we don't need it any more
- $this->template = '';
- $this->buildBlockvariablelist();
-
- } // end func init
-
- /**
- * Replaces an existing block with new content.
- *
- * This function will replace a block of the template and all blocks
- * contained in the replaced block and add a new block insted, means
- * you can dynamically change your template.
- *
- * Note that changing the template structure violates one of the IT[X]
- * development goals. I've tried to write a simple to use template engine
- * supporting blocks. In contrast to other systems IT[X] analyses the way
- * you've nested blocks and knows which block belongs into another block.
- * The nesting information helps to make the API short and simple. Replacing
- * blocks does not only mean that IT[X] has to update the nesting
- * information (relatively time consumpting task) but you have to make sure
- * that you do not get confused due to the template change itself.
- *
- * @param string Blockname
- * @param string Blockcontent
- * @param boolean true if the new block inherits the content
- * of the old block
- * @return boolean
- * @throws IT_Error
- * @see replaceBlockfile(), addBlock(), addBlockfile()
- * @access public
- */
- function replaceBlock($block, $template, $keep_content = false)
- {
- if (!isset($this->blocklist[$block])) {
- return new IT_Error(
- "The block "."'$block'".
- " does not exist in the template and thus it can't be replaced.",
- __FILE__, __LINE__
- );
- }
-
- if ($template == '') {
- return new IT_Error('No block content given.', __FILE__, __LINE__);
- }
-
- if ($keep_content) {
- $blockdata = $this->blockdata[$block];
- }
-
- // remove all kinds of links to the block / data of the block
- $this->removeBlockData($block);
-
- $template = "<!-- BEGIN $block -->" . $template . "<!-- END $block -->";
- $parents = $this->blockparents[$block];
- $this->findBlocks($template);
- $this->blockparents[$block] = $parents;
-
- // KLUDGE: rebuild the list for all block - could be done faster
- $this->buildBlockvariablelist();
-
- if ($keep_content) {
- $this->blockdata[$block] = $blockdata;
- }
-
- // old TODO - I'm not sure if we need this
- // update caches
-
- return true;
- } // end func replaceBlock
-
- /**
- * Replaces an existing block with new content from a file.
- *
- * @brother replaceBlock()
- * @param string Blockname
- * @param string Name of the file that contains the blockcontent
- * @param boolean true if the new block inherits the content of the old block
- * @access public
- */
- function replaceBlockfile($block, $filename, $keep_content = false)
- {
- return $this->replaceBlock($block, $this->getFile($filename), $keep_content);
- } // end func replaceBlockfile
-
- /**
- * Adds a block to the template changing a variable placeholder
- * to a block placeholder.
- *
- * Add means "replace a variable placeholder by a new block".
- * This is different to PHPLibs templates. The function loads a
- * block, creates a handle for it and assigns it to a certain
- * variable placeholder. To to the same with PHPLibs templates you would
- * call set_file() to create the handle and parse() to assign the
- * parsed block to a variable. By this PHPLibs templates assume
- * that you tend to assign a block to more than one one placeholder.
- * To assign a parsed block to more than only the placeholder you specify
- * in this function you have to use a combination of getBlock()
- * and setVariable().
- *
- * As no updates to cached data is necessary addBlock() and addBlockfile()
- * are rather "cheap" meaning quick operations.
- *
- * The block content must not start with <!-- BEGIN blockname -->
- * and end with <!-- END blockname --> this would cause overhead and
- * produce an error.
- *
- * @param string Name of the variable placeholder, the name must be unique
- * within the template.
- * @param string Name of the block to be added
- * @param string Content of the block
- * @return boolean
- * @throws IT_Error
- * @see addBlockfile()
- * @access public
- */
- function addBlock($placeholder, $blockname, $template)
- {
- // Don't trust any user even if it's a programmer or yourself...
- if ($placeholder == '') {
- return new IT_Error('No variable placeholder given.',
- __FILE__, __LINE__
- );
- } elseif ($blockname == '' ||
- !preg_match($this->checkblocknameRegExp, $blockname)
- ) {
- return new IT_Error("No or invalid blockname '$blockname' given.",
- __FILE__, __LINE__
- );
- } elseif ($template == '') {
- return new IT_Error('No block content given.', __FILE__, __LINE__);
- } elseif (isset($this->blocklist[$blockname])) {
- return new IT_Error('The block already exists.',
- __FILE__, __LINE__
- );
- }
-
- // find out where to insert the new block
- $parents = $this->findPlaceholderBlocks($placeholder);
- if (count($parents) == 0) {
-
- return new IT_Error(
- "The variable placeholder".
- " '$placeholder' was not found in the template.",
- __FILE__, __LINE__
- );
-
- } elseif (count($parents) > 1) {
-
- reset($parents);
- while (list($k, $parent) = each($parents)) {
- $msg .= "$parent, ";
- }
- $msg = substr($parent, -2);
-
- return new IT_Error("The variable placeholder "."'$placeholder'".
- " must be unique, found in multiple blocks '$msg'.",
- __FILE__, __LINE__
- );
- }
-
- $template = "<!-- BEGIN $blockname -->" . $template . "<!-- END $blockname -->";
- $this->findBlocks($template);
- if ($this->flagBlocktrouble) {
- return false; // findBlocks() already throws an exception
- }
- $this->blockinner[$parents[0]][] = $blockname;
- $this->blocklist[$parents[0]] = preg_replace(
- '@' . $this->openingDelimiter . $placeholder .
- $this->closingDelimiter . '@',
-
- $this->openingDelimiter . '__' . $blockname . '__' .
- $this->closingDelimiter,
-
- $this->blocklist[$parents[0]]
- );
-
- $this->deleteFromBlockvariablelist($parents[0], $placeholder);
- $this->updateBlockvariablelist($blockname);
-
- return true;
- } // end func addBlock
-
- /**
- * Adds a block taken from a file to the template changing a variable
- * placeholder to a block placeholder.
- *
- * @param string Name of the variable placeholder to be converted
- * @param string Name of the block to be added
- * @param string File that contains the block
- * @brother addBlock()
- * @access public
- */
- function addBlockfile($placeholder, $blockname, $filename)
- {
- return $this->addBlock($placeholder, $blockname, $this->getFile($filename));
- } // end func addBlockfile
-
- /**
- * Returns the name of the (first) block that contains
- * the specified placeholder.
- *
- * @param string Name of the placeholder you're searching
- * @param string Name of the block to scan. If left out (default)
- * all blocks are scanned.
- * @return string Name of the (first) block that contains
- * the specified placeholder.
- * If the placeholder was not found or an error occured
- * an empty string is returned.
- * @throws IT_Error
- * @access public
- */
- function placeholderExists($placeholder, $block = '')
- {
- if ($placeholder == '') {
- new IT_Error('No placeholder name given.', __FILE__, __LINE__);
- return '';
- }
-
- if ($block != '' && !isset($this->blocklist[$block])) {
- new IT_Error("Unknown block '$block'.", __FILE__, __LINE__);
- return '';
- }
-
- // name of the block where the given placeholder was found
- $found = '';
-
- if ($block != '') {
- if (is_array($variables = $this->blockvariables[$block])) {
- // search the value in the list of blockvariables
- reset($variables);
- while (list($k, $variable) = each($variables)) {
- if ($k == $placeholder) {
- $found = $block;
- break;
- }
- }
- }
- } else {
-
- // search all blocks and return the name of the first block that
- // contains the placeholder
- reset($this->blockvariables);
- while (list($blockname, $variables) = each($this->blockvariables)){
- if (is_array($variables) && isset($variables[$placeholder])) {
- $found = $blockname;
- break;
- }
- }
- }
-
- return $found;
- } // end func placeholderExists
-
- /**
- * Checks the list of function calls in the template and
- * calls their callback function.
- *
- * @access public
- */
- function performCallback()
- {
- reset($this->functions);
- while (list($func_id, $function) = each($this->functions)) {
- if (isset($this->callback[$function['name']])) {
- if ($this->callback[$function['name']]['expandParameters']) {
- $callFunction = 'call_user_func_array';
- } else {
- $callFunction = 'call_user_func';
- }
-
- if ($this->callback[$function['name']]['object'] != '') {
- $call =
- $callFunction(
- array(
- &$GLOBALS[$this->callback[$function['name']]['object']],
- $this->callback[$function['name']]['function']),
- $function['args']
- );
-
- } else {
- $call =
- $callFunction(
- $this->callback[$function['name']]['function'],
- $function['args']
- );
- }
- $this->variableCache['__function' . $func_id . '__'] = $call;
- }
- }
-
- } // end func performCallback
-
- /**
- * Returns a list of all function calls in the current template.
- *
- * @return array
- * @access public
- */
- function getFunctioncalls()
- {
- return $this->functions;
- } // end func getFunctioncalls
-
- /**
- * Replaces a function call with the given replacement.
- *
- * @param int Function ID
- * @param string Replacement
- * @deprecated
- */
- function setFunctioncontent($functionID, $replacement)
- {
- $this->variableCache['__function' . $functionID . '__'] = $replacement;
- } // end func setFunctioncontent
-
- /**
- * Sets a callback function.
- *
- * IT[X] templates (note the X) can contain simple function calls.
- * "function call" means that the editor of the template can add
- * special placeholder to the template like 'func_h1("embedded in h1")'.
- * IT[X] will grab this function calls and allow you to define a callback
- * function for them.
- *
- * This is an absolutely evil feature. If your application makes heavy
- * use of such callbacks and you're even implementing if-then etc. on
- * the level of a template engine you're reiventing the wheel... - that's
- * actually how PHP came into life. Anyway, sometimes it's handy.
- *
- * Consider also using XML/XSLT or native PHP. And please do not push
- * IT[X] any further into this direction of adding logics to the template
- * engine.
- *
- * For those of you ready for the X in IT[X]:
- *
- * <?php
- * ...
- * function h_one($args) {
- * return sprintf('<h1>%s</h1>', $args[0]);
- * }
- *
- * ...
- * $itx = new HTML_Template_ITX( ... );
- * ...
- * $itx->setCallbackFunction('h1', 'h_one');
- * $itx->performCallback();
- * ?>
- *
- * template:
- * func_h1('H1 Headline');
- *
- * @param string Function name in the template
- * @param string Name of the callback function
- * @param string Name of the callback object
- * @param boolean If the callback is called with a list of parameters or
- * with an array holding the parameters
- * @return boolean False on failure.
- * @throws IT_Error
- * @access public
- * @deprecated The $callbackobject parameter is depricated since
- * version 1.2 and might be dropped in further versions.
- */
- function
- setCallbackFunction($tplfunction, $callbackfunction, $callbackobject = '', $expandCallbackParameters=false)
- {
- if ($tplfunction == '' || $callbackfunction == '') {
- return new IT_Error(
- "No template function "."('$tplfunction')".
- " and/or no callback function ('$callback') given.",
- __FILE__, __LINE__
- );
- }
- $this->callback[$tplfunction] = array(
- 'function' => $callbackfunction,
- 'object' => $callbackobject,
- 'expandParameters' => (boolean) $expandCallbackParameters
- );
-
- return true;
- } // end func setCallbackFunction
-
- /**
- * Sets the Callback function lookup table
- *
- * @param array function table
- * array[templatefunction] =
- * array(
- * "function" => userfunction,
- * "object" => userobject
- * )
- * @access public
- */
- function setCallbackFuntiontable($functions)
- {
- $this->callback = $functions;
- } // end func setCallbackFunctiontable
-
- /**
- * Recursively removes all data assiciated with a block, including all inner blocks
- *
- * @param string block to be removed
- * @access private
- */
- function removeBlockData($block)
- {
- if (isset($this->blockinner[$block])) {
- foreach ($this->blockinner[$block] as $k => $inner) {
- $this->removeBlockData($inner);
- }
-
- unset($this->blockinner[$block]);
- }
-
- unset($this->blocklist[$block]);
- unset($this->blockdata[$block]);
- unset($this->blockvariables[$block]);
- unset($this->touchedBlocks[$block]);
-
- } // end func removeBlockinner
-
- /**
- * Returns a list of blocknames in the template.
- *
- * @return array [blockname => blockname]
- * @access public
- * @see blockExists()
- */
- function getBlocklist()
- {
- $blocklist = array();
- foreach ($this->blocklist as $block => $content) {
- $blocklist[$block] = $block;
- }
-
- return $blocklist;
- } // end func getBlocklist
-
- /**
- * Checks wheter a block exists.
- *
- * @param string
- * @return boolean
- * @access public
- * @see getBlocklist()
- */
- function blockExists($blockname)
- {
- return isset($this->blocklist[$blockname]);
- } // end func blockExists
-
- /**
- * Returns a list of variables of a block.
- *
- * @param string Blockname
- * @return array [varname => varname]
- * @access public
- * @see BlockvariableExists()
- */
- function getBlockvariables($block)
- {
- if (!isset($this->blockvariables[$block])) {
- return array();
- }
-
- $variables = array();
- foreach ($this->blockvariables[$block] as $variable => $v) {
- $variables[$variable] = $variable;
- }
-
- return $variables;
- } // end func getBlockvariables
-
- /**
- * Checks wheter a block variable exists.
- *
- * @param string Blockname
- * @param string Variablename
- * @return boolean
- * @access public
- * @see getBlockvariables()
- */
- function BlockvariableExists($block, $variable)
- {
- return isset($this->blockvariables[$block][$variable]);
- } // end func BlockvariableExists
-
- /**
- * Builds a functionlist from the template.
- * @access private
- */
- function buildFunctionlist()
- {
- $this->functions = array();
-
- $template = $this->template;
- $num = 0;
-
- while (preg_match($this->functionRegExp, $template, $regs)) {
-
- $pos = strpos($template, $regs[0]);
- $template = substr($template, $pos + strlen($regs[0]));
-
- $head = $this->getValue($template, ')');
- $args = array();
-
- $search = $regs[0] . $head . ')';
-
- $replace = $this->openingDelimiter .
- '__function' . $num . '__' .
- $this->closingDelimiter;
-
- $this->template = str_replace($search, $replace, $this->template);
- $template = str_replace($search, $replace, $template);
-
- while ($head != '' && $args2 = $this->getValue($head, ',')) {
- $arg2 = trim($args2);
- $args[] = ('"' == $arg2{0} || "'" == $arg2{0}) ?
- substr($arg2, 1, -1) : $arg2;
- if ($arg2 == $head) {
- break;
- }
- $head = substr($head, strlen($arg2) + 1);
- }
-
- $this->functions[$num++] = array(
- 'name' => $regs[1],
- 'args' => $args
- );
- }
-
- } // end func buildFunctionlist
-
- /**
- * Truncates the given code from the first occurence of
- * $delimiter but ignores $delimiter enclosed by " or '.
- *
- * @access private
- * @param string The code which should be parsed
- * @param string The delimiter char
- * @return string
- * @see buildFunctionList()
- */
- function getValue($code, $delimiter) {
- if ($code == '') {
- return '';
- }
-
- if (!is_array($delimiter)) {
- $delimiter = array( $delimiter => true );
- }
-
- $len = strlen($code);
- $enclosed = false;
- $enclosed_by = '';
-
- if (isset($delimiter[$code[0]])) {
- $i = 1;
- } else {
- for ($i = 0; $i < $len; ++$i) {
- $char = $code[$i];
-
- if (
- ($char == '"' || $char == "'") &&
- ($char == $enclosed_by || '' == $enclosed_by) &&
- (0 == $i || ($i > 0 && '\\' != $code[$i - 1]))
- ) {
-
- if (!$enclosed) {
- $enclosed_by = $char;
- } else {
- $enclosed_by = "";
- }
- $enclosed = !$enclosed;
-
- }
-
- if (!$enclosed && isset($delimiter[$char])) {
- break;
- }
- }
- }
-
- return substr($code, 0, $i);
- } // end func getValue
-
- /**
- * Deletes one or many variables from the block variable list.
- *
- * @param string Blockname
- * @param mixed Name of one variable or array of variables
- * ( array ( name => true ) ) to be stripped.
- * @access private
- */
- function deleteFromBlockvariablelist($block, $variables)
- {
- if (!is_array($variables)) {
- $variables = array($variables => true);
- }
-
- reset($this->blockvariables[$block]);
- while (list($varname, $val) = each($this->blockvariables[$block])) {
- if (isset($variables[$varname])) {
- unset($this->blockvariables[$block][$varname]);
- }
- }
- } // end deleteFromBlockvariablelist
-
- /**
- * Updates the variable list of a block.
- *
- * @param string Blockname
- * @access private
- */
- function updateBlockvariablelist($block)
- {
- preg_match_all( $this->variablesRegExp,
- $this->blocklist[$block], $regs
- );
-
- if (count($regs[1]) != 0) {
- foreach ($regs[1] as $k => $var) {
- $this->blockvariables[$block][$var] = true;
- }
- } else {
- $this->blockvariables[$block] = array();
- }
-
- // check if any inner blocks were found
- if (isset($this->blockinner[$block]) &&
- is_array($this->blockinner[$block]) &&
- count($this->blockinner[$block]) > 0
- ) {
- /*
- * loop through inner blocks, registering the variable
- * placeholders in each
- */
- foreach ($this->blockinner[$block] as $childBlock) {
- $this->updateBlockvariablelist($childBlock);
- }
- }
- } // end func updateBlockvariablelist
-
- /**
- * Returns an array of blocknames where the given variable
- * placeholder is used.
- *
- * @param string Variable placeholder
- * @return array $parents parents[0..n] = blockname
- * @access public
- */
- function findPlaceholderBlocks($variable)
- {
- $parents = array();
- reset($this->blocklist);
- while (list($blockname, $content) = each($this->blocklist)) {
- reset($this->blockvariables[$blockname]);
- while (
- list($varname, $val) = each($this->blockvariables[$blockname]))
- {
- if ($variable == $varname) {
- $parents[] = $blockname;
- }
- }
- }
-
- return $parents;
- } // end func findPlaceholderBlocks
-
- /**
- * Handles warnings, saves them to $warn and prints them or
- * calls die() depending on the flags
- *
- * @param string Warning
- * @param string File where the warning occured
- * @param int Linenumber where the warning occured
- * @see $warn, $printWarning, $haltOnWarning
- * @access private
- */
- function warning($message, $file = '', $line = 0)
- {
- $message = sprintf(
- 'HTML_Template_ITX Warning: %s [File: %s, Line: %d]',
- $message,
- $file,
- $line
- );
-
- $this->warn[] = $message;
-
- if ($this->printWarning) {
- print $message;
- }
-
- if ($this->haltOnWarning) {
- die($message);
- }
- } // end func warning
-
-} // end class HTML_Template_ITX
-?>
+++ /dev/null
-<?php
-//
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2005 Ulf Wendel, Pierre-Alain Joye |
-// +----------------------------------------------------------------------+
-// | This source file is subject to the New BSD license, That is bundled |
-// | with this package in the file LICENSE, and is available through |
-// | the world-wide-web at |
-// | http://www.opensource.org/licenses/bsd-license.php |
-// | If you did not receive a copy of the new BSD license and are unable |
-// | to obtain it through the world-wide-web, please send a note to |
-// | pajoye@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Ulf Wendel <ulf.wendel@phpdoc.de> |
-// | Pierre-Alain Joye <pajoye@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: IT_Error.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-require_once "PEAR.php";
-
-/**
-* IT[X] Error class
-*
-* @package HTML_Template_IT
-*/
-class IT_Error extends PEAR_Error {
-
-
- /**
- * Prefix of all error messages.
- *
- * @var string
- */
- var $error_message_prefix = "IntegratedTemplate Error: ";
-
- /**
- * Creates an cache error object.
- *
- * @param string error message
- * @param string file where the error occured
- * @param string linenumber where the error occured
- */
- function IT_Error($msg, $file = __FILE__, $line = __LINE__) {
-
- $this->PEAR_Error(sprintf("%s [%s on line %d].", $msg, $file, $line));
-
- } // end func IT_Error
-
-} // end class IT_Error
-?>
+++ /dev/null
-<?php
-/**
- * Implementation of Integrated Templates API with template 'compilation' added.
- *
- * PHP versions 4 and 5
- *
- * LICENSE: This source file is subject to version 3.01 of the PHP license
- * that is available through the world-wide-web at the following URI:
- * http://www.php.net/license/3_01.txt If you did not receive a copy of
- * the PHP License and are unable to obtain it through the web, please
- * send a note to license@php.net so we can mail you a copy immediately.
- *
- * @category HTML
- * @package HTML_Template_Sigma
- * @author Ulf Wendel <ulf.wendel@phpdoc.de>
- * @author Alexey Borzov <avb@php.net>
- * @copyright 2001-2007 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version CVS: $Id: Sigma.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
- * @link http://pear.php.net/package/HTML_Template_Sigma
- */
-
-/**
- * PEAR and PEAR_Error classes (for error handling)
- */
-require_once 'PEAR.php';
-
-/**#@+
- * Error codes
- * @see HTML_Template_Sigma::errorMessage()
- */
-define('SIGMA_OK', 1);
-define('SIGMA_ERROR', -1);
-define('SIGMA_TPL_NOT_FOUND', -2);
-define('SIGMA_BLOCK_NOT_FOUND', -3);
-define('SIGMA_BLOCK_DUPLICATE', -4);
-define('SIGMA_CACHE_ERROR', -5);
-define('SIGMA_UNKNOWN_OPTION', -6);
-define('SIGMA_PLACEHOLDER_NOT_FOUND', -10);
-define('SIGMA_PLACEHOLDER_DUPLICATE', -11);
-define('SIGMA_BLOCK_EXISTS', -12);
-define('SIGMA_INVALID_CALLBACK', -13);
-define('SIGMA_CALLBACK_SYNTAX_ERROR', -14);
-/**#@-*/
-
-/**
-* Implementation of Integrated Templates API with template 'compilation' added.
-*
-* The main new feature in Sigma is the template 'compilation'. Consider the
-* following: when loading a template file the engine has to parse it using
-* regular expressions to find all the blocks and variable placeholders. This
-* is a very "expensive" operation and is definitely an overkill to do on
-* every page request: templates seldom change on production websites. This is
-* where the cache kicks in: it saves an internal representation of the
-* template structure into a file and this file gets loaded instead of the
-* source one on subsequent requests (unless the source changes, of course).
-*
-* While HTML_Template_Sigma inherits PHPLib Template's template syntax, it has
-* an API which is easier to understand. When using HTML_Template_PHPLIB, you
-* have to explicitly name a source and a target the block gets parsed into.
-* This gives maximum flexibility but requires full knowledge of template
-* structure from the programmer.
-*
-* Integrated Template on the other hands manages block nesting and parsing
-* itself. The engine knows that inner1 is a child of block2, there's
-* no need to tell it about this:
-*
-* <pre>
-* + __global__ (hidden and automatically added)
-* + block1
-* + block2
-* + inner1
-* + inner2
-* </pre>
-*
-* To add content to block1 you simply type:
-* <code>$tpl->setCurrentBlock("block1");</code>
-* and repeat this as often as needed:
-* <code>
-* $tpl->setVariable(...);
-* $tpl->parseCurrentBlock();
-* </code>
-*
-* To add content to block2 you would type something like:
-* <code>
-* $tpl->setCurrentBlock("inner1");
-* $tpl->setVariable(...);
-* $tpl->parseCurrentBlock();
-*
-* $tpl->setVariable(...);
-* $tpl->parseCurrentBlock();
-*
-* $tpl->parse("block2");
-* </code>
-*
-* This will result in one repetition of block2 which contains two repetitions
-* of inner1. inner2 will be removed if $removeEmptyBlock is set to true (which
-* is the default).
-*
-* Usage:
-* <code>
-* $tpl = new HTML_Template_Sigma( [string filerootdir], [string cacherootdir] );
-*
-* // load a template or set it with setTemplate()
-* $tpl->loadTemplatefile( string filename [, boolean removeUnknownVariables, boolean removeEmptyBlocks] )
-*
-* // set "global" Variables meaning variables not beeing within a (inner) block
-* $tpl->setVariable( string variablename, mixed value );
-*
-* // like with the HTML_Template_PHPLIB there's a second way to use setVariable()
-* $tpl->setVariable( array ( string varname => mixed value ) );
-*
-* // Let's use any block, even a deeply nested one
-* $tpl->setCurrentBlock( string blockname );
-*
-* // repeat this as often as you need it.
-* $tpl->setVariable( array ( string varname => mixed value ) );
-* $tpl->parseCurrentBlock();
-*
-* // get the parsed template or print it: $tpl->show()
-* $html = $tpl->get();
-* </code>
-*
-* @category HTML
-* @package HTML_Template_Sigma
-* @author Ulf Wendel <ulf.wendel@phpdoc.de>
-* @author Alexey Borzov <avb@php.net>
-* @version Release: 1.1.6
-*/
-class HTML_Template_Sigma extends PEAR
-{
- /**
- * First character of a variable placeholder ( _{_VARIABLE} ).
- * @var string
- * @access public
- * @see $closingDelimiter, $blocknameRegExp, $variablenameRegExp
- */
- var $openingDelimiter = '{';
-
- /**
- * Last character of a variable placeholder ( {VARIABLE_}_ )
- * @var string
- * @access public
- * @see $openingDelimiter, $blocknameRegExp, $variablenameRegExp
- */
- var $closingDelimiter = '}';
-
- /**
- * RegExp for matching the block names in the template.
- * Per default "sm" is used as the regexp modifier, "i" is missing.
- * That means a case sensitive search is done.
- * @var string
- * @access public
- * @see $variablenameRegExp, $openingDelimiter, $closingDelimiter
- */
- var $blocknameRegExp = '[0-9A-Za-z_-]+';
-
- /**
- * RegExp matching a variable placeholder in the template.
- * Per default "sm" is used as the regexp modifier, "i" is missing.
- * That means a case sensitive search is done.
- * @var string
- * @access public
- * @see $blocknameRegExp, $openingDelimiter, $closingDelimiter
- */
- var $variablenameRegExp = '[0-9A-Za-z._-]+';
-
- /**
- * RegExp used to find variable placeholder, filled by the constructor
- * @var string Looks somewhat like @(delimiter varname delimiter)@
- * @see HTML_Template_Sigma()
- */
- var $variablesRegExp = '';
-
- /**
- * RegExp used to strip unused variable placeholders
- * @see $variablesRegExp, HTML_Template_Sigma()
- */
- var $removeVariablesRegExp = '';
-
- /**
- * RegExp used to find blocks and their content, filled by the constructor
- * @var string
- * @see HTML_Template_Sigma()
- */
- var $blockRegExp = '';
-
- /**
- * Controls the handling of unknown variables, default is remove
- * @var boolean
- * @access public
- */
- var $removeUnknownVariables = true;
-
- /**
- * Controls the handling of empty blocks, default is remove
- * @var boolean
- * @access public
- */
- var $removeEmptyBlocks = true;
-
- /**
- * Name of the current block
- * @var string
- */
- var $currentBlock = '__global__';
-
- /**
- * Template blocks and their content
- * @var array
- * @see _buildBlocks()
- * @access private
- */
- var $_blocks = array();
-
- /**
- * Content of parsed blocks
- * @var array
- * @see get(), parse()
- * @access private
- */
- var $_parsedBlocks = array();
-
- /**
- * Variable names that appear in the block
- * @var array
- * @see _buildBlockVariables()
- * @access private
- */
- var $_blockVariables = array();
-
- /**
- * Inner blocks inside the block
- * @var array
- * @see _buildBlocks()
- * @access private
- */
- var $_children = array();
-
- /**
- * List of blocks to preserve even if they are "empty"
- * @var array
- * @see touchBlock(), $removeEmptyBlocks
- * @access private
- */
- var $_touchedBlocks = array();
-
- /**
- * List of blocks which should not be shown even if not "empty"
- * @var array
- * @see hideBlock(), $removeEmptyBlocks
- * @access private
- */
- var $_hiddenBlocks = array();
-
- /**
- * Variables for substitution.
- *
- * Variables are kept in this array before the replacements are done.
- * This allows automatic removal of empty blocks.
- *
- * @var array
- * @see setVariable()
- * @access private
- */
- var $_variables = array();
-
- /**
- * Global variables for substitution
- *
- * These are substituted into all blocks, are not cleared on
- * block parsing and do not trigger "non-empty" logic. I.e. if
- * only global variables are substituted into the block, it is
- * still considered "empty".
- *
- * @var array
- * @see setVariable(), setGlobalVariable()
- * @access private
- */
- var $_globalVariables = array();
-
- /**
- * Root directory for "source" templates
- * @var string
- * @see HTML_Template_Sigma(), setRoot()
- */
- var $fileRoot = '';
-
- /**
- * Directory to store the "prepared" templates in
- * @var string
- * @see HTML_Template_Sigma(), setCacheRoot()
- * @access private
- */
- var $_cacheRoot = null;
-
- /**
- * Flag indicating that the global block was parsed
- * @var boolean
- */
- var $flagGlobalParsed = false;
-
- /**
- * Options to control some finer aspects of Sigma's work.
- *
- * @var array
- * @access private
- */
- var $_options = array(
- 'preserve_data' => false,
- 'trim_on_save' => true
- );
-
- /**
- * Function name prefix used when searching for function calls in the template
- * @var string
- */
- var $functionPrefix = 'func_';
-
- /**
- * Function name RegExp
- * @var string
- */
- var $functionnameRegExp = '[_a-zA-Z]+[A-Za-z_0-9]*';
-
- /**
- * RegExp used to grep function calls in the template (set by the constructor)
- * @var string
- * @see _buildFunctionlist(), HTML_Template_Sigma()
- */
- var $functionRegExp = '';
-
- /**
- * List of functions found in the template.
- * @var array
- * @access private
- */
- var $_functions = array();
-
- /**
- * List of callback functions specified by the user
- * @var array
- * @access private
- */
- var $_callback = array();
-
- /**
- * RegExp used to find file inclusion calls in the template (should have 'e' modifier)
- * @var string
- */
- var $includeRegExp = '#<!--\s+INCLUDE\s+(\S+)\s+-->#ime';
-
- /**
- * Files queued for inclusion
- * @var array
- * @access private
- */
- var $_triggers = array();
-
-
- /**
- * Constructor: builds some complex regular expressions and optionally
- * sets the root directories.
- *
- * Make sure that you call this constructor if you derive your template
- * class from this one.
- *
- * @param string root directory for templates
- * @param string directory to cache "prepared" templates in
- * @see setRoot(), setCacheRoot()
- */
- function HTML_Template_Sigma($root = '', $cacheRoot = '')
- {
- // the class is inherited from PEAR to be able to use $this->setErrorHandling()
- $this->PEAR();
- $this->variablesRegExp = '@' . $this->openingDelimiter . '(' . $this->variablenameRegExp . ')' .
- '(:(' . $this->functionnameRegExp . '))?' . $this->closingDelimiter . '@sm';
- $this->removeVariablesRegExp = '@'.$this->openingDelimiter.'\s*('.$this->variablenameRegExp.')\s*'.$this->closingDelimiter.'@sm';
- $this->blockRegExp = '@<!--\s+BEGIN\s+('.$this->blocknameRegExp.')\s+-->(.*)<!--\s+END\s+\1\s+-->@sm';
- $this->functionRegExp = '@' . $this->functionPrefix . '(' . $this->functionnameRegExp . ')\s*\(@sm';
- $this->setRoot($root);
- $this->setCacheRoot($cacheRoot);
-
- $this->setCallbackFunction('h', 'htmlspecialchars');
- $this->setCallbackFunction('u', 'urlencode');
- $this->setCallbackFunction('j', array(&$this, '_jsEscape'));
- }
-
-
- /**
- * Sets the file root for templates. The file root gets prefixed to all
- * filenames passed to the object.
- *
- * @param string directory name
- * @see HTML_Template_Sigma()
- * @access public
- */
- function setRoot($root)
- {
- if (('' != $root) && (DIRECTORY_SEPARATOR != substr($root, -1))) {
- $root .= DIRECTORY_SEPARATOR;
- }
- $this->fileRoot = $root;
- }
-
-
- /**
- * Sets the directory to cache "prepared" templates in, the directory should be writable for PHP.
- *
- * The "prepared" template contains an internal representation of template
- * structure: essentially a serialized array of $_blocks, $_blockVariables,
- * $_children and $_functions, may also contain $_triggers. This allows
- * to bypass expensive calls to _buildBlockVariables() and especially
- * _buildBlocks() when reading the "prepared" template instead of
- * the "source" one.
- *
- * The files in this cache do not have any TTL and are regenerated when the
- * source templates change.
- *
- * @param string directory name
- * @see HTML_Template_Sigma(), _getCached(), _writeCache()
- * @access public
- */
- function setCacheRoot($root)
- {
- if (empty($root)) {
- $root = null;
- } elseif (DIRECTORY_SEPARATOR != substr($root, -1)) {
- $root .= DIRECTORY_SEPARATOR;
- }
- $this->_cacheRoot = $root;
- }
-
-
- /**
- * Sets the option for the template class
- *
- * Currently available options:
- * - preserve_data: If false (default), then substitute variables and
- * remove empty placeholders in data passed through setVariable (see also
- * PHP bugs #20199, #21951)
- * - trim_on_save: Whether to trim extra whitespace from template on cache
- * save (defaults to true). Generally safe to leave this on, unless you
- * have <<pre>><</pre>> in templates or want to preserve HTML indentantion
- *
- * @access public
- * @param string option name
- * @param mixed option value
- * @return mixed SIGMA_OK on success, error object on failure
- */
- function setOption($option, $value)
- {
- if (isset($this->_options[$option])) {
- $this->_options[$option] = $value;
- return SIGMA_OK;
- }
- return $this->raiseError($this->errorMessage(SIGMA_UNKNOWN_OPTION, $option), SIGMA_UNKNOWN_OPTION);
- }
-
-
- /**
- * Returns a textual error message for an error code
- *
- * @access public
- * @param integer error code
- * @param string additional data to insert into message
- * @return string error message
- */
- function errorMessage($code, $data = null)
- {
- static $errorMessages;
- if (!isset($errorMessages)) {
- $errorMessages = array(
- SIGMA_ERROR => 'unknown error',
- SIGMA_OK => '',
- SIGMA_TPL_NOT_FOUND => 'Cannot read the template file \'%s\'',
- SIGMA_BLOCK_NOT_FOUND => 'Cannot find block \'%s\'',
- SIGMA_BLOCK_DUPLICATE => 'The name of a block must be unique within a template. Block \'%s\' found twice.',
- SIGMA_CACHE_ERROR => 'Cannot save template file \'%s\'',
- SIGMA_UNKNOWN_OPTION => 'Unknown option \'%s\'',
- SIGMA_PLACEHOLDER_NOT_FOUND => 'Variable placeholder \'%s\' not found',
- SIGMA_PLACEHOLDER_DUPLICATE => 'Placeholder \'%s\' should be unique, found in multiple blocks',
- SIGMA_BLOCK_EXISTS => 'Block \'%s\' already exists',
- SIGMA_INVALID_CALLBACK => 'Callback does not exist',
- SIGMA_CALLBACK_SYNTAX_ERROR => 'Cannot parse template function: %s'
- );
- }
-
- if (PEAR::isError($code)) {
- $code = $code->getCode();
- }
- if (!isset($errorMessages[$code])) {
- return $errorMessages[SIGMA_ERROR];
- } else {
- return (null === $data)? $errorMessages[$code]: sprintf($errorMessages[$code], $data);
- }
- }
-
-
- /**
- * Prints a block with all replacements done.
- *
- * @access public
- * @param string block name
- * @see get()
- */
- function show($block = '__global__')
- {
- print $this->get($block);
- }
-
-
- /**
- * Returns a block with all replacements done.
- *
- * @param string block name
- * @param bool whether to clear parsed block contents
- * @return string block with all replacements done
- * @throws PEAR_Error
- * @access public
- * @see show()
- */
- function get($block = '__global__', $clear = false)
- {
- if (!isset($this->_blocks[$block])) {
- return $this->raiseError($this->errorMessage(SIGMA_BLOCK_NOT_FOUND, $block), SIGMA_BLOCK_NOT_FOUND);
- }
- if ('__global__' == $block && !$this->flagGlobalParsed) {
- $this->parse('__global__');
- }
- // return the parsed block, removing the unknown placeholders if needed
- if (!isset($this->_parsedBlocks[$block])) {
- return '';
-
- } else {
- $ret = $this->_parsedBlocks[$block];
- if ($clear) {
- unset($this->_parsedBlocks[$block]);
- }
- if ($this->removeUnknownVariables) {
- $ret = preg_replace($this->removeVariablesRegExp, '', $ret);
- }
- if ($this->_options['preserve_data']) {
- $ret = str_replace($this->openingDelimiter . '%preserved%' . $this->closingDelimiter, $this->openingDelimiter, $ret);
- }
- return $ret;
- }
- }
-
-
- /**
- * Parses the given block.
- *
- * @param string block name
- * @param boolean true if the function is called recursively (do not set this to true yourself!)
- * @param boolean true if parsing a "hidden" block (do not set this to true yourself!)
- * @access public
- * @see parseCurrentBlock()
- * @throws PEAR_Error
- */
- function parse($block = '__global__', $flagRecursion = false, $fakeParse = false)
- {
- static $vars;
-
- if (!isset($this->_blocks[$block])) {
- return $this->raiseError($this->errorMessage(SIGMA_BLOCK_NOT_FOUND, $block), SIGMA_BLOCK_NOT_FOUND);
- }
- if ('__global__' == $block) {
- $this->flagGlobalParsed = true;
- }
- if (!isset($this->_parsedBlocks[$block])) {
- $this->_parsedBlocks[$block] = '';
- }
- $outer = $this->_blocks[$block];
-
- if (!$flagRecursion) {
- $vars = array();
- }
- // block is not empty if its local var is substituted
- $empty = true;
- foreach ($this->_blockVariables[$block] as $allowedvar => $v) {
- if (isset($this->_variables[$allowedvar])) {
- $vars[$this->openingDelimiter . $allowedvar . $this->closingDelimiter] = $this->_variables[$allowedvar];
- $empty = false;
- // vital for checking "empty/nonempty" status
- unset($this->_variables[$allowedvar]);
- }
- }
-
- // processing of the inner blocks
- if (isset($this->_children[$block])) {
- foreach ($this->_children[$block] as $innerblock => $v) {
- $placeholder = $this->openingDelimiter.'__'.$innerblock.'__'.$this->closingDelimiter;
-
- if (isset($this->_hiddenBlocks[$innerblock])) {
- // don't bother actually parsing this inner block; but we _have_
- // to go through its local vars to prevent problems on next iteration
- $this->parse($innerblock, true, true);
- unset($this->_hiddenBlocks[$innerblock]);
- $outer = str_replace($placeholder, '', $outer);
-
- } else {
- $this->parse($innerblock, true, $fakeParse);
- // block is not empty if its inner block is not empty
- if ('' != $this->_parsedBlocks[$innerblock]) {
- $empty = false;
- }
-
- $outer = str_replace($placeholder, $this->_parsedBlocks[$innerblock], $outer);
- $this->_parsedBlocks[$innerblock] = '';
- }
- }
- }
-
- // add "global" variables to the static array
- foreach ($this->_globalVariables as $allowedvar => $value) {
- if (isset($this->_blockVariables[$block][$allowedvar])) {
- $vars[$this->openingDelimiter . $allowedvar . $this->closingDelimiter] = $value;
- }
- }
- // if we are inside a hidden block, don't bother
- if (!$fakeParse) {
- if (0 != count($vars) && (!$flagRecursion || !empty($this->_functions[$block]))) {
- $varKeys = array_keys($vars);
- $varValues = $this->_options['preserve_data']? array_map(array(&$this, '_preserveOpeningDelimiter'), array_values($vars)): array_values($vars);
- }
-
- // check whether the block is considered "empty" and append parsed content if not
- if (!$empty || ('__global__' == $block) || !$this->removeEmptyBlocks || isset($this->_touchedBlocks[$block])) {
- // perform callbacks
- if (!empty($this->_functions[$block])) {
- foreach ($this->_functions[$block] as $id => $data) {
- $placeholder = $this->openingDelimiter . '__function_' . $id . '__' . $this->closingDelimiter;
- // do not waste time calling function more than once
- if (!isset($vars[$placeholder])) {
- $args = array();
- $preserveArgs = isset($this->_callback[$data['name']]['preserveArgs']) && $this->_callback[$data['name']]['preserveArgs'];
- foreach ($data['args'] as $arg) {
- $args[] = (empty($varKeys) || $preserveArgs)? $arg: str_replace($varKeys, $varValues, $arg);
- }
- if (isset($this->_callback[$data['name']]['data'])) {
- $res = call_user_func_array($this->_callback[$data['name']]['data'], $args);
- } else {
- $res = isset($args[0])? $args[0]: '';
- }
- $outer = str_replace($placeholder, $res, $outer);
- // save the result to variable cache, it can be requested somewhere else
- $vars[$placeholder] = $res;
- }
- }
- }
- // substitute variables only on non-recursive call, thus all
- // variables from all inner blocks get substituted
- if (!$flagRecursion && !empty($varKeys)) {
- $outer = str_replace($varKeys, $varValues, $outer);
- }
-
- $this->_parsedBlocks[$block] .= $outer;
- if (isset($this->_touchedBlocks[$block])) {
- unset($this->_touchedBlocks[$block]);
- }
- }
- }
- return $empty;
- }
-
-
- /**
- * Sets a variable value.
- *
- * The function can be used either like setVariable("varname", "value")
- * or with one array $variables["varname"] = "value" given setVariable($variables)
- *
- * @access public
- * @param mixed variable name or array ('varname'=>'value')
- * @param string variable value if $variable is not an array
- */
- function setVariable($variable, $value = '')
- {
- if (is_array($variable)) {
- $this->_variables = array_merge($this->_variables, $variable);
- } elseif (!is_array($variable) && is_array($value)) {
- $this->_variables = array_merge($this->_variables, $this->_flattenVariables($variable, $value));
- } else {
- $this->_variables[$variable] = $value;
- }
- }
-
-
- /**
- * Sets a global variable value.
- *
- * @access public
- * @param mixed variable name or array ('varname'=>'value')
- * @param string variable value if $variable is not an array
- * @see setVariable()
- */
- function setGlobalVariable($variable, $value = '')
- {
- if (is_array($variable)) {
- $this->_globalVariables = array_merge($this->_globalVariables, $variable);
- } else if (!is_array($variable) && is_array($value)) {
- $this->_globalVariables = array_merge($this->_globalVariables, $this->_flattenVariables($variable, $value));
- } else {
- $this->_globalVariables[$variable] = $value;
- }
- }
-
-
- /**
- * Sets the name of the current block: the block where variables are added
- *
- * @param string block name
- * @return mixed SIGMA_OK on success, error object on failure
- * @throws PEAR_Error
- * @access public
- */
- function setCurrentBlock($block = '__global__')
- {
- if (!isset($this->_blocks[$block])) {
- return $this->raiseError($this->errorMessage(SIGMA_BLOCK_NOT_FOUND, $block), SIGMA_BLOCK_NOT_FOUND);
- }
- $this->currentBlock = $block;
- return SIGMA_OK;
- }
-
-
- /**
- * Parses the current block
- *
- * @see parse(), setCurrentBlock()
- * @access public
- */
- function parseCurrentBlock()
- {
- return $this->parse($this->currentBlock);
- }
-
-
- /**
- * Returns the current block name
- *
- * @return string block name
- * @access public
- */
- function getCurrentBlock()
- {
- return $this->currentBlock;
- }
-
-
- /**
- * Preserves the block even if empty blocks should be removed.
- *
- * Sometimes you have blocks that should be preserved although they are
- * empty (no placeholder replaced). Think of a shopping basket. If it's
- * empty you have to show a message to the user. If it's filled you have
- * to show the contents of the shopping basket. Now where to place the
- * message that the basket is empty? It's not a good idea to place it
- * in you application as customers tend to like unecessary minor text
- * changes. Having another template file for an empty basket means that
- * one fine day the filled and empty basket templates will have different
- * layouts.
- *
- * So blocks that do not contain any placeholders but only messages like
- * "Your shopping basked is empty" are intoduced. Now if there is no
- * replacement done in such a block the block will be recognized as "empty"
- * and by default ($removeEmptyBlocks = true) be stripped off. To avoid this
- * you can call touchBlock()
- *
- * @param string block name
- * @return mixed SIGMA_OK on success, error object on failure
- * @throws PEAR_Error
- * @access public
- * @see $removeEmptyBlocks, $_touchedBlocks
- */
- function touchBlock($block)
- {
- if (!isset($this->_blocks[$block])) {
- return $this->raiseError($this->errorMessage(SIGMA_BLOCK_NOT_FOUND, $block), SIGMA_BLOCK_NOT_FOUND);
- }
- if (isset($this->_hiddenBlocks[$block])) {
- unset($this->_hiddenBlocks[$block]);
- }
- $this->_touchedBlocks[$block] = true;
- return SIGMA_OK;
- }
-
-
- /**
- * Hides the block even if it is not "empty".
- *
- * Is somewhat an opposite to touchBlock().
- *
- * Consider a block (a 'edit' link for example) that should be visible to
- * registered/"special" users only, but its visibility is triggered by
- * some little 'id' field passed in a large array into setVariable(). You
- * can either carefully juggle your variables to prevent the block from
- * appearing (a fragile solution) or simply call hideBlock()
- *
- * @param string block name
- * @return mixed SIGMA_OK on success, error object on failure
- * @throws PEAR_Error
- * @access public
- */
- function hideBlock($block)
- {
- if (!isset($this->_blocks[$block])) {
- return $this->raiseError($this->errorMessage(SIGMA_BLOCK_NOT_FOUND, $block), SIGMA_BLOCK_NOT_FOUND);
- }
- if (isset($this->_touchedBlocks[$block])) {
- unset($this->_touchedBlocks[$block]);
- }
- $this->_hiddenBlocks[$block] = true;
- return SIGMA_OK;
- }
-
-
- /**
- * Sets the template.
- *
- * You can either load a template file from disk with LoadTemplatefile() or set the
- * template manually using this function.
- *
- * @access public
- * @param string template content
- * @param boolean remove unknown/unused variables?
- * @param boolean remove empty blocks?
- * @return mixed SIGMA_OK on success, error object on failure
- * @see loadTemplatefile()
- */
- function setTemplate($template, $removeUnknownVariables = true, $removeEmptyBlocks = true)
- {
- $this->_resetTemplate($removeUnknownVariables, $removeEmptyBlocks);
- $list = $this->_buildBlocks('<!-- BEGIN __global__ -->'.$template.'<!-- END __global__ -->');
- if (PEAR::isError($list)) {
- return $list;
- }
- return $this->_buildBlockVariables();
- }
-
-
- /**
- * Loads a template file.
- *
- * If caching is on, then it checks whether a "prepared" template exists.
- * If it does, it gets loaded instead of the original, if it does not, then
- * the original gets loaded and prepared and then the prepared version is saved.
- * addBlockfile() and replaceBlockfile() implement quite the same logic.
- *
- * @param string filename
- * @param boolean remove unknown/unused variables?
- * @param boolean remove empty blocks?
- * @access public
- * @return mixed SIGMA_OK on success, error object on failure
- * @see setTemplate(), $removeUnknownVariables, $removeEmptyBlocks
- */
- function loadTemplateFile($filename, $removeUnknownVariables = true, $removeEmptyBlocks = true)
- {
- if ($this->_isCached($filename)) {
- $this->_resetTemplate($removeUnknownVariables, $removeEmptyBlocks);
- return $this->_getCached($filename);
- }
- $template = $this->_getFile($this->fileRoot . $filename);
- if (PEAR::isError($template)) {
- return $template;
- }
- $this->_triggers = array();
- $template = preg_replace($this->includeRegExp, "\$this->_makeTrigger('\\1', '__global__')", $template);
- if (SIGMA_OK !== ($res = $this->setTemplate($template, $removeUnknownVariables, $removeEmptyBlocks))) {
- return $res;
- } else {
- return $this->_writeCache($filename, '__global__');
- }
- }
-
-
- /**
- * Adds a block to the template changing a variable placeholder to a block placeholder.
- *
- * This means that a new block will be integrated into the template in
- * place of a variable placeholder. The variable placeholder will be
- * removed and the new block will behave in the same way as if it was
- * inside the original template.
- *
- * The block content must not start with <!-- BEGIN blockname --> and end with
- * <!-- END blockname -->, if it does the error will be thrown.
- *
- * @param string name of the variable placeholder, the name must be unique within the template.
- * @param string name of the block to be added
- * @param string content of the block
- * @return mixed SIGMA_OK on success, error object on failure
- * @throws PEAR_Error
- * @see addBlockfile()
- * @access public
- */
- function addBlock($placeholder, $block, $template)
- {
- if (isset($this->_blocks[$block])) {
- return $this->raiseError($this->errorMessage(SIGMA_BLOCK_EXISTS, $block), SIGMA_BLOCK_EXISTS);
- }
- $parents = $this->_findParentBlocks($placeholder);
- if (0 == count($parents)) {
- return $this->raiseError($this->errorMessage(SIGMA_PLACEHOLDER_NOT_FOUND, $placeholder), SIGMA_PLACEHOLDER_NOT_FOUND);
- } elseif (count($parents) > 1) {
- return $this->raiseError($this->errorMessage(SIGMA_PLACEHOLDER_DUPLICATE, $placeholder), SIGMA_PLACEHOLDER_DUPLICATE);
- }
-
- $template = "<!-- BEGIN $block -->" . $template . "<!-- END $block -->";
- $list = $this->_buildBlocks($template);
- if (PEAR::isError($list)) {
- return $list;
- }
- $this->_replacePlaceholder($parents[0], $placeholder, $block);
- return $this->_buildBlockVariables($block);
- }
-
-
- /**
- * Adds a block taken from a file to the template, changing a variable placeholder
- * to a block placeholder.
- *
- * @param string name of the variable placeholder
- * @param string name of the block to be added
- * @param string template file that contains the block
- * @return mixed SIGMA_OK on success, error object on failure
- * @throws PEAR_Error
- * @see addBlock()
- * @access public
- */
- function addBlockfile($placeholder, $block, $filename)
- {
- if ($this->_isCached($filename)) {
- return $this->_getCached($filename, $block, $placeholder);
- }
- $template = $this->_getFile($this->fileRoot . $filename);
- if (PEAR::isError($template)) {
- return $template;
- }
- $template = preg_replace($this->includeRegExp, "\$this->_makeTrigger('\\1', '{$block}')", $template);
- if (SIGMA_OK !== ($res = $this->addBlock($placeholder, $block, $template))) {
- return $res;
- } else {
- return $this->_writeCache($filename, $block);
- }
- }
-
-
- /**
- * Replaces an existing block with new content.
- *
- * This function will replace a block of the template and all blocks
- * contained in it and add a new block instead. This means you can
- * dynamically change your template.
- *
- * Sigma analyses the way you've nested blocks and knows which block
- * belongs into another block. This nesting information helps to make the
- * API short and simple. Replacing blocks does not only mean that Sigma
- * has to update the nesting information (relatively time consuming task)
- * but you have to make sure that you do not get confused due to the
- * template change yourself.
- *
- * @param string name of a block to replace
- * @param string new content
- * @param boolean true if the parsed contents of the block should be kept
- * @access public
- * @see replaceBlockfile(), addBlock()
- * @return mixed SIGMA_OK on success, error object on failure
- * @throws PEAR_Error
- */
- function replaceBlock($block, $template, $keepContent = false)
- {
- if (!isset($this->_blocks[$block])) {
- return $this->raiseError($this->errorMessage(SIGMA_BLOCK_NOT_FOUND, $block), SIGMA_BLOCK_NOT_FOUND);
- }
- // should not throw a error as we already checked for block existance
- $this->_removeBlockData($block, $keepContent);
- $template = "<!-- BEGIN $block -->" . $template . "<!-- END $block -->";
-
- $list = $this->_buildBlocks($template);
- if (PEAR::isError($list)) {
- return $list;
- }
- // renew the variables list
- return $this->_buildBlockVariables($block);
- }
-
-
- /**
- * Replaces an existing block with new content from a file.
- *
- * @access public
- * @param string name of a block to replace
- * @param string template file that contains the block
- * @param boolean true if the parsed contents of the block should be kept
- * @return mixed SIGMA_OK on success, error object on failure
- * @throws PEAR_Error
- * @see replaceBlock(), addBlockfile()
- */
- function replaceBlockfile($block, $filename, $keepContent = false)
- {
- if ($this->_isCached($filename)) {
- if (PEAR::isError($res = $this->_removeBlockData($block, $keepContent))) {
- return $res;
- } else {
- return $this->_getCached($filename, $block);
- }
- }
- $template = $this->_getFile($this->fileRoot . $filename);
- if (PEAR::isError($template)) {
- return $template;
- }
- $template = preg_replace($this->includeRegExp, "\$this->_makeTrigger('\\1', '{$block}')", $template);
- if (SIGMA_OK !== ($res = $this->replaceBlock($block, $template, $keepContent))) {
- return $res;
- } else {
- return $this->_writeCache($filename, $block);
- }
- }
-
-
- /**
- * Checks if the block exists in the template
- *
- * @param string block name
- * @return bool
- * @access public
- */
- function blockExists($block)
- {
- return isset($this->_blocks[$block]);
- }
-
-
- /**
- * Returns the name of the (first) block that contains the specified placeholder.
- *
- * @param string Name of the placeholder you're searching
- * @param string Name of the block to scan. If left out (default) all blocks are scanned.
- * @return string Name of the (first) block that contains the specified placeholder.
- * If the placeholder was not found an empty string is returned.
- * @access public
- * @throws PEAR_Error
- */
- function placeholderExists($placeholder, $block = '')
- {
- if ('' != $block && !isset($this->_blocks[$block])) {
- return $this->raiseError($this->errorMessage(SIGMA_BLOCK_NOT_FOUND, $block), SIGMA_BLOCK_NOT_FOUND);
- }
- if ('' != $block) {
- // if we search in the specific block, we should just check the array
- return isset($this->_blockVariables[$block][$placeholder])? $block: '';
- } else {
- // _findParentBlocks returns an array, we need only the first element
- $parents = $this->_findParentBlocks($placeholder);
- return empty($parents)? '': $parents[0];
- }
- } // end func placeholderExists
-
-
- /**
- * Sets a callback function.
- *
- * Sigma templates can contain simple function calls. This means that the
- * author of the template can add a special placeholder to it:
- * <pre>
- * func_h1("embedded in h1")
- * </pre>
- * Sigma will parse the template for these placeholders and will allow
- * you to define a callback function for them. Callback will be called
- * automatically when the block containing such function call is parse()'d.
- *
- * Please note that arguments to these template functions can contain
- * variable placeholders: func_translate('Hello, {username}'), but not
- * blocks or other function calls.
- *
- * This should NOT be used to add logic (except some presentation one) to
- * the template. If you use a lot of such callbacks and implement business
- * logic through them, then you're reinventing the wheel. Consider using
- * XML/XSLT, native PHP or some other template engine.
- *
- * <code>
- * function h_one($arg) {
- * return '<h1>' . $arg . '</h1>';
- * }
- * ...
- * $tpl = new HTML_Template_Sigma( ... );
- * ...
- * $tpl->setCallbackFunction('h1', 'h_one');
- * </code>
- *
- * template:
- * <pre>
- * func_h1('H1 Headline');
- * </pre>
- *
- * @param string Function name in the template
- * @param mixed A callback: anything that can be passed to call_user_func_array()
- * @param bool If true, then no variable substitution in arguments will take place before function call
- * @return mixed SIGMA_OK on success, error object on failure
- * @throws PEAR_Error
- * @access public
- */
- function setCallbackFunction($tplFunction, $callback, $preserveArgs = false)
- {
- if (!is_callable($callback)) {
- return $this->raiseError($this->errorMessage(SIGMA_INVALID_CALLBACK), SIGMA_INVALID_CALLBACK);
- }
- $this->_callback[$tplFunction] = array(
- 'data' => $callback,
- 'preserveArgs' => $preserveArgs
- );
- return SIGMA_OK;
- } // end func setCallbackFunction
-
-
- /**
- * Returns a list of blocks within a template.
- *
- * If $recursive is false, it returns just a 'flat' array of $parent's
- * direct subblocks. If $recursive is true, it builds a tree of template
- * blocks using $parent as root. Tree structure is compatible with
- * PEAR::Tree's Memory_Array driver.
- *
- * @param string parent block name
- * @param bool whether to return a tree of child blocks (true) or a 'flat' array (false)
- * @access public
- * @return array a list of child blocks
- * @throws PEAR_Error
- */
- function getBlockList($parent = '__global__', $recursive = false)
- {
- if (!isset($this->_blocks[$parent])) {
- return $this->raiseError($this->errorMessage(SIGMA_BLOCK_NOT_FOUND, $parent), SIGMA_BLOCK_NOT_FOUND);
- }
- if (!$recursive) {
- return isset($this->_children[$parent])? array_keys($this->_children[$parent]): array();
- } else {
- $ret = array('name' => $parent);
- if (!empty($this->_children[$parent])) {
- $ret['children'] = array();
- foreach (array_keys($this->_children[$parent]) as $child) {
- $ret['children'][] = $this->getBlockList($child, true);
- }
- }
- return $ret;
- }
- }
-
-
- /**
- * Returns a list of placeholders within a block.
- *
- * Only 'normal' placeholders are returned, not auto-created ones.
- *
- * @param string block name
- * @access public
- * @return array a list of placeholders
- * @throws PEAR_Error
- */
- function getPlaceholderList($block = '__global__')
- {
- if (!isset($this->_blocks[$block])) {
- return $this->raiseError($this->errorMessage(SIGMA_BLOCK_NOT_FOUND, $block), SIGMA_BLOCK_NOT_FOUND);
- }
- $ret = array();
- foreach ($this->_blockVariables[$block] as $var => $v) {
- if ('__' != substr($var, 0, 2) || '__' != substr($var, -2)) {
- $ret[] = $var;
- }
- }
- return $ret;
- }
-
-
- /**
- * Clears the variables
- *
- * Global variables are not affected. The method is useful when you add
- * a lot of variables via setVariable() and are not sure whether all of
- * them appear in the block you parse(). If you clear the variables after
- * parse(), you don't risk them suddenly showing up in other blocks.
- *
- * @access public
- * @see setVariable()
- */
- function clearVariables()
- {
- $this->_variables = array();
- }
-
-
- //------------------------------------------------------------
- //
- // Private methods follow
- //
- //------------------------------------------------------------
-
- /**
- * Builds the variable names for nested variables
- *
- * @param string variable name
- * @param array value array
- * @return array array with 'name.key' keys
- * @access private
- */
- function _flattenVariables($name, $array)
- {
- $ret = array();
- foreach ($array as $key => $value) {
- if (is_array($value)) {
- $ret = array_merge($ret, $this->_flattenVariables($name . '.' . $key, $value));
- } else {
- $ret[$name . '.' . $key] = $value;
- }
- }
- return $ret;
- }
-
- /**
- * Reads the file and returns its content
- *
- * @param string filename
- * @return string file content (or error object)
- * @access private
- */
- function _getFile($filename)
- {
- if (!($fh = @fopen($filename, 'rb'))) {
- return $this->raiseError($this->errorMessage(SIGMA_TPL_NOT_FOUND, $filename), SIGMA_TPL_NOT_FOUND);
- }
- $content = fread($fh, max(1, filesize($filename)));
- fclose($fh);
- return $content;
- }
-
-
- /**
- * Recursively builds a list of all variables within a block.
- *
- * Also calls _buildFunctionlist() for each block it visits
- *
- * @param string block name
- * @see _buildFunctionlist()
- * @access private
- */
- function _buildBlockVariables($block = '__global__')
- {
- $this->_blockVariables[$block] = array();
- $this->_functions[$block] = array();
- preg_match_all($this->variablesRegExp, $this->_blocks[$block], $regs, PREG_SET_ORDER);
- foreach ($regs as $match) {
- $this->_blockVariables[$block][$match[1]] = true;
- if (!empty($match[3])) {
- $funcData = array(
- 'name' => $match[3],
- 'args' => array($this->openingDelimiter . $match[1] . $this->closingDelimiter)
- );
- $funcId = substr(md5(serialize($funcData)), 0, 10);
-
- // update block info
- $this->_blocks[$block] = str_replace($match[0], $this->openingDelimiter . '__function_' . $funcId . '__' . $this->closingDelimiter, $this->_blocks[$block]);
- $this->_blockVariables[$block]['__function_' . $funcId . '__'] = true;
- $this->_functions[$block][$funcId] = $funcData;
- }
- }
- if (SIGMA_OK != ($res = $this->_buildFunctionlist($block))) {
- return $res;
- }
- if (isset($this->_children[$block]) && is_array($this->_children[$block])) {
- foreach ($this->_children[$block] as $child => $v) {
- if (SIGMA_OK != ($res = $this->_buildBlockVariables($child))) {
- return $res;
- }
- }
- }
- return SIGMA_OK;
- }
-
-
- /**
- * Recusively builds a list of all blocks within the template.
- *
- * @param string template to be scanned
- * @see $_blocks
- * @throws PEAR_Error
- * @return mixed array of block names on success or error object on failure
- * @access private
- */
- function _buildBlocks($string)
- {
- $blocks = array();
- if (preg_match_all($this->blockRegExp, $string, $regs, PREG_SET_ORDER)) {
- foreach ($regs as $k => $match) {
- $blockname = $match[1];
- $blockcontent = $match[2];
- if (isset($this->_blocks[$blockname]) || isset($blocks[$blockname])) {
- return $this->raiseError($this->errorMessage(SIGMA_BLOCK_DUPLICATE, $blockname), SIGMA_BLOCK_DUPLICATE);
- }
- $this->_blocks[$blockname] = $blockcontent;
- $blocks[$blockname] = true;
- $inner = $this->_buildBlocks($blockcontent);
- if (PEAR::isError($inner)) {
- return $inner;
- }
- foreach ($inner as $name => $v) {
- $pattern = sprintf('@<!--\s+BEGIN\s+%s\s+-->(.*)<!--\s+END\s+%s\s+-->@sm', $name, $name);
- $replacement = $this->openingDelimiter.'__'.$name.'__'.$this->closingDelimiter;
- $this->_blocks[$blockname] = preg_replace($pattern, $replacement, $this->_blocks[$blockname]);
- $this->_children[$blockname][$name] = true;
- }
- }
- }
- return $blocks;
- }
-
-
- /**
- * Resets the object's properties, used before processing a new template
- *
- * @param boolean remove unknown/unused variables?
- * @param boolean remove empty blocks?
- * @see setTemplate(), loadTemplateFile()
- * @access private
- */
- function _resetTemplate($removeUnknownVariables = true, $removeEmptyBlocks = true)
- {
- $this->removeUnknownVariables = $removeUnknownVariables;
- $this->removeEmptyBlocks = $removeEmptyBlocks;
- $this->currentBlock = '__global__';
- $this->_variables = array();
- $this->_blocks = array();
- $this->_children = array();
- $this->_parsedBlocks = array();
- $this->_touchedBlocks = array();
- $this->_functions = array();
- $this->flagGlobalParsed = false;
- } // _resetTemplate
-
-
- /**
- * Checks whether we have a "prepared" template cached.
- *
- * If we do not do caching, always returns false
- *
- * @access private
- * @param string source filename
- * @return bool yes/no
- * @see loadTemplatefile(), addBlockfile(), replaceBlockfile()
- */
- function _isCached($filename)
- {
- if (null === $this->_cacheRoot) {
- return false;
- }
- $cachedName = $this->_cachedName($filename);
- $sourceName = $this->fileRoot . $filename;
- // if $sourceName does not exist, error will be thrown later
- $sourceTime = @filemtime($sourceName);
- if ((false !== $sourceTime) && @file_exists($cachedName) && (filemtime($cachedName) > $sourceTime)) {
- return true;
- } else {
- return false;
- }
- } // _isCached
-
-
- /**
- * Loads a "prepared" template file
- *
- * @access private
- * @param string filename
- * @param string block name
- * @param string variable placeholder to replace by a block
- * @return mixed SIGMA_OK on success, error object on failure
- * @see loadTemplatefile(), addBlockfile(), replaceBlockfile()
- */
- function _getCached($filename, $block = '__global__', $placeholder = '')
- {
- // the same checks are done in addBlock()
- if (!empty($placeholder)) {
- if (isset($this->_blocks[$block])) {
- return $this->raiseError($this->errorMessage(SIGMA_BLOCK_EXISTS, $block), SIGMA_BLOCK_EXISTS);
- }
- $parents = $this->_findParentBlocks($placeholder);
- if (0 == count($parents)) {
- return $this->raiseError($this->errorMessage(SIGMA_PLACEHOLDER_NOT_FOUND, $placeholder), SIGMA_PLACEHOLDER_NOT_FOUND);
- } elseif (count($parents) > 1) {
- return $this->raiseError($this->errorMessage(SIGMA_PLACEHOLDER_DUPLICATE, $placeholder), SIGMA_PLACEHOLDER_DUPLICATE);
- }
- }
- $content = $this->_getFile($this->_cachedName($filename));
- if (PEAR::isError($content)) {
- return $content;
- }
- $cache = unserialize($content);
- if ('__global__' != $block) {
- $this->_blocks[$block] = $cache['blocks']['__global__'];
- $this->_blockVariables[$block] = $cache['variables']['__global__'];
- $this->_children[$block] = $cache['children']['__global__'];
- $this->_functions[$block] = $cache['functions']['__global__'];
- unset($cache['blocks']['__global__'], $cache['variables']['__global__'], $cache['children']['__global__'], $cache['functions']['__global__']);
- }
- $this->_blocks = array_merge($this->_blocks, $cache['blocks']);
- $this->_blockVariables = array_merge($this->_blockVariables, $cache['variables']);
- $this->_children = array_merge($this->_children, $cache['children']);
- $this->_functions = array_merge($this->_functions, $cache['functions']);
-
- // the same thing gets done in addBlockfile()
- if (!empty($placeholder)) {
- $this->_replacePlaceholder($parents[0], $placeholder, $block);
- }
- // pull the triggers, if any
- if (isset($cache['triggers'])) {
- return $this->_pullTriggers($cache['triggers']);
- }
- return SIGMA_OK;
- } // _getCached
-
-
- /**
- * Returns a full name of a "prepared" template file
- *
- * @access private
- * @param string source filename, relative to root directory
- * @return string filename
- */
- function _cachedName($filename)
- {
- if (OS_WINDOWS) {
- $filename = str_replace(array('/', '\\', ':'), array('__', '__', ''), $filename);
- } else {
- $filename = str_replace('/', '__', $filename);
- }
- return $this->_cacheRoot. $filename. '.it';
- } // _cachedName
-
-
- /**
- * Writes a prepared template file.
- *
- * Even if NO caching is going on, this method has a side effect: it calls
- * the _pullTriggers() method and thus loads all files added via <!-- INCLUDE -->
- *
- * @access private
- * @param string source filename, relative to root directory
- * @param string name of the block to save into file
- * @return mixed SIGMA_OK on success, error object on failure
- */
- function _writeCache($filename, $block)
- {
- // do not save anything if no cache dir, but do pull triggers
- if (null !== $this->_cacheRoot) {
- $cache = array(
- 'blocks' => array(),
- 'variables' => array(),
- 'children' => array(),
- 'functions' => array()
- );
- $cachedName = $this->_cachedName($filename);
- $this->_buildCache($cache, $block);
- if ('__global__' != $block) {
- foreach (array_keys($cache) as $k) {
- $cache[$k]['__global__'] = $cache[$k][$block];
- unset($cache[$k][$block]);
- }
- }
- if (isset($this->_triggers[$block])) {
- $cache['triggers'] = $this->_triggers[$block];
- }
- if (!($fh = @fopen($cachedName, 'wb'))) {
- return $this->raiseError($this->errorMessage(SIGMA_CACHE_ERROR, $cachedName), SIGMA_CACHE_ERROR);
- }
- fwrite($fh, serialize($cache));
- fclose($fh);
- }
- // now pull triggers
- if (isset($this->_triggers[$block])) {
- if (SIGMA_OK !== ($res = $this->_pullTriggers($this->_triggers[$block]))) {
- return $res;
- }
- unset($this->_triggers[$block]);
- }
- return SIGMA_OK;
- } // _writeCache
-
-
- /**
- * Builds an array of template data to be saved in prepared template file
- *
- * @access private
- * @param array template data
- * @param string block to add to the array
- */
- function _buildCache(&$cache, $block)
- {
- if (!$this->_options['trim_on_save']) {
- $cache['blocks'][$block] = $this->_blocks[$block];
- } else {
- $cache['blocks'][$block] = preg_replace(
- array('/^\\s+/m', '/\\s+$/m', '/(\\r?\\n)+/'),
- array('', '', "\n"),
- $this->_blocks[$block]
- );
- }
- $cache['variables'][$block] = $this->_blockVariables[$block];
- $cache['functions'][$block] = isset($this->_functions[$block])? $this->_functions[$block]: array();
- if (!isset($this->_children[$block])) {
- $cache['children'][$block] = array();
- } else {
- $cache['children'][$block] = $this->_children[$block];
- foreach (array_keys($this->_children[$block]) as $child) {
- $this->_buildCache($cache, $child);
- }
- }
- }
-
-
- /**
- * Recursively removes all data belonging to a block
- *
- * @param string block name
- * @param boolean true if the parsed contents of the block should be kept
- * @return mixed SIGMA_OK on success, error object on failure
- * @see replaceBlock(), replaceBlockfile()
- * @access private
- */
- function _removeBlockData($block, $keepContent = false)
- {
- if (!isset($this->_blocks[$block])) {
- return $this->raiseError($this->errorMessage(SIGMA_BLOCK_NOT_FOUND, $block), SIGMA_BLOCK_NOT_FOUND);
- }
- if (!empty($this->_children[$block])) {
- foreach (array_keys($this->_children[$block]) as $child) {
- $this->_removeBlockData($child, false);
- }
- unset($this->_children[$block]);
- }
- unset($this->_blocks[$block]);
- unset($this->_blockVariables[$block]);
- unset($this->_hiddenBlocks[$block]);
- unset($this->_touchedBlocks[$block]);
- unset($this->_functions[$block]);
- if (!$keepContent) {
- unset($this->_parsedBlocks[$block]);
- }
- return SIGMA_OK;
- }
-
-
- /**
- * Returns the names of the blocks where the variable placeholder appears
- *
- * @param string variable name
- * @return array block names
- * @see addBlock(), addBlockfile(), placeholderExists()
- * @access private
- */
- function _findParentBlocks($variable)
- {
- $parents = array();
- foreach ($this->_blockVariables as $blockname => $varnames) {
- if (!empty($varnames[$variable])) {
- $parents[] = $blockname;
- }
- }
- return $parents;
- }
-
-
- /**
- * Replaces a variable placeholder by a block placeholder.
- *
- * Of course, it also updates the necessary arrays
- *
- * @param string name of the block containing the placeholder
- * @param string variable name
- * @param string block name
- * @access private
- */
- function _replacePlaceholder($parent, $placeholder, $block)
- {
- $this->_children[$parent][$block] = true;
- $this->_blockVariables[$parent]['__'.$block.'__'] = true;
- $this->_blocks[$parent] = str_replace($this->openingDelimiter.$placeholder.$this->closingDelimiter,
- $this->openingDelimiter.'__'.$block.'__'.$this->closingDelimiter,
- $this->_blocks[$parent] );
- unset($this->_blockVariables[$parent][$placeholder]);
- }
-
-
- /**
- * Generates a placeholder to replace an <!-- INCLUDE filename --> statement
- *
- * @access private
- * @param string filename
- * @param string current block name
- * @return string a placeholder
- */
- function _makeTrigger($filename, $block)
- {
- $name = 'trigger_' . substr(md5($filename . ' ' . uniqid($block)), 0, 10);
- $this->_triggers[$block][$name] = $filename;
- return $this->openingDelimiter . $name . $this->closingDelimiter;
- }
-
-
- /**
- * Replaces the "trigger" placeholders by the matching file contents.
- *
- * @see _makeTrigger(), addBlockfile()
- * @param array array ('trigger placeholder' => 'filename')
- * @return mixed SIGMA_OK on success, error object on failure
- * @access private
- */
- function _pullTriggers($triggers)
- {
- foreach ($triggers as $placeholder => $filename) {
- if (SIGMA_OK !== ($res = $this->addBlockfile($placeholder, $placeholder, $filename))) {
- return $res;
- }
- // we actually do not need the resultant block...
- $parents = $this->_findParentBlocks('__' . $placeholder . '__');
- // merge current block's children and variables with the parent's ones
- if (isset($this->_children[$placeholder])) {
- $this->_children[$parents[0]] = array_merge($this->_children[$parents[0]], $this->_children[$placeholder]);
- }
- $this->_blockVariables[$parents[0]] = array_merge($this->_blockVariables[$parents[0]], $this->_blockVariables[$placeholder]);
- if (isset($this->_functions[$placeholder])) {
- $this->_functions[$parents[0]] = array_merge($this->_functions[$parents[0]], $this->_functions[$placeholder]);
- }
- // substitute the block's contents into parent's
- $this->_blocks[$parents[0]] = str_replace(
- $this->openingDelimiter . '__' . $placeholder . '__' . $this->closingDelimiter,
- $this->_blocks[$placeholder],
- $this->_blocks[$parents[0]]
- );
- // remove the stuff that is no more needed
- unset($this->_blocks[$placeholder], $this->_blockVariables[$placeholder], $this->_children[$placeholder], $this->_functions[$placeholder]);
- unset($this->_children[$parents[0]][$placeholder], $this->_blockVariables[$parents[0]]['__' . $placeholder . '__']);
- }
- return SIGMA_OK;
- }
-
-
- /**
- * Builds a list of functions in a block.
- *
- * @access private
- * @param string Block name
- * @see _buildBlockVariables()
- */
- function _buildFunctionlist($block)
- {
- $template = $this->_blocks[$block];
- $this->_blocks[$block] = '';
-
- while (preg_match($this->functionRegExp, $template, $regs)) {
- $this->_blocks[$block] .= substr($template, 0, strpos($template, $regs[0]));
- $template = substr($template, strpos($template, $regs[0]) + strlen($regs[0]));
-
- $state = 1;
- $funcData = array(
- 'name' => $regs[1],
- 'args' => array()
- );
- for ($i = 0, $len = strlen($template); $i < $len; $i++) {
- $char = $template{$i};
- switch ($state) {
- case 0:
- case -1:
- break 2;
-
- case 1:
- $arg = '';
- if (')' == $char) {
- $state = 0;
- } elseif (',' == $char) {
- $error = 'Unexpected \',\'';
- $state = -1;
- } elseif ('\'' == $char || '"' == $char) {
- $quote = $char;
- $state = 5;
- } elseif (!ctype_space($char)) {
- $arg .= $char;
- $state = 3;
- }
- break;
-
- case 2:
- $arg = '';
- if (',' == $char || ')' == $char) {
- $error = 'Unexpected \'' . $char . '\'';
- $state = -1;
- } elseif ('\'' == $char || '"' == $char) {
- $quote = $char;
- $state = 5;
- } elseif (!ctype_space($char)) {
- $arg .= $char;
- $state = 3;
- }
- break;
-
- case 3:
- if (')' == $char) {
- $funcData['args'][] = rtrim($arg);
- $state = 0;
- } elseif (',' == $char) {
- $funcData['args'][] = rtrim($arg);
- $state = 2;
- } elseif ('\'' == $char || '"' == $char) {
- $quote = $char;
- $arg .= $char;
- $state = 4;
- } else {
- $arg .= $char;
- }
- break;
-
- case 4:
- $arg .= $char;
- if ($quote == $char) {
- $state = 3;
- }
- break;
-
- case 5:
- if ('\\' == $char) {
- $state = 6;
- } elseif ($quote == $char) {
- $state = 7;
- } else {
- $arg .= $char;
- }
- break;
-
- case 6:
- $arg .= $char;
- $state = 5;
- break;
-
- case 7:
- if (')' == $char) {
- $funcData['args'][] = $arg;
- $state = 0;
- } elseif (',' == $char) {
- $funcData['args'][] = $arg;
- $state = 2;
- } elseif (!ctype_space($char)) {
- $error = 'Unexpected \'' . $char . '\' (expected: \')\' or \',\')';
- $state = -1;
- }
- break;
- } // switch
- } // for
- if (0 != $state) {
- return $this->raiseError($this->errorMessage(SIGMA_CALLBACK_SYNTAX_ERROR, (empty($error)? 'Unexpected end of input': $error) . ' in ' . $regs[0] . substr($template, 0, $i)), SIGMA_CALLBACK_SYNTAX_ERROR);
- } else {
- $funcId = 'f' . substr(md5(serialize($funcData)), 0, 10);
- $template = substr($template, $i);
-
- $this->_blocks[$block] .= $this->openingDelimiter . '__function_' . $funcId . '__' . $this->closingDelimiter;
- $this->_blockVariables[$block]['__function_' . $funcId . '__'] = true;
- $this->_functions[$block][$funcId] = $funcData;
- }
- } // while
- $this->_blocks[$block] .= $template;
- return SIGMA_OK;
- } // end func _buildFunctionlist
-
-
- /**
- * Replaces an opening delimiter by a special string.
- *
- * Used to implement $_options['preserve_data'] logic
- *
- * @access private
- * @param string
- * @return string
- */
- function _preserveOpeningDelimiter($str)
- {
- return (false === strpos($str, $this->openingDelimiter))?
- $str:
- str_replace($this->openingDelimiter, $this->openingDelimiter . '%preserved%' . $this->closingDelimiter, $str);
- }
-
-
- /**
- * Quotes the string so that it can be used in Javascript string constants
- *
- * @access private
- * @param string
- * @return string
- */
- function _jsEscape($value)
- {
- return strtr($value, array(
- "\r" => '\r', "'" => "\\'", "\n" => '\n',
- '"' => '\"', "\t" => '\t', '\\' => '\\\\'
- ));
- }
-}
-?>
+++ /dev/null
-// +-----------------------------------------------------------------------+
-// | Copyright (c) 2002-2005, Richard Heyes, Harald Radi |
-// | All rights reserved. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | o Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | o Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution.|
-// | o The names of the authors may not be used to endorse or promote |
-// | products derived from this software without specific prior written |
-// | permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
-// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT |
-// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
-// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
-// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
-// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
-// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
-// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
-// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
-// | |
-// +-----------------------------------------------------------------------+
-// | Author: Richard Heyes <richard@phpguru.org> |
-// | Harald Radi <harald.radi@nme.at> |
-// +-----------------------------------------------------------------------+
-//
-// $Id: TreeMenu.js,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-/**
-* Function to create copies of objects which are
-* normally passed around by references (Arrays for example)
-*/
-function arrayCopy(input)
-{
- var output = new Array(input.length);
-
- for (i in input) {
- if (typeof(input[i]) == 'array') {
- output[i] = arrayCopy(input[i]);
- } else {
- output[i] = input[i];
- }
- }
-
- return output;
-}
-
-/**
-* TreeMenu class
-*/
- function TreeMenu(iconpath, myname, linkTarget, defaultClass, usePersistence, noTopLevelImages)
- {
- // Properties
- this.iconpath = iconpath;
- this.myname = myname;
- this.linkTarget = linkTarget;
- this.defaultClass = defaultClass;
- this.usePersistence = usePersistence;
- this.noTopLevelImages = noTopLevelImages;
- this.n = new Array();
- this.output = '';
-
- this.nodeRefs = new Array();
- this.branches = new Array();
- this.branchStatus = new Array();
- this.layerRelations = new Array();
- this.childParents = new Array();
- this.cookieStatuses = new Array();
-
- this.preloadImages();
- }
-
-/**
-* Adds a node to the tree
-*/
- TreeMenu.prototype.addItem = function (newNode)
- {
- newIndex = this.n.length;
- this.n[newIndex] = newNode;
-
- return this.n[newIndex];
- }
-
-/**
-* Preload images hack for Mozilla
-*/
- TreeMenu.prototype.preloadImages = function ()
- {
- var plustop = new Image; plustop.src = this.iconpath + '/plustop.gif';
- var plusbottom = new Image; plusbottom.src = this.iconpath + '/plusbottom.gif';
- var plus = new Image; plus.src = this.iconpath + '/plus.gif';
-
- var minustop = new Image; minustop.src = this.iconpath + '/minustop.gif';
- var minusbottom = new Image; minusbottom.src = this.iconpath + '/minusbottom.gif';
- var minus = new Image; minus.src = this.iconpath + '/minus.gif';
-
- var branchtop = new Image; branchtop.src = this.iconpath + '/branchtop.gif';
- var branchbottom = new Image; branchbottom.src = this.iconpath + '/branchbottom.gif';
- var branch = new Image; branch.src = this.iconpath + '/branch.gif';
-
- var linebottom = new Image; linebottom.src = this.iconpath + '/linebottom.gif';
- var line = new Image; line.src = this.iconpath + '/line.gif';
- }
-
-/**
-* Main function that draws the menu and assigns it
-* to the layer (or document.write()s it)
-*/
- TreeMenu.prototype.drawMenu = function ()// OPTIONAL ARGS: nodes = [], level = [], prepend = '', expanded = false, visbility = 'inline', parentLayerID = null
- {
- /**
- * Necessary variables
- */
- var output = '';
- var modifier = '';
- var layerID = '';
- var parentLayerID = '';
-
- /**
- * Parse any optional arguments
- */
- var nodes = arguments[0] ? arguments[0] : this.n
- var level = arguments[1] ? arguments[1] : [];
- var prepend = arguments[2] ? arguments[2] : '';
- var expanded = arguments[3] ? arguments[3] : false;
- var visibility = arguments[4] ? arguments[4] : 'inline';
- var parentLayerID = arguments[5] ? arguments[5] : null;
-
- var currentlevel = level.length;
-
- for (var i=0; i<nodes.length; i++) {
-
- level[currentlevel] = i+1;
- layerID = this.myname + '_' + 'node_' + this.implode('_', level);
-
- /**
- * Store this object in the nodeRefs array
- */
- this.nodeRefs[layerID] = nodes[i];
-
- /**
- * Store the child/parent relationship
- */
- this.childParents[layerID] = parentLayerID;
-
- /**
- * Gif modifier
- */
- if (i == 0 && parentLayerID == null) {
- modifier = nodes.length > 1 ? "top" : 'single';
- } else if(i == (nodes.length-1)) {
- modifier = "bottom";
- } else {
- modifier = "";
- }
-
- /**
- * Single root branch is always expanded
- */
- if (!this.doesMenu() || (parentLayerID == null && (nodes.length == 1 || this.noTopLevelImages))) {
- expanded = true;
-
- } else if (nodes[i].expanded) {
- expanded = true;
-
- } else {
- expanded = false;
- }
-
- /**
- * Make sure visibility is correct based on parent status
- */
- visibility = this.checkParentVisibility(layerID) ? visibility : 'none';
-
- /**
- * Setup branch status and build an indexed array
- * of branch layer ids
- */
- if (nodes[i].n.length > 0) {
- this.branchStatus[layerID] = expanded;
- this.branches[this.branches.length] = layerID;
- }
-
- /**
- * Setup toggle relationship
- */
- if (!this.layerRelations[parentLayerID]) {
- this.layerRelations[parentLayerID] = new Array();
- }
- this.layerRelations[parentLayerID][this.layerRelations[parentLayerID].length] = layerID;
-
- /**
- * Branch images
- */
- var gifname = nodes[i].n.length && this.doesMenu() && nodes[i].isDynamic ? (expanded ? 'minus' : 'plus') : 'branch';
- var iconName = expanded && nodes[i].expandedIcon ? nodes[i].expandedIcon : nodes[i].icon;
- var iconimg = nodes[i].icon ? this.stringFormat('<img src="{0}/{1}" align="top" id="icon_{2}">', this.iconpath, iconName, layerID) : '';
-
- /**
- * Add event handlers
- */
- var eventHandlers = "";
- for (j in nodes[i].events) {
- eventHandlers += this.stringFormat('{0}="{1}" ', j, nodes[i].events[j]);
- }
-
- /**
- * Build the html to write to the document
- * IMPORTANT:
- * document.write()ing the string: '<div style="display:...' will screw up nn4.x
- */
- var layerTag = this.doesMenu() ? this.stringFormat('<div id="{0}" style="display: {1}" class="{2}">', layerID, visibility, (nodes[i].cssClass ? nodes[i].cssClass : this.defaultClass)) : this.stringFormat('<div class="{0}">', nodes[i].cssClass ? nodes[i].cssClass : this.defaultClass);
- var onMDown = this.doesMenu() && nodes[i].n.length && nodes[i].isDynamic ? this.stringFormat('onmousedown="{0}.toggleBranch(\'{1}\', true)" style="cursor: pointer; cursor: hand"', this.myname, layerID) : '';
- var imgTag = this.stringFormat('<img src="{0}/{1}{2}.gif" align="top" border="0" name="img_{3}" {4}>', this.iconpath, gifname, modifier, layerID, onMDown);
- var linkTarget= nodes[i].linkTarget ? nodes[i].linkTarget : this.linkTarget;
- var linkStart = nodes[i].link ? this.stringFormat('<a href="{0}" target="{1}">', nodes[i].link, linkTarget) : '';
-
- var linkEnd = nodes[i].link ? '</a>' : '';
-
- this.output += this.stringFormat('{0}<nobr>{1}{2}{3}{4}<span {5}>{6}</span>{7}</nobr><br></div>',
- layerTag,
- prepend,
- parentLayerID == null && (nodes.length == 1 || this.noTopLevelImages) ? '' : imgTag,
- iconimg,
- linkStart,
- eventHandlers,
- nodes[i].title,
- linkEnd);
-
- /**
- * Traverse sub nodes ?
- */
- if (nodes[i].n.length) {
- /**
- * Determine what to prepend. If there is only one root
- * node then the prepend to pass to children is nothing.
- * Otherwise it depends on where we are in the tree.
- */
- if (parentLayerID == null && (nodes.length == 1 || this.noTopLevelImages)) {
- var newPrepend = '';
-
- } else if (i < (nodes.length - 1)) {
- var newPrepend = prepend + this.stringFormat('<img src="{0}/line.gif" align="top">', this.iconpath);
-
- } else {
- var newPrepend = prepend + this.stringFormat('<img src="{0}/linebottom.gif" align="top">', this.iconpath);
- }
-
- this.drawMenu(nodes[i].n,
- arrayCopy(level),
- newPrepend,
- nodes[i].expanded,
- expanded ? 'inline' : 'none',
- layerID);
- }
- }
- }
-
-/**
-* Writes the output generated by drawMenu() to the page
-*/
- TreeMenu.prototype.writeOutput = function ()
- {
- document.write(this.output);
- }
-
-/**
-* Toggles a branches visible status. Called from resetBranches()
-* and also when a +/- graphic is clicked.
-*/
- TreeMenu.prototype.toggleBranch = function (layerID, updateStatus) // OPTIONAL ARGS: fireEvents = true
- {
- var currentDisplay = this.getLayer(layerID).style.display;
- var newDisplay = (this.branchStatus[layerID] && currentDisplay == 'inline') ? 'none' : 'inline';
- var fireEvents = arguments[2] != null ? arguments[2] : true;
-
- for (var i=0; i<this.layerRelations[layerID].length; i++) {
-
- if (this.branchStatus[this.layerRelations[layerID][i]]) {
- this.toggleBranch(this.layerRelations[layerID][i], false);
- }
-
- this.getLayer(this.layerRelations[layerID][i]).style.display = newDisplay;
- }
-
- if (updateStatus) {
- this.branchStatus[layerID] = !this.branchStatus[layerID];
-
- /**
- * Persistence
- */
- if (this.doesPersistence() && !arguments[2] && this.usePersistence) {
- this.setExpandedStatusForCookie(layerID, this.branchStatus[layerID]);
- }
-
- /**
- * Fire custom events
- */
- if (fireEvents) {
- nodeObject = this.nodeRefs[layerID];
-
- if (nodeObject.ontoggle != null) {
- eval(nodeObject.ontoggle);
- }
-
- if (newDisplay == 'none' && nodeObject.oncollapse != null) {
- eval(nodeObject.oncollapse);
- } else if (newDisplay == 'inline' && nodeObject.onexpand != null){
- eval(nodeObject.onexpand);
- }
- }
-
- // Swap image
- this.swapImage(layerID);
- }
-
- // Swap icon
- this.swapIcon(layerID);
- }
-
-/**
-* Swaps the plus/minus branch images
-*/
- TreeMenu.prototype.swapImage = function (layerID)
- {
- var imgSrc = document.images['img_' + layerID].src;
-
- var re = /^(.*)(plus|minus)(bottom|top|single)?.gif$/
- if (matches = imgSrc.match(re)) {
-
- document.images['img_' + layerID].src = this.stringFormat('{0}{1}{2}{3}',
- matches[1],
- matches[2] == 'plus' ? 'minus' : 'plus',
- matches[3] ? matches[3] : '',
- '.gif');
- }
- }
-
-/**
-* Swaps the icon for the expanded icon if one
-* has been supplied.
-*/
- TreeMenu.prototype.swapIcon = function (layerID)
- {
- if (document.images['icon_' + layerID]) {
- var imgSrc = document.images['icon_' + layerID].src;
-
- if (this.nodeRefs[layerID].icon && this.nodeRefs[layerID].expandedIcon) {
- var newSrc = (imgSrc.indexOf(this.nodeRefs[layerID].expandedIcon) == -1 ? this.nodeRefs[layerID].expandedIcon : this.nodeRefs[layerID].icon);
-
- document.images['icon_' + layerID].src = this.iconpath + '/' + newSrc;
- }
- }
- }
-
-/**
-* Can the browser handle the dynamic menu?
-*/
- TreeMenu.prototype.doesMenu = function ()
- {
- return (is_ie4up || is_nav6up || is_gecko || is_opera7);
- }
-
-/**
-* Can the browser handle save the branch status
-*/
- TreeMenu.prototype.doesPersistence = function ()
- {
- return (is_ie4up || is_gecko || is_nav6up || is_opera7);
- }
-
-/**
-* Returns the appropriate layer accessor
-*/
- TreeMenu.prototype.getLayer = function (layerID)
- {
- if (is_ie4) {
- return document.all(layerID);
-
- } else if (document.getElementById(layerID)) {
- return document.getElementById(layerID);
-
- } else if (document.all && document.all(layerID)) {
- return document.all(layerID);
- }
- }
-
-/**
-* Save the status of the layer
-*/
- TreeMenu.prototype.setExpandedStatusForCookie = function (layerID, expanded)
- {
- this.cookieStatuses[layerID] = expanded;
- this.saveCookie();
- }
-
-/**
-* Load the status of the layer
-*/
- TreeMenu.prototype.getExpandedStatusFromCookie = function (layerID)
- {
- if (this.cookieStatuses[layerID]) {
- return this.cookieStatuses[layerID];
- }
-
- return false;
- }
-
-/**
-* Saves the cookie that holds which branches are expanded.
-* Only saves the details of the branches which are expanded.
-*/
- TreeMenu.prototype.saveCookie = function ()
- {
- var cookieString = new Array();
-
- for (var i in this.cookieStatuses) {
- if (this.cookieStatuses[i] == true) {
- cookieString[cookieString.length] = i;
- }
- }
-
- document.cookie = 'TreeMenuBranchStatus=' + cookieString.join(':');
- }
-
-/**
-* Reads cookie parses it for status info and
-* stores that info in the class member.
-*/
- TreeMenu.prototype.loadCookie = function ()
- {
- var cookie = document.cookie.split('; ');
-
- for (var i=0; i < cookie.length; i++) {
- var crumb = cookie[i].split('=');
- if ('TreeMenuBranchStatus' == crumb[0] && crumb[1]) {
- var expandedBranches = crumb[1].split(':');
- for (var j=0; j<expandedBranches.length; j++) {
- this.cookieStatuses[expandedBranches[j]] = true;
- }
- }
- }
- }
-
-/**
-* Reset branch status
-*/
- TreeMenu.prototype.resetBranches = function ()
- {
- if (!this.doesPersistence()) {
- return false;
- }
-
- this.loadCookie();
-
- for (var i=0; i<this.branches.length; i++) {
- var status = this.getExpandedStatusFromCookie(this.branches[i]);
- // Only update if it's supposed to be expanded and it's not already
- if (status == true && this.branchStatus[this.branches[i]] != true) {
- if (this.checkParentVisibility(this.branches[i])) {
- this.toggleBranch(this.branches[i], true, false);
- } else {
- this.branchStatus[this.branches[i]] = true;
- this.swapImage(this.branches[i]);
- }
- }
- }
- }
-
-/**
-* Checks whether a branch should be open
-* or not based on its parents' status
-*/
- TreeMenu.prototype.checkParentVisibility = function (layerID)
- {
- if (this.in_array(this.childParents[layerID], this.branches)
- && this.branchStatus[this.childParents[layerID]]
- && this.checkParentVisibility(this.childParents[layerID]) ) {
-
- return true;
-
- } else if (this.childParents[layerID] == null) {
- return true;
- }
-
- return false;
- }
-
-/**
-* New C# style string formatter
-*/
- TreeMenu.prototype.stringFormat = function (strInput)
- {
- var idx = 0;
-
- for (var i=1; i<arguments.length; i++) {
- while ((idx = strInput.indexOf('{' + (i - 1) + '}', idx)) != -1) {
- strInput = strInput.substring(0, idx) + arguments[i] + strInput.substr(idx + 3);
- }
- }
-
- return strInput;
- }
-
-/**
-* Also much adored, the PHP implode() function
-*/
- TreeMenu.prototype.implode = function (seperator, input)
- {
- var output = '';
-
- for (var i=0; i<input.length; i++) {
- if (i == 0) {
- output += input[i];
- } else {
- output += seperator + input[i];
- }
- }
-
- return output;
- }
-
-/**
-* Aah, all the old favourites are coming out...
-*/
- TreeMenu.prototype.in_array = function (item, arr)
- {
- for (var i=0; i<arr.length; i++) {
- if (arr[i] == item) {
- return true;
- }
- }
-
- return false;
- }
-
-/**
-* TreeNode Class
-*/
- function TreeNode(title, icon, link, expanded, isDynamic, cssClass, linkTarget, expandedIcon)
- {
- this.title = title;
- this.icon = icon;
- this.expandedIcon = expandedIcon;
- this.link = link;
- this.expanded = expanded;
- this.isDynamic = isDynamic;
- this.cssClass = cssClass;
- this.linkTarget = linkTarget;
- this.n = new Array();
- this.events = new Array();
- this.handlers = null;
- this.oncollapse = null;
- this.onexpand = null;
- this.ontoggle = null;
- }
-
-/**
-* Adds a node to an already existing node
-*/
- TreeNode.prototype.addItem = function (newNode)
- {
- newIndex = this.n.length;
- this.n[newIndex] = newNode;
-
- return this.n[newIndex];
- }
-
-/**
-* Sets an event for this particular node
-*/
- TreeNode.prototype.setEvent = function (eventName, eventHandler)
- {
- switch (eventName.toLowerCase()) {
- case 'onexpand':
- this.onexpand = eventHandler;
- break;
-
- case 'oncollapse':
- this.oncollapse = eventHandler;
- break;
-
- case 'ontoggle':
- this.ontoggle = eventHandler;
- break;
-
- default:
- this.events[eventName] = eventHandler;
- }
- }
-
-/**
-* That's the end of the tree classes. What follows is
-* the browser detection code.
-*/
-
-
-//<!--
-// Ultimate client-side JavaScript client sniff. Version 3.03
-// (C) Netscape Communications 1999-2001. Permission granted to reuse and distribute.
-// Revised 17 May 99 to add is_nav5up and is_ie5up (see below).
-// Revised 20 Dec 00 to add is_gecko and change is_nav5up to is_nav6up
-// also added support for IE5.5 Opera4&5 HotJava3 AOLTV
-// Revised 22 Feb 01 to correct Javascript Detection for IE 5.x, Opera 4,
-// correct Opera 5 detection
-// add support for winME and win2k
-// synch with browser-type-oo.js
-// Revised 26 Mar 01 to correct Opera detection
-// Revised 02 Oct 01 to add IE6 detection
-
-// Everything you always wanted to know about your JavaScript client
-// but were afraid to ask. Creates "is_" variables indicating:
-// (1) browser vendor:
-// is_nav, is_ie, is_opera, is_hotjava, is_webtv, is_TVNavigator, is_AOLTV
-// (2) browser version number:
-// is_major (integer indicating major version number: 2, 3, 4 ...)
-// is_minor (float indicating full version number: 2.02, 3.01, 4.04 ...)
-// (3) browser vendor AND major version number
-// is_nav2, is_nav3, is_nav4, is_nav4up, is_nav6, is_nav6up, is_gecko, is_ie3,
-// is_ie4, is_ie4up, is_ie5, is_ie5up, is_ie5_5, is_ie5_5up, is_ie6, is_ie6up, is_hotjava3, is_hotjava3up,
-// is_opera2, is_opera3, is_opera4, is_opera5, is_opera5up
-// (4) JavaScript version number:
-// is_js (float indicating full JavaScript version number: 1, 1.1, 1.2 ...)
-// (5) OS platform and version:
-// is_win, is_win16, is_win32, is_win31, is_win95, is_winnt, is_win98, is_winme, is_win2k
-// is_os2
-// is_mac, is_mac68k, is_macppc
-// is_unix
-// is_sun, is_sun4, is_sun5, is_suni86
-// is_irix, is_irix5, is_irix6
-// is_hpux, is_hpux9, is_hpux10
-// is_aix, is_aix1, is_aix2, is_aix3, is_aix4
-// is_linux, is_sco, is_unixware, is_mpras, is_reliant
-// is_dec, is_sinix, is_freebsd, is_bsd
-// is_vms
-//
-// See http://www.it97.de/JavaScript/JS_tutorial/bstat/navobj.html and
-// http://www.it97.de/JavaScript/JS_tutorial/bstat/Browseraol.html
-// for detailed lists of userAgent strings.
-//
-// Note: you don't want your Nav4 or IE4 code to "turn off" or
-// stop working when new versions of browsers are released, so
-// in conditional code forks, use is_ie5up ("IE 5.0 or greater")
-// is_opera5up ("Opera 5.0 or greater") instead of is_ie5 or is_opera5
-// to check version in code which you want to work on future
-// versions.
-
-/**
-* Severly curtailed all this as only certain elements
-* are required by TreeMenu, specifically:
-* o is_ie4up
-* o is_nav6up
-* o is_gecko
-*/
-
- // convert all characters to lowercase to simplify testing
- var agt=navigator.userAgent.toLowerCase();
-
- // *** BROWSER VERSION ***
- // Note: On IE5, these return 4, so use is_ie5up to detect IE5.
- var is_major = parseInt(navigator.appVersion);
- var is_minor = parseFloat(navigator.appVersion);
-
- // Note: Opera and WebTV spoof Navigator. We do strict client detection.
- // If you want to allow spoofing, take out the tests for opera and webtv.
- var is_nav = ((agt.indexOf('mozilla')!=-1) && (agt.indexOf('spoofer')==-1)
- && (agt.indexOf('compatible') == -1) && (agt.indexOf('opera')==-1)
- && (agt.indexOf('webtv')==-1) && (agt.indexOf('hotjava')==-1));
- var is_nav6up = (is_nav && (is_major >= 5));
- var is_gecko = (agt.indexOf('gecko') != -1);
-
-
- var is_ie = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
- var is_ie4 = (is_ie && (is_major == 4) && (agt.indexOf("msie 4")!=-1) );
- var is_ie4up = (is_ie && (is_major >= 4));
-
- var is_opera = (agt.indexOf("opera") != -1);
- var is_opera7 = (is_opera && is_major >= 7) || agt.indexOf("opera 7") != -1;
-
- // Patch from Harald Fielker
- if (agt.indexOf('konqueror') != -1) {
- var is_nav = false;
- var is_nav6up = false;
- var is_gecko = false;
- var is_ie = true;
- var is_ie4 = true;
- var is_ie4up = true;
- }
-//--> end hide JavaScript
+++ /dev/null
-<?php
-// +-----------------------------------------------------------------------+
-// | Copyright (c) 2002-2005, Richard Heyes, Harald Radi |
-// | All rights reserved. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | o Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | o Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution.|
-// | o The names of the authors may not be used to endorse or promote |
-// | products derived from this software without specific prior written |
-// | permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
-// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT |
-// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
-// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
-// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
-// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
-// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
-// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
-// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
-// | |
-// +-----------------------------------------------------------------------+
-// | Author: Richard Heyes <http://www.phpguru.org/> |
-// | Harald Radi <harald.radi@nme.at> |
-// +-----------------------------------------------------------------------+
-//
-// $Id: TreeMenu.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-/**
-* HTML_TreeMenu Class
-*
-* A simple couple of PHP classes and some not so simple
-* Jabbascript which produces a tree menu. In IE this menu
-* is dynamic, with branches being collapsable. In IE5+ the
-* status of the collapsed/open branches persists across page
-* refreshes.In any other browser the tree is static. Code is
-* based on work of Harald Radi.
-*
-* Usage.
-*
-* After installing the package, copy the example php script to
-* your servers document root. Also place the TreeMenu.js and the
-* images folder in the same place. Running the script should
-* then produce the tree.
-*
-* Thanks go to Chip Chapin (http://www.chipchapin.com) for many
-* excellent ideas and improvements.
-*
-* @author Richard Heyes <richard@php.net>
-* @author Harald Radi <harald.radi@nme.at>
-* @access public
-* @package HTML_TreeMenu
-*/
-
-class HTML_TreeMenu
-{
- /**
- * Indexed array of subnodes
- * @var array
- */
- var $items;
-
- /**
- * Constructor
- *
- * @access public
- */
- function HTML_TreeMenu()
- {
- // Not much to do here :(
- }
-
- /**
- * This function adds an item to the the tree.
- *
- * @access public
- * @param object $node The node to add. This object should be
- * a HTML_TreeNode object.
- * @return object Returns a reference to the new node inside
- * the tree.
- */
- function &addItem(&$node)
- {
- $this->items[] = &$node;
- return $this->items[count($this->items) - 1];
- }
-
- /**
- * Import method for creating HTML_TreeMenu objects/structures
- * out of existing tree objects/structures. Currently supported
- * are Wolfram Kriesings' PEAR Tree class, and Richard Heyes' (me!)
- * Tree class (available here: http://www.phpguru.org/). This
- * method is intended to be used statically, eg:
- * $treeMenu = &HTML_TreeMenu::createFromStructure($myTreeStructureObj);
- *
- * @param array $params An array of parameters that determine
- * how the import happens. This can consist of:
- * structure => The tree structure
- * type => The type of the structure, currently
- * can be either 'heyes' or 'kriesing'
- * nodeOptions => Default options for each node
- *
- * @return object The resulting HTML_TreeMenu object
- */
- function createFromStructure($params)
- {
- if (!isset($params['nodeOptions'])) {
- $params['nodeOptions'] = array();
- }
-
- switch (@$params['type']) {
-
- /**
- * Wolfram Kriesings' PEAR Tree class
- */
- case 'kriesing':
- $className = strtolower(get_class($params['structure']->dataSourceClass));
- $isXMLStruct = strpos($className,'_xml') !== false ? true : false;
-
- // Get the entire tree, the $nodes are sorted like in the tree view
- // from top to bottom, so we can easily put them in the nodes
- $nodes = $params['structure']->getNode();
-
- // Make a new menu and fill it with the values from the tree
- $treeMenu = new HTML_TreeMenu();
- $curNode[0] = &$treeMenu; // we need the current node as the reference to the
-
- foreach ( $nodes as $aNode ) {
- $events = array();
- $data = array();
-
- // In an XML, all the attributes are saved in an array, but since they might be
- // used as the parameters, we simply extract them here if we handle an XML-structure
- if ( $isXMLStruct && sizeof($aNode['attributes']) ){
- foreach ( $aNode['attributes'] as $key=>$val ) {
- if ( !$aNode[$key] ) { // dont overwrite existing values
- $aNode[$key] = $val;
- }
- }
- }
-
- // Process all the data that are saved in $aNode and put them in the data and/or events array
- foreach ( $aNode as $key=>$val ) {
- if ( !is_array($val) ) {
- // Dont get the recursive data in here! they are always arrays
- if ( substr($key,0,2) == 'on' ){ // get the events
- $events[$key] = $val;
- }
-
- // I put it in data too, so in case an options starts with 'on' its also passed to the node ... not too cool i know
- $data[$key] = $val;
- }
- }
-
- // Normally the text is in 'name' in the Tree class, so we check both but 'text' is used if found
- $data['text'] = $aNode['text'] ? $aNode['text'] : $aNode['name'];
-
- // Add the item to the proper node
- $thisNode = &$curNode[$aNode['level']]->addItem( new HTML_TreeNode( $data , $events ) );
- $curNode[$aNode['level']+1] = &$thisNode;
- }
- break;
-
- /**
- * Richard Heyes' (me!) second (array based) Tree class
- */
- case 'heyes_array':
- // Need to create a HTML_TreeMenu object ?
- if (!isset($params['treeMenu'])) {
- $treeMenu = &new HTML_TreeMenu();
- $parentID = 0;
- } else {
- $treeMenu = &$params['treeMenu'];
- $parentID = $params['parentID'];
- }
-
- // Loop thru the trees nodes
- foreach ($params['structure']->getChildren($parentID) as $nodeID) {
- $data = $params['structure']->getData($nodeID);
- $parentNode = &$treeMenu->addItem(new HTML_TreeNode(array_merge($params['nodeOptions'], $data)));
-
- // Recurse ?
- if ($params['structure']->hasChildren($nodeID)) {
- $recurseParams['type'] = 'heyes_array';
- $recurseParams['parentID'] = $nodeID;
- $recurseParams['nodeOptions'] = $params['nodeOptions'];
- $recurseParams['structure'] = &$params['structure'];
- $recurseParams['treeMenu'] = &$parentNode;
- HTML_TreeMenu::createFromStructure($recurseParams);
- }
- }
-
- break;
-
- /**
- * Richard Heyes' (me!) original OO based Tree class
- */
- case 'heyes':
- default:
- // Need to create a HTML_TreeMenu object ?
- if (!isset($params['treeMenu'])) {
- $treeMenu = &new HTML_TreeMenu();
- } else {
- $treeMenu = &$params['treeMenu'];
- }
-
- // Loop thru the trees nodes
- foreach ($params['structure']->nodes->nodes as $node) {
- $tag = $node->getTag();
- $parentNode = &$treeMenu->addItem(new HTML_TreeNode(array_merge($params['nodeOptions'], $tag)));
-
- // Recurse ?
- if (!empty($node->nodes->nodes)) {
- $recurseParams['structure'] = $node;
- $recurseParams['nodeOptions'] = $params['nodeOptions'];
- $recurseParams['treeMenu'] = &$parentNode;
- HTML_TreeMenu::createFromStructure($recurseParams);
- }
- }
- break;
-
- }
-
- return $treeMenu;
- }
-
- /**
- * Creates a treeMenu from XML. The structure of your XML should be
- * like so:
- *
- * <treemenu>
- * <node text="First node" icon="folder.gif" expandedIcon="folder-expanded.gif" />
- * <node text="Second node" icon="folder.gif" expandedIcon="folder-expanded.gif">
- * <node text="Sub node" icon="folder.gif" expandedIcon="folder-expanded.gif" />
- * </node>
- * <node text="Third node" icon="folder.gif" expandedIcon="folder-expanded.gif">
- * </treemenu>
- *
- * Any of the options you can supply to the HTML_TreeNode constructor can be supplied as
- * attributes to the <node> tag. If there are no subnodes for a particular node, you can
- * use the XML shortcut <node ... /> instead of <node ... ></node>. The $xml argument can
- * be either the XML as a string, or an pre-created XML_Tree object. Also, this method
- * REQUIRES my own Tree class to work (http://www.phpguru.org/static/tree.html). If this has not
- * been include()ed or require()ed this method will die().
- *
- * @param mixed $xml This can be either a string containing the XML, or an XML_Tree object
- * (the PEAR::XML_Tree package).
- * @return object The HTML_TreeMenu object
- */
- function createFromXML($xml)
- {
- if (!class_exists('Tree')) {
- die('Could not find Tree class');
- }
-
- // Supplied $xml is a string
- if (is_string($xml)) {
- require_once('XML/Tree.php');
- $xmlTree = &new XML_Tree();
- $xmlTree->getTreeFromString($xml);
-
- // Supplied $xml is an XML_Tree object
- } else {
- $xmlTree = $xml;
- }
-
- // Now process the XML_Tree object, setting the XML attributes
- // to be the tag data (with out the XML tag name or contents).
- $treeStructure = Tree::createFromXMLTree($xmlTree, true);
- $treeStructure->nodes->traverse(create_function('&$node', '$tagData = $node->getTag(); $node->setTag($tagData["attributes"]);'));
-
-
- return HTML_TreeMenu::createFromStructure(array('structure' => $treeStructure));
- }
-} // HTML_TreeMenu
-
-
-/**
-* HTML_TreeNode class
-*
-* This class is supplementary to the above and provides a way to
-* add nodes to the tree. A node can have other nodes added to it.
-*
-* @author Richard Heyes <richard@php.net>
-* @author Harald Radi <harald.radi@nme.at>
-* @access public
-* @package HTML_TreeMenu
-*/
-class HTML_TreeNode
-{
- /**
- * The text for this node.
- * @var string
- */
- var $text;
-
- /**
- * The link for this node.
- * @var string
- */
- var $link;
-
- /**
- * The icon for this node.
- * @var string
- */
- var $icon;
-
- /**
- * The icon to show when expanded for this node.
- * @var string
- */
- var $expandedIcon;
-
- /**
- * The css class for this node
- * @var string
- */
- var $cssClass;
-
- /**
- * The link target for this node
- * @var string
- */
- var $linkTarget;
-
- /**
- * Indexed array of subnodes
- * @var array
- */
- var $items;
-
- /**
- * Whether this node is expanded or not
- * @var bool
- */
- var $expanded;
-
- /**
- * Whether this node is dynamic or not
- * @var bool
- */
- var $isDynamic;
-
- /**
- * Should this node be made visible?
- * @var bool
- */
- var $ensureVisible;
-
- /**
- * The parent node. Null if top level
- * @var object
- */
- var $parent;
-
- /**
- * Javascript event handlers;
- * @var array
- */
- var $events;
-
- /**
- * Constructor
- *
- * @access public
- * @param array $options An array of options which you can pass to change
- * the way this node looks/acts. This can consist of:
- * o text The title of the node, defaults to blank
- * o link The link for the node, defaults to blank
- * o icon The icon for the node, defaults to blank
- * o expandedIcon The icon to show when the node is expanded
- * o cssClass The CSS class for this node, defaults to blank
- * o expanded The default expanded status of this node, defaults to false
- * This doesn't affect non dynamic presentation types
- * o linkTarget Target for the links. Defaults to linkTarget of the
- * HTML_TreeMenu_Presentation.
- * o isDynamic If this node is dynamic or not. Only affects
- * certain presentation types.
- * o ensureVisible If true this node will be made visible despite the expanded
- * settings, and client side persistence. Will not affect
- * some presentation styles, such as Listbox. Default is false
- * @param array $events An array of javascript events and the corresponding event handlers.
- * Additionally to the standard javascript events you can specify handlers
- * for the 'onexpand', 'oncollapse' and 'ontoggle' events which will be fired
- * whenever a node is collapsed and/or expanded.
- */
- function HTML_TreeNode($options = array(), $events = array())
- {
- $this->text = '';
- $this->link = '';
- $this->icon = '';
- $this->expandedIcon = '';
- $this->cssClass = '';
- $this->expanded = false;
- $this->isDynamic = true;
- $this->ensureVisible = false;
- $this->linkTarget = null;
-
- $this->parent = null;
- $this->events = $events;
-
- foreach ($options as $option => $value) {
- $this->$option = $value;
- }
- }
-
- /**
- * Allows setting of various parameters after the initial
- * constructor call. Possible options you can set are:
- * o text
- * o link
- * o icon
- * o cssClass
- * o expanded
- * o isDynamic
- * o ensureVisible
- * ie The same options as in the constructor
- *
- * @access public
- * @param string $option Option to set
- * @param string $value Value to set the option to
- */
- function setOption($option, $value)
- {
- $this->$option = $value;
- }
-
- /**
- * Adds a new subnode to this node.
- *
- * @access public
- * @param object $node The new node
- */
- function &addItem(&$node)
- {
- $node->parent = &$this;
- $this->items[] = &$node;
-
- /**
- * If the subnode has ensureVisible set it needs
- * to be handled, and all parents set accordingly.
- */
- if ($node->ensureVisible) {
- $this->_ensureVisible();
- }
-
- return $this->items[count($this->items) - 1];
- }
-
- /**
- * Private function to handle ensureVisible stuff
- *
- * @access private
- */
- function _ensureVisible()
- {
- $this->ensureVisible = true;
- $this->expanded = true;
-
- if (!is_null($this->parent)) {
- $this->parent->_ensureVisible();
- }
- }
-} // HTML_TreeNode
-
-
-/**
-* HTML_TreeMenu_Presentation class
-*
-* Base class for other presentation classes to
-* inherit from.
-*/
-class HTML_TreeMenu_Presentation
-{
- /**
- * The TreeMenu structure
- * @var object
- */
- var $menu;
-
- /**
- * Base constructor simply sets the menu object
- *
- * @param object $structure The menu structure
- */
- function HTML_TreeMenu_Presentation(&$structure)
- {
- $this->menu = &$structure;
- }
-
- /**
- * Prints the HTML generated by the toHTML() method.
- * toHTML() must therefore be defined by the derived
- * class.
- *
- * @access public
- * @param array Options to set. Any options taken by
- * the presentation class can be specified
- * here.
- */
- function printMenu($options = array())
- {
- foreach ($options as $option => $value) {
- $this->$option = $value;
- }
-
- echo $this->toHTML();
- }
-}
-
-
-/**
-* HTML_TreeMenu_DHTML class
-*
-* This class is a presentation class for the tree structure
-* created using the TreeMenu/TreeNode. It presents the
-* traditional tree, static for browsers that can't handle
-* the DHTML.
-*/
-class HTML_TreeMenu_DHTML extends HTML_TreeMenu_Presentation
-{
- /**
- * Dynamic status of the treemenu. If true (default) this has no effect. If
- * false it will override all dynamic status vars and set the menu to be
- * fully expanded an non-dynamic.
- */
- var $isDynamic;
-
- /**
- * Path to the images
- * @var string
- */
- var $images;
-
- /**
- * Target for the links generated
- * @var string
- */
- var $linkTarget;
-
- /**
- * Whether to use clientside persistence or not
- * @var bool
- */
- var $usePersistence;
-
- /**
- * The default CSS class for the nodes
- */
- var $defaultClass;
-
- /**
- * Whether to skip first level branch images
- * @var bool
- */
- var $noTopLevelImages;
-
- /**
- * Name of Jabbascript object to use
- * @var string
- */
- var $jsObjectName;
-
- /**
- * Constructor, takes the tree structure as
- * an argument and an array of options which
- * can consist of:
- * o images - The path to the images folder. Defaults to "images"
- * o linkTarget - The target for the link. Defaults to "_self"
- * o defaultClass - The default CSS class to apply to a node. Default is none.
- * o usePersistence - Whether to use clientside persistence. This persistence
- * is achieved using cookies. Default is true.
- * o noTopLevelImages - Whether to skip displaying the first level of images if
- * there is multiple top level branches.
- * o maxDepth - The maximum depth of indentation. Useful for ensuring
- * deeply nested trees don't go way off to the right of your
- * page etc. Defaults to no limit.
- * o jsObjectName - Name to use for jabbascript object. Set this if you have
- * different menus that should maintain their persistence
- * information separately.
- *
- * And also a boolean for whether the entire tree is dynamic or not.
- * This overrides any perNode dynamic settings.
- *
- * @param object $structure The menu structure
- * @param array $options Array of options
- * @param bool $isDynamic Whether the tree is dynamic or not
- */
- function HTML_TreeMenu_DHTML(&$structure, $options = array(), $isDynamic = true)
- {
- $this->HTML_TreeMenu_Presentation($structure);
- $this->isDynamic = $isDynamic;
-
- // Defaults
- $this->images = 'images';
- $this->maxDepth = 0; // No limit
- $this->linkTarget = '_self';
- $this->jsObjectName = 'objTreeMenu';
- $this->defaultClass = '';
- $this->usePersistence = true;
- $this->noTopLevelImages = false;
-
- foreach ($options as $option => $value) {
- $this->$option = $value;
- }
- }
-
- /**
- * Returns the HTML for the menu. This method can be
- * used instead of printMenu() to use the menu system
- * with a template system.
- *
- * @access public
- * @return string The HTML for the menu
- */
- function toHTML()
- {
- static $count = 0;
- $menuObj = $this->jsObjectName . '_' . ++$count;
-
- $html = "\n";
- $html .= '<script type="text/javascript">' . "\n//<![CDATA[\n\t";
- $html .= sprintf('%s = new TreeMenu("%s", "%s", "%s", "%s", %s, %s);',
- $menuObj,
- $this->images,
- $menuObj,
- $this->linkTarget,
- $this->defaultClass,
- $this->usePersistence ? 'true' : 'false',
- $this->noTopLevelImages ? 'true' : 'false');
-
- $html .= "\n";
-
- /**
- * Loop through subnodes
- */
- if (isset($this->menu->items)) {
- for ($i=0; $i<count($this->menu->items); $i++) {
- $html .= $this->_nodeToHTML($this->menu->items[$i], $menuObj);
- }
- }
-
- $html .= sprintf("\n\t%s.drawMenu();", $menuObj);
- $html .= sprintf("\n\t%s.writeOutput();", $menuObj);
-
- if ($this->usePersistence && $this->isDynamic) {
- $html .= sprintf("\n\t%s.resetBranches();", $menuObj);
- }
- $html .= "\n// ]]>\n</script>";
-
- return $html;
- }
-
- /**
- * Prints a node of the menu
- *
- * @access private
- */
- function _nodeToHTML($nodeObj, $prefix, $return = 'newNode', $currentDepth = 0, $maxDepthPrefix = null)
- {
- $prefix = empty($maxDepthPrefix) ? $prefix : $maxDepthPrefix;
-
- $expanded = $this->isDynamic ? ($nodeObj->expanded ? 'true' : 'false') : 'true';
- $isDynamic = $this->isDynamic ? ($nodeObj->isDynamic ? 'true' : 'false') : 'false';
- $html = sprintf("\t %s = %s.addItem(new TreeNode('%s', %s, %s, %s, %s, '%s', '%s', %s));\n",
- $return,
- $prefix,
- str_replace("'", "\\'", $nodeObj->text),
- !empty($nodeObj->icon) ? "'" . $nodeObj->icon . "'" : 'null',
- !empty($nodeObj->link) ? "'" . $nodeObj->link . "'" : 'null',
- $expanded,
- $isDynamic,
- $nodeObj->cssClass,
- $nodeObj->linkTarget,
- !empty($nodeObj->expandedIcon) ? "'" . $nodeObj->expandedIcon . "'" : 'null');
-
- foreach ($nodeObj->events as $event => $handler) {
- $html .= sprintf("\t %s.setEvent('%s', '%s');\n",
- $return,
- $event,
- str_replace(array("\r", "\n", "'"), array('\r', '\n', "\'"), $handler));
- }
-
- if ($this->maxDepth > 0 AND $currentDepth == $this->maxDepth) {
- $maxDepthPrefix = $prefix;
- }
-
- /**
- * Loop through subnodes
- */
- if (!empty($nodeObj->items)) {
- for ($i=0; $i<count($nodeObj->items); $i++) {
- $html .= $this->_nodeToHTML($nodeObj->items[$i], $return, $return . '_' . ($i + 1), $currentDepth + 1, $maxDepthPrefix);
- }
- }
-
- return $html;
- }
-} // End class HTML_TreeMenu_DHTML
-
-
-/**
-* HTML_TreeMenu_Listbox class
-*
-* This class presents the menu as a listbox
-*/
-class HTML_TreeMenu_Listbox extends HTML_TreeMenu_Presentation
-{
- /**
- * The text that is displayed in the first option
- * @var string
- */
- var $promoText;
-
- /**
- * The character used for indentation
- * @var string
- */
- var $indentChar;
-
- /**
- * How many of the indent chars to use
- * per indentation level
- * @var integer
- */
- var $indentNum;
-
- /**
- * Target for the links generated
- * @var string
- */
- var $linkTarget;
-
- /**
- * Constructor
- *
- * @param object $structure The menu structure
- * @param array $options Options whic affect the display of the listbox.
- * These can consist of:
- * o promoText The text that appears at the the top of the listbox
- * Defaults to "Select..."
- * o indentChar The character to use for indenting the nodes
- * Defaults to " "
- * o indentNum How many of the indentChars to use per indentation level
- * Defaults to 2
- * o linkTarget Target for the links. Defaults to "_self"
- * o submitText Text for the submit button. Defaults to "Go"
- */
- function HTML_TreeMenu_Listbox($structure, $options = array())
- {
- $this->HTML_TreeMenu_Presentation($structure);
-
- $this->promoText = 'Select...';
- $this->indentChar = ' ';
- $this->indentNum = 2;
- $this->linkTarget = '_self';
- $this->submitText = 'Go';
-
- foreach ($options as $option => $value) {
- $this->$option = $value;
- }
- }
-
- /**
- * Returns the HTML generated
- */
- function toHTML()
- {
- static $count = 0;
- $nodeHTML = '';
-
- /**
- * Loop through subnodes
- */
- if (isset($this->menu->items)) {
- for ($i=0; $i<count($this->menu->items); $i++) {
- $nodeHTML .= $this->_nodeToHTML($this->menu->items[$i]);
- }
- }
-
- return sprintf('<form target="%s" action="" onsubmit="var link = this.%s.options[this.%s.selectedIndex].value; if (link) {this.action = link; return true} else return false"><select name="%s"><option value="">%s</option>%s</select> <input type="submit" value="%s" /></form>',
- $this->linkTarget,
- 'HTML_TreeMenu_Listbox_' . ++$count,
- 'HTML_TreeMenu_Listbox_' . $count,
- 'HTML_TreeMenu_Listbox_' . $count,
- $this->promoText,
- $nodeHTML,
- $this->submitText);
- }
-
- /**
- * Returns HTML for a single node
- *
- * @access private
- */
- function _nodeToHTML($node, $prefix = '')
- {
- $html = sprintf('<option value="%s">%s%s</option>', $node->link, $prefix, $node->text);
-
- /**
- * Loop through subnodes
- */
- if (isset($node->items)) {
- for ($i=0; $i<count($node->items); $i++) {
- $html .= $this->_nodeToHTML($node->items[$i], $prefix . str_repeat($this->indentChar, $this->indentNum));
- }
- }
-
- return $html;
- }
-} // End class HTML_TreeMenu_Listbox
-?>
+++ /dev/null
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Stig Bakken <ssb@fast.no> |
-// | |
-// +----------------------------------------------------------------------+
-//
-// $Id: HTTP.php,v 1.1.1.1 2008/04/28 15:20:46 jamie Exp $
-//
-// HTTP utility functions.
-//
-
-class HTTP
-{
- /**
- * Format a RFC compliant HTTP header. This function
- * honors the "y2k_compliance" php.ini directive.
- *
- * @param int $time UNIX timestamp
- *
- * @return mixed HTTP date string, or false for an invalid timestamp.
- *
- * @author Stig Bakken <ssb@fast.no>
- * @author Sterling Hughes <sterling@php.net>
- */
- function Date($time)
- {
- /* If we're y2k compliant, use the newer, reccomended RFC 822
- format */
- if (ini_get("y2k_compliance") == true) {
- return gmdate("D, d M Y H:i:s \G\M\T", $time);
- }
- /* Use RFC-850 which supports two character year numbers */
- else {
- return gmdate("F, d-D-y H:i:s \G\M\T", $time);
- }
- }
-
- /**
- * Negotiate language with the user's browser through the
- * Accept-Language HTTP header or the user's host address.
- * Language codes are generally in the form "ll" for a language
- * spoken in only one country, or "ll-CC" for a language spoken in
- * a particular country. For example, U.S. English is "en-US",
- * while British English is "en-UK". Portugese as spoken in
- * Portugal is "pt-PT", while Brazilian Portugese is "pt-BR".
- * Two-letter country codes can be found in the ISO 3166 standard.
- *
- * Quantities in the Accept-Language: header are supported, for
- * example:
- *
- * Accept-Language: en-UK;q=0.7, en-US;q=0.6, no;q=1.0, dk;q=0.8
- *
- * @param array $supported an associative array indexed by language
- * codes (country codes) supported by the application. Values
- * must evaluate to true.
- *
- * @param string $default the default language to use if none is found
- * during negotiation, defaults to "en-US" for U.S. English
- *
- * @return string the negotiated language result
- *
- * @author Stig Bakken <ssb@fast.no>
- */
- function negotiateLanguage(&$supported, $default = 'en-US')
- {
- global $HTTP_SERVER_VARS;
-
- $supported = array_change_key_case($supported, CASE_LOWER);
-
- /* If the client has sent an Accept-Language: header, see if
- * it contains a language we support.
- */
- if (isset($HTTP_SERVER_VARS['HTTP_ACCEPT_LANGUAGE'])) {
- $accepted = split(',[[:space:]]*', $HTTP_SERVER_VARS['HTTP_ACCEPT_LANGUAGE']);
- for ($i = 0; $i < count($accepted); $i++) {
- if (eregi('^([a-z_-]+);[[:space:]]*q=([0-9\.]+)', $accepted[$i], $arr)) {
- $q = (double)$arr[2];
- $l = $arr[1];
- } else {
- $q = 42;
- $l = strtolower($accepted[$i]);
- }
-
- if (!empty($supported[$l]) && ($q > 0.0)) {
- if ($q == 42) {
- return $l;
- }
- $candidates[$l] = $q;
- }
- }
- if (isset($candidates)) {
- arsort($candidates);
- reset($candidates);
- return key($candidates);
- }
- }
-
- /* Check for a valid language code in the top-level domain of
- * the client's host address.
- */
- if (isset($HTTP_SERVER_VARS['REMOTE_HOST']) &&
- ereg("\.[^\.]+$", $HTTP_SERVER_VARS['REMOTE_HOST'], $arr)) {
- $lang = strtolower($arr[1]);
- if (!empty($supported[$lang])) {
- return $lang;
- }
- }
-
- return $default;
- }
-
- /**
- * Sends a "HEAD" HTTP command to a server and returns the headers
- * as an associative array. Example output could be:
- * Array
- * (
- * [response_code] => 200 // The HTTP response code
- * [response] => HTTP/1.1 200 OK // The full HTTP response string
- * [Date] => Fri, 11 Jan 2002 01:41:44 GMT
- * [Server] => Apache/1.3.20 (Unix) PHP/4.1.1
- * [X-Powered-By] => PHP/4.1.1
- * [Connection] => close
- * [Content-Type] => text/html
- * )
- *
- * @param string $url A valid url, for ex: http://pear.php.net/credits.php
- * @return mixed Assoc array or PEAR error
- *
- * @author Tomas V.V.Cox <cox@idecnet.com>
- */
- function head($url)
- {
- $purl = parse_url($url);
- $port = (isset($purl['port'])) ? $purl['port'] : 80;
- $fp = fsockopen($purl['host'], $port, $errno, $errstr, 10);
- if (!$fp) {
- include_once "PEAR.php";
- return PEAR::raiseError("HTTP::head Error $errstr ($erno)");
- }
- $path = (!empty($purl['path'])) ? $purl['path'] : '/';
-
- fputs($fp, "HEAD $path HTTP/1.0\r\n");
- fputs($fp, "Host: " . $purl['host'] . "\r\n");
- fputs($fp, "Connection: close\r\n\r\n");
-
- $response = rtrim(fgets($fp, 4096));
- if(preg_match("|^HTTP/[^\s]*\s(.*?)\s|", $response, $status)) {
- $headers['response_code'] = $status[1];
- }
- $headers['response'] = $response;
-
- while ($line = fgets($fp, 4096)) {
- if (!trim($line)) {
- break;
- }
- if (($pos = strpos($line, ':')) !== false) {
- $header = substr($line, 0, $pos);
- $value = trim(substr($line, $pos + 1));
- $headers[$header] = $value;
- }
- }
- fclose($fp);
- return $headers;
- }
-
- /**
- * This function redirects the client. This is done by issuing
- * a Location: header and exiting.
- *
- * @author Richard Heyes <richard@php.net>
- * @param string $url URL where the redirect should go to
- */
- function redirect($url)
- {
- global $HTTP_SERVER_VARS;
- if (!preg_match('/^(https?|ftp):\/\//', $url)) {
- $server = 'http' . (@$HTTP_SERVER_VARS['HTTPS'] == 'on' ? 's' : '') . '://' . $HTTP_SERVER_VARS['SERVER_NAME'];
- if ($HTTP_SERVER_VARS['SERVER_PORT'] != 80 &&
- $HTTP_SERVER_VARS['SERVER_PORT'] != 443) {
- $server .= ':' . $HTTP_SERVER_VARS['SERVER_PORT'];
- }
-
- $path = dirname($HTTP_SERVER_VARS['PHP_SELF']);
- if ($url{0} != '/') {
- $path .= $url;
- $server .= dirname($HTTP_SERVER_VARS['PHP_SELF']);
- $url = $server . '/' . preg_replace('!^\./!', '', $url);
- } else {
- $url = $server . $url;
- }
- }
-
- header('Location: ' . $url);
- exit;
- }
-}
-?>
+++ /dev/null
-<?php
-/**
- * +-----------------------------------------------------------------------+
- * | Copyright (c) 2004, Tony Bibbs |
- * | All rights reserved. |
- * | |
- * | Redistribution and use in source and binary forms, with or without |
- * | modification, are permitted provided that the following conditions |
- * | are met: |
- * | |
- * | o Redistributions of source code must retain the above copyright |
- * | notice, this list of conditions and the following disclaimer. |
- * | o Redistributions in binary form must reproduce the above copyright |
- * | notice, this list of conditions and the following disclaimer in the |
- * | documentation and/or other materials provided with the distribution.|
- * | o The names of the authors may not be used to endorse or promote |
- * | products derived from this software without specific prior written |
- * | permission. |
- * | |
- * | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
- * | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
- * | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
- * | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT |
- * | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
- * | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
- * | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
- * | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
- * | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
- * | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
- * | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
- * | |
- * +-----------------------------------------------------------------------+
- * | Author: Tony Bibbs <tony@geeklog.net> |
- * +-----------------------------------------------------------------------+
- *
- * PHP version 5
- *
- * @category HTTP
- * @package HTTP_Session2
- * @author Alexander Radivaniovich <info@wwwlab.net>
- * @author Tony Bibbs <tony@geeklog.net>
- * @license http://www.opensource.org/licenses/bsd-license.php The BSD License
- * @version CVS: $Id: Session2.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- * @link http://pear.php.net/package/HTTP_Session2
- */
-
-/**
- * HTTP_Session2_Exception
- */
-require_once 'HTTP/Session2/Exception.php';
-
-/**
- * Class for managing HTTP sessions
- *
- * Provides access to session-state values as well as session-level
- * settings and lifetime management methods.
- * Based on the standart PHP session handling mechanism
- * it provides for you more advanced features such as
- * database container, idle and expire timeouts, etc.
- *
- * Expample 1:
- *
- * <code>
- * // Setting some options and detecting of a new session
- * HTTP_Session2::useCookies(false);
- * HTTP_Session2::start('MySessionID');
- * HTTP_Session2::set('variable', 'The string');
- * if (HTTP_Session2::isNew()) {
- * echo 'new session was created with the current request';
- * $visitors++; // Increase visitors count
- * }
- *
- * //HTTP_Session2::regenerateId();
- * </code>
- *
- * Example 2:
- *
- * <code>
- * // Using database container
- * HTTP_Session2::setContainer('DB');
- * HTTP_Session2::start();
- * </code>
- *
- * Example 3:
- *
- * <code>
- * // Setting timeouts
- * HTTP_Session2::start();
- * HTTP_Session2::setExpire(time() + 60 * 60); // expires in one hour
- * HTTP_Session2::setIdle(10 * 60); // idles in ten minutes
- * if (HTTP_Session2::isExpired()) {
- * // expired
- * echo('Your session is expired!');
- * HTTP_Session2::destroy();
- * }
- * if (HTTP_Session2::isIdle()) {
- * // idle
- * echo('You've been idle for too long!');
- * HTTP_Session2::destroy();
- * }
- * HTTP_Session2::updateIdle();
- * </code>
- *
- * @category HTTP
- * @package HTTP_Session2
- * @author Alexander Radivaniovich <info@wwwlab.net>
- * @author Tony Bibbs <tony@geeklog.net>
- * @license http://www.opensource.org/licenses/bsd-license.php The BSD License
- * @version Release: @package_version@
- * @link http://pear.php.net/package/HTTP_Session2
- */
-class HTTP_Session2
-{
- /**
- * @const STARTED - The session was started with the current request
- */
- const STARTED = 1;
-
- /**
- * @const CONTINUE - No new session was started with the current request
- */
- const CONTINUED = 2;
-
- /**
- * @const ERR_UNKNOWN_CONTAINER - Container not found.
- */
- const ERR_UNKNOWN_CONTAINER = 667;
-
- /**
- * @const ERR_SYSTEM_PERM - System permissions not sufficient.
- * E.g. Not enough permissions to override ini-settings.
- */
- const ERR_SYSTEM_PERM = 668;
-
- /**
- * Container instance
- */
- public static $container;
-
- /**
- * Sets user-defined session storage functions
- *
- * Sets the user-defined session storage functions which are used
- * for storing and retrieving data associated with a session.
- * This is most useful when a storage method other than
- * those supplied by PHP sessions is preferred.
- * i.e. Storing the session data in a local database.
- *
- * @param string $container Name of the container (e.g. DB, MDB, ...).
- * @param array $container_options Options, most likely an array.
- *
- * @return void
- * @see session_set_save_handler()
- */
- static function setContainer($container, $container_options = null)
- {
- $container_class = 'HTTP_Session2_Container_' . $container;
- $container_classfile = 'HTTP/Session2/Container/' . $container . '.php';
-
- include_once $container_classfile;
- if (!class_exists($container_class)) {
- throw new HTTP_Session2_Exception(
- "Container class, $container_class, does not exist",
- self::ERR_UNKNOWN_CONTAINER);
- }
- self::$container = new $container_class($container_options);
-
- self::$container->set();
- }
-
- /**
- * Initializes session data
- *
- * Creates a session (or resumes the current one
- * based on the session id being passed
- * via a GET variable or a cookie).
- * You can provide your own name and/or id for a session.
- *
- * @param string $name Name of a session, default is 'SessionID'
- * @param string $id Id of a session which will be used
- * only when the session is new
- *
- * @return void
- * @see session_name()
- * @see session_id()
- * @see session_start()
- */
- public function start($name = 'SessionID', $id = null)
- {
- self::name($name);
- if (is_null(self::detectID())) {
- if ($id) {
- self::id($id);
- } else {
- self::id(uniqid(dechex(rand())));
- }
- }
- session_start();
- if (!isset($_SESSION['__HTTP_Session2_Info'])) {
- $_SESSION['__HTTP_Session2_Info'] = self::STARTED;
- } else {
- $_SESSION['__HTTP_Session2_Info'] = self::CONTINUED;
- }
- }
-
- /**
- * Writes session data and ends session
- *
- * Session data is usually stored after your script
- * terminated without the need to call HTTP_Session2::stop(),
- * but as session data is locked to prevent concurrent
- * writes only one script may operate on a session at any time.
- * When using framesets together with sessions you will
- * experience the frames loading one by one due to this
- * locking. You can reduce the time needed to load all the
- * frames by ending the session as soon as all changes
- * to session variables are done.
- *
- * @return void
- * @see session_write_close()
- */
- public static function pause()
- {
- session_write_close();
- }
-
- /**
- * Frees all session variables and destroys all data
- * registered to a session
- *
- * This method resets the $_SESSION variable and
- * destroys all of the data associated
- * with the current session in its storage (file or DB).
- * It forces new session to be started after this method
- * is called. It does not unset the session cookie.
- *
- * @return void
- * @see session_unset()
- * @see session_destroy()
- */
- public static function destroy()
- {
- session_unset();
- session_destroy();
- }
-
- /**
- * Free all session variables
- *
- * @todo TODO Save expire and idle timestamps?
- * @return void
- */
- public static function clear()
- {
- $info = $_SESSION['__HTTP_Session2_Info'];
-
- session_unset();
-
- $_SESSION['__HTTP_Session2_Info'] = $info;
- }
-
- /**
- * Tries to find any session id in $_GET, $_POST or $_COOKIE
- *
- * @return string Session ID (if exists) or null
- */
- public static function detectID()
- {
- if (self::useCookies()) {
- if (isset($_COOKIE[self::name()])) {
- return $_COOKIE[self::name()];
- }
- } else {
- if (isset($_GET[self::name()])) {
- return $_GET[self::name()];
- }
- if (isset($_POST[self::name()])) {
- return $_POST[self::name()];
- }
- }
- return null;
- }
-
- /**
- * Sets new name of a session
- *
- * @param string $name New name of a sesion
- *
- * @return string Previous name of a session
- * @see session_name()
- */
- public static function name($name = null)
- {
- if (isset($name)) {
- return session_name($name);
- }
- return session_name();
- }
-
- /**
- * Sets new ID of a session
- *
- * @param string $id New ID of a sesion
- *
- * @return string Previous ID of a session
- * @see session_id()
- */
- public static function id($id = null)
- {
- if (isset($id)) {
- return session_id($id);
- }
- return session_id();
- }
-
- /**
- * Sets the maximum expire time
- *
- * @param integer $time Time in seconds
- * @param bool $add Add time to current expire time or not
- *
- * @return void
- */
- public static function setExpire($time, $add = false)
- {
- if ($add && isset($_SESSION['__HTTP_Session2_Expire'])) {
- $_SESSION['__HTTP_Session2_Expire'] += $time;
- } else {
- $_SESSION['__HTTP_Session2_Expire'] = $time;
- }
- if (!isset($_SESSION['__HTTP_Session2_Expire_TS'])) {
- $_SESSION['__HTTP_Session2_Expire_TS'] = time();
- }
- }
-
- /**
- * Sets the maximum idle time
- *
- * Sets the time-out period allowed
- * between requests before the session-state
- * provider terminates the session.
- *
- * @param integer $time Time in seconds
- * @param bool $add Add time to current maximum idle time or not
- *
- * @return void
- */
- public static function setIdle($time, $add = false)
- {
- if ($add && isset($_SESSION['__HTTP_Session2_Idle'])) {
- $_SESSION['__HTTP_Session2_Idle'] += $time;
- } else {
- $_SESSION['__HTTP_Session2_Idle'] = $time;
- }
- if (!isset($_SESSION['__HTTP_Session2_Idle_TS'])) {
- $_SESSION['__HTTP_Session2_Idle_TS'] = time();
- }
- }
-
- /**
- * Returns the time up to the session is valid
- *
- * @return integer Time when the session idles
- */
- public static function sessionValidThru()
- {
- if (
- !isset($_SESSION['__HTTP_Session2_Idle_TS'])
- || !isset($_SESSION['__HTTP_Session2_Idle'])) {
- return 0;
- }
- return $_SESSION['__HTTP_Session2_Idle_TS']
- + $_SESSION['__HTTP_Session2_Idle'];
- }
-
- /**
- * Check if session is expired
- *
- * @return boolean
- */
- public static function isExpired()
- {
- if (
- isset($_SESSION['__HTTP_Session2_Expire'])
- && $_SESSION['__HTTP_Session2_Expire'] > 0
- && isset($_SESSION['__HTTP_Session2_Expire_TS'])
- &&
- (
- $_SESSION['__HTTP_Session2_Expire_TS']
- + $_SESSION['__HTTP_Session2_Expire']
- ) <= time()) {
- return true;
- }
- return false;
- }
-
- /**
- * Check if session is idle
- *
- * @return boolean Obvious
- */
- public static function isIdle()
- {
- if (
- isset($_SESSION['__HTTP_Session2_Idle'])
- && $_SESSION['__HTTP_Session2_Idle'] > 0
- && isset($_SESSION['__HTTP_Session2_Idle_TS'])
- && (
- $_SESSION['__HTTP_Session2_Idle_TS']
- + $_SESSION['__HTTP_Session2_Idle']
- ) <= time()) {
- return true;
- }
- return false;
- }
-
- /**
- * Updates the idletime
- *
- * @return void
- */
- public static function updateIdle()
- {
- if (isset($_SESSION['__HTTP_Session2_Idle_TS'])) {
- $_SESSION['__HTTP_Session2_Idle_TS'] = time();
- }
- }
-
- /**
- * If optional parameter is specified it indicates whether the module will
- * use cookies to store the session id on the client side in a cookie.
- *
- * By default this cookie will be deleted when the browser is closed!
- *
- * It will throw an Exception if it's not able to set the session.use_cookie
- * property.
- *
- * It returns the previous value of this property.
- *
- * @param boolean $useCookies If specified it will replace the previous value
- * of this property
- *
- * @return boolean The previous value of the property
- * @throws HTTP_Session2_Exception If ini_set fails!
- * @see session_set_cookie_params()
- */
- public static function useCookies($useCookies = null)
- {
- $return = false;
- if (ini_get('session.use_cookies') == '1') {
- $return = true;
- }
- if ($useCookies != null) {
- if ($useCookies) {
- $status = ini_set('session.use_cookies', 1);
- } else {
- $status = ini_set('session.use_cookies', 0);
- }
- if ($status === false) {
- throw new HTTP_Session2_Exception(
- 'Could not set session.use_cookies, please check permissions.',
- self::ERR_SYSTEM_PERM);
- }
- }
- return $return;
- }
-
- /**
- * Gets a value indicating whether the session
- * was created with the current request
- *
- * You MUST call this method only after you have started
- * the session with the HTTP_Session2::start() method.
- *
- * @return boolean true if the session was created
- * with the current request, false otherwise
- * @see self::start()
- */
- public static function isNew()
- {
- // The best way to check if a session is new is to check
- // for existence of a session data storage
- // with the current session id, but this is impossible
- // with the default PHP module wich is 'files'.
- // So we need to emulate it.
- return !isset($_SESSION['__HTTP_Session2_Info']) ||
- $_SESSION['__HTTP_Session2_Info'] == self::STARTED;
- }
-
- /**
- * Register variable with the current session
- *
- * @param string $name Name of a global variable
- *
- * @return void
- * @see session_register()
- */
- public static function register($name)
- {
- session_register($name);
- }
-
- /**
- * Unregister a variable from the current session
- *
- * @param string $name Name of a global variable
- *
- * @return void
- * @see session_unregister()
- */
- public static function unregister($name)
- {
- session_unregister($name);
- }
-
- /**
- * Returns session variable
- *
- * @param string $name Name of a variable
- * @param mixed $default Default value of a variable if not set
- *
- * @return mixed Value of a variable
- */
- public static function &get($name, $default = null)
- {
- if (!isset($_SESSION[$name]) && isset($default)) {
- $_SESSION[$name] = $default;
- }
- return $_SESSION[$name];
- }
-
- /**
- * Sets session variable
- *
- * @param string $name Name of a variable
- * @param mixed $value Value of a variable
- *
- * @return mixed Old value of a variable
- */
- public function set($name, $value)
- {
- $return = (isset($_SESSION[$name])) ? $_SESSION[$name] : null;
- if (null === $value) {
- unset($_SESSION[$name]);
- } else {
- $_SESSION[$name] = $value;
- }
- return $return;
- }
-
- /**
- * Returns local variable of a script
- *
- * Two scripts can have local variables with the same names
- *
- * @param string $name Name of a variable
- * @param mixed $default Default value of a variable if not set
- *
- * @return mixed Value of a local variable
- */
- static function &getLocal($name, $default = null)
- {
- $local = md5(self::localName());
- if (!is_array($_SESSION[$local])) {
- $_SESSION[$local] = array();
- }
- if (!isset($_SESSION[$local][$name]) && isset($default)) {
- $_SESSION[$local][$name] = $default;
- }
- return $_SESSION[$local][$name];
- }
-
- /**
- * Sets local variable of a script.
- * Two scripts can have local variables with the same names.
- *
- * @param string $name Name of a local variable
- * @param mixed $value Value of a local variable
- *
- * @return mixed Old value of a local variable
- */
- static function setLocal($name, $value)
- {
- $local = md5(self::localName());
- if (!is_array($_SESSION[$local])) {
- $_SESSION[$local] = array();
- }
- $return = $_SESSION[$local][$name];
- if (null === $value) {
- unset($_SESSION[$local][$name]);
- } else {
- $_SESSION[$local][$name] = $value;
- }
- return $return;
- }
-
- /**
- * set the usage of transparent SID
- *
- * @param boolean $useTransSID Flag to use transparent SID
- *
- * @return boolean
- */
- static function useTransSID($useTransSID = false)
- {
- $return = ini_get('session.use_trans_sid') ? true : false;
- if ($useTransSID === false) {
- ini_set('session.use_trans_sid', $useTransSID ? 1 : 0);
- }
- return $return;
- }
-
- /**
- * Sets new local name
- *
- * @param string $name New local name
- *
- * @return string Previous local name
- */
- static function localName($name = null)
- {
- $return = '';
- if (isset($GLOBALS['__HTTP_Session2_Localname'])) {
- $return .= $GLOBALS['__HTTP_Session2_Localname'];
- }
- if (!empty($name)) {
- $GLOBALS['__HTTP_Session2_Localname'] = $name;
- }
- return $return;
- }
-
- /**
- * init
- *
- * @return void
- */
- static function init()
- {
- // Disable auto-start of a sesion
- ini_set('session.auto_start', 0);
-
- // Set local name equal to the current script name
- self::localName($_SERVER['SCRIPT_NAME']);
- }
-
- /**
- * Regenrates session id
- *
- * If session_regenerate_id() is not available emulates its functionality
- *
- * @param boolean $deleteOldSessionData Whether to delete data of old session
- *
- * @return boolean
- */
- public static function regenerateId($deleteOldSessionData = false)
- {
- if (function_exists('session_regenerate_id')) {
- return session_regenerate_id($deleteOldSessionData);
-
- // emulate session_regenerate_id()
- } else {
-
- do {
- $newId = uniqid(dechex(rand()));
- } while ($newId === session_id());
-
- if ($deleteOldSessionData) {
- session_unset();
- }
-
- session_id($newId);
-
- return true;
- }
- }
-
- /**
- * This function copies session data of specified id to specified table
- *
- * @param string $target Target to replicate to
- * @param string $id Id of record to replicate
- *
- * @return boolean
- */
- public static function replicate($target, $id = null)
- {
- return self::$container->replicate($target, $id);
- }
-
- /**
- * If optional parameter is specified it determines the number of seconds
- * after which session data will be seen as 'garbage' and cleaned up
- *
- * It returns the previous value of this property
- *
- * @param boolean $gcMaxLifetime If specified it will replace the previous value
- * of this property
- *
- * @return boolean The previous value of the property
- */
- public static function setGcMaxLifetime($gcMaxLifetime = null)
- {
- $return = ini_get('session.gc_maxlifetime');
- if (isset($gcMaxLifetime) && is_int($gcMaxLifetime) && $gcMaxLifetime >= 1) {
- ini_set('session.gc_maxlifetime', $gcMaxLifetime);
- }
- return $return;
- }
-
- /**
- * If optional parameter is specified it determines the
- * probability that the gc (garbage collection) routine is started
- * and session data is cleaned up
- *
- * It returns the previous value of this property
- *
- * @param boolean $gcProbability If specified it will replace the previous value
- * of this property
- *
- * @return boolean The previous value of the property
- */
- public static function setGcProbability($gcProbability = null)
- {
- $return = ini_get('session.gc_probability');
- if (isset($gcProbability) &&
- is_int($gcProbability) &&
- $gcProbability >= 1 &&
- $gcProbability <= 100) {
- ini_set('session.gc_probability', $gcProbability);
- }
- return $return;
- }
-}
-
-HTTP_Session2::init();
-?>
+++ /dev/null
-<?php
-/**
- * +-----------------------------------------------------------------------+
- * | Copyright (c) 2004, Tony Bibbs |
- * | All rights reserved. |
- * | |
- * | Redistribution and use in source and binary forms, with or without |
- * | modification, are permitted provided that the following conditions |
- * | are met: |
- * | |
- * | o Redistributions of source code must retain the above copyright |
- * | notice, this list of conditions and the following disclaimer. |
- * | o Redistributions in binary form must reproduce the above copyright |
- * | notice, this list of conditions and the following disclaimer in the |
- * | documentation and/or other materials provided with the distribution.|
- * | o The names of the authors may not be used to endorse or promote |
- * | products derived from this software without specific prior written |
- * | permission. |
- * | |
- * | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
- * | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
- * | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
- * | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT |
- * | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
- * | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
- * | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
- * | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
- * | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
- * | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
- * | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
- * | |
- * +-----------------------------------------------------------------------+
- * | Author: Alexander Radivanovich <info@wwwlab.net> |
- * | Tony Bibbs <tony@geeklog.net> |
- * +-----------------------------------------------------------------------+
- *
- * PHP version 5
- *
- * @category HTTP
- * @package HTTP_Session2
- * @author Alexander Radivaniovich <info@wwwlab.net>
- * @author Tony Bibbs <tony@geeklog.net>
- * @license http://www.opensource.org/licenses/bsd-license.php The BSD License
- * @version CVS: $Id: Container.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- * @link http://pear.php.net/package/HTTP_Session2
- */
-
-/**
- * HTTP_Session2_Container_Interface
- */
-require_once 'HTTP/Session2/Container/Interface.php';
-
-/**
- * Container class for storing session data data
- *
- * @category HTTP
- * @package HTTP_Session2
- * @author Alexander Radivaniovich <info@wwwlab.net>
- * @author Tony Bibbs <tony@geeklog.net>
- * @license http://www.opensource.org/licenses/bsd-license.php The BSD License
- * @version Release: @package_version@
- * @link http://pear.php.net/package/HTTP_Session2
- */
-abstract class HTTP_Session2_Container implements HTTP_Session2_Container_Interface
-{
- /**
- * Additional options for the container object
- *
- * @var array
- */
- protected $options = array();
-
- /**
- * Constrtuctor method
- *
- * @param array $options Additional options for the container object
- *
- * @return void
- */
- public function __construct($options = null)
- {
- $this->setDefaults();
- if (is_array($options)) {
- $this->parseOptions($options);
- }
- }
-
- /**
- * Set some default options
- *
- * @return void
- */
- protected function setDefaults()
- {
- }
-
- /**
- * Parse options passed to the container class
- *
- * @param array $options Options
- *
- * @return void
- */
- protected function parseOptions($options)
- {
- foreach ($options as $option => $value) {
- if (in_array($option, array_keys($this->options))) {
- $this->options[$option] = $value;
- }
- }
- }
-
- /**
- * Set session save handler
- *
- * @return void
- */
- public function set()
- {
- session_module_name('user');
- session_set_save_handler(array($this, 'open'),
- array($this, 'close'),
- array($this, 'read'),
- array($this, 'write'),
- array($this, 'destroy'),
- array($this, 'gc'));
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-/**
- * +-----------------------------------------------------------------------+
- * | Copyright (c) 2002, Alexander Radivanovich |
- * | All rights reserved. |
- * | |
- * | Redistribution and use in source and binary forms, with or without |
- * | modification, are permitted provided that the following conditions |
- * | are met: |
- * | |
- * | o Redistributions of source code must retain the above copyright |
- * | notice, this list of conditions and the following disclaimer. |
- * | o Redistributions in binary form must reproduce the above copyright |
- * | notice, this list of conditions and the following disclaimer in the |
- * | documentation and/or other materials provided with the distribution.|
- * | o The names of the authors may not be used to endorse or promote |
- * | products derived from this software without specific prior written |
- * | permission. |
- * | |
- * | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
- * | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
- * | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
- * | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT |
- * | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
- * | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
- * | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
- * | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
- * | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
- * | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
- * | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
- * | |
- * +-----------------------------------------------------------------------+
- * | Author: Alexander Radivanovich <info@wwwlab.net> |
- * +-----------------------------------------------------------------------+
- *
- * PHP Version 5
- *
- * @category HTTP
- * @package HTTP_Session2
- * @author Alexander Radivanovich <info@wwwlab.net>
- * @license http://www.opensource.org/licenses/bsd-license.php The BSD License
- * @version CVS: $Id: DB.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- * @link http://pear.php.net/package/HTTP_Session2
- */
-
-/**
- * HTTP/Session2/Container.php
- * @ignore
- */
-require_once 'HTTP/Session2/Container.php';
-
-/**
- * HTTP/Session2/Exception.php
- *
- * @todo Implement HTTP_Session2_Containter_DB_Exception
- */
-require_once 'HTTP/Session2/Exception.php';
-
-/**
- * DB.php
- * @ignore
- */
-require_once 'DB.php';
-
-/**
- * Database container for session data
- *
- * Create the following table to store session data
- * <code>
- * CREATE TABLE `sessiondata` (
- * `id` CHAR(32) NOT NULL,
- * `expiry` INT UNSIGNED NOT NULL DEFAULT 0,
- * `data` TEXT NOT NULL,
- * PRIMARY KEY (`id`)
- * );
- * </code>
- *
- * @category HTTP
- * @package HTTP_Session2
- * @author Alexander Radivanovich <info@wwwlab.net>
- * @license http://www.opensource.org/licenses/bsd-license.php The BSD License
- * @version Release: @package_version@
- * @link http://pear.php.net/package/HTTP_Session2
- */
-class HTTP_Session2_Container_DB extends HTTP_Session2_Container
-{
-
- /**
- * DB connection object
- *
- * @var object DB
- */
- private $db = null;
-
- /**
- * Session data cache id
- *
- * @var mixed
- */
- private $crc = false;
-
- /**
- * Constrtuctor method
- *
- * $options is an array with the options.<br>
- * The options are:
- * <ul>
- * <li>'dsn' - The DSN string</li>
- * <li>'table' - Table with session data, default is 'sessiondata'</li>
- * <li>'autooptimize' - Boolean, 'true' to optimize
- * the table on garbage collection, default is 'false'.</li>
- * </ul>
- *
- * @param array $options The options
- *
- * @return void
- */
- public function __construct($options)
- {
- parent::__construct($options);
- }
-
- /**
- * Connect to database by using the given DSN string
- *
- * @param string $dsn DSN string
- *
- * @return boolean
- * @throws HTTP_Session2_Exception An exception?!
- */
- protected function connect($dsn)
- {
- if (is_string($dsn)) {
- $this->db = DB::connect($dsn);
- } else if (is_object($dsn) && is_a($dsn, 'db_common')) {
- $this->db = $dsn;
- } else if (DB::isError($dsn)) {
- throw new HTTP_Session2_Exception($dsn->getMessage(), $dsn->getCode());
- } else {
- $msg = "The given dsn was not valid in file ";
- $msg .= __FILE__ . " at line " . __LINE__;
- throw new HTTP_Session2_Exception($msg);
- }
- if (DB::isError($this->db)) {
- throw new HTTP_Session2_Exception($this->db->getMessage(),
- $this->db->getCode());
- }
- return true;
- }
-
- /**
- * Set some default options
- *
- * @return void
- */
- protected function setDefaults()
- {
- $this->options['dsn'] = null;
- $this->options['table'] = 'sessiondata';
- $this->options['autooptimize'] = false;
- }
-
- /**
- * Establish connection to a database
- *
- * @param string $save_path The path to save/write sessions.
- * @param string $session_name The session name.
- *
- * @return boolean
- * @uses self::connect();
- * @uses self::$options
- */
- public function open($save_path, $session_name)
- {
- return $this->connect($this->options['dsn']);
- }
-
- /**
- * Free resources
- *
- * @return boolean
- */
- public function close()
- {
- return true;
- }
-
- /**
- * Read session data
- *
- * @param string $id The Id!
- *
- * @return mixed
- * @throws HTTP_Session2_Exception An exception!?
- */
- public function read($id)
- {
- $query = sprintf("SELECT data FROM %s WHERE id = %s AND expiry >= %d",
- $this->options['table'],
- $this->db->quote(md5($id)),
- time());
-
- $result = $this->db->getOne($query);
- if (DB::isError($result)) {
- throw new HTTP_Session2_Exception($result->getMessage(),
- $result->getCode());
- }
- $this->crc = strlen($result) . crc32($result);
- return $result;
- }
-
- /**
- * Write session data
- *
- * @param string $id The id.
- * @param string $data The data.
- *
- * @return boolean
- * @todo Remove sprintf(), they are expensive.
- */
- public function write($id, $data)
- {
- if ((false !== $this->crc)
- && ($this->crc === strlen($data) . crc32($data))) {
- /* $_SESSION hasn't been touched, no need to update the blob column */
- $query = "UPDATE %s SET expiry = %d WHERE id = %s AND expiry >= %d";
- $query = sprintf($query,
- $this->options['table'],
- time() + ini_get('session.gc_maxlifetime'),
- $this->db->quote(md5($id)),
- time());
- } else {
- /* Check if table row already exists */
- $query = sprintf("SELECT COUNT(id) FROM %s WHERE id = '%s'",
- $this->options['table'],
- md5($id));
-
- $result = $this->db->getOne($query);
- if (DB::isError($result)) {
- new DB_Error($result->code, PEAR_ERROR_DIE);
- return false;
- }
- if (0 == intval($result)) {
- /* Insert new row into table */
- $query = "INSERT INTO %s (id, expiry, data) VALUES (%s, %d, %s)";
- $query = sprintf($query,
- $this->options['table'],
- $this->db->quote(md5($id)),
- time() + ini_get('session.gc_maxlifetime'),
- $this->db->quote($data));
- } else {
- /* Update existing row */
- $query = "UPDATE %s SET expiry = %d, data = %s";
- $query .= " WHERE id = %s AND expiry >= %d";
- $query = sprintf($query,
- $this->options['table'],
- time() + ini_get('session.gc_maxlifetime'),
- $this->db->quote($data),
- $this->db->quote(md5($id)),
- time());
- }
- }
- $result = $this->db->query($query);
- if (DB::isError($result)) {
- new DB_Error($result->code, PEAR_ERROR_DIE);
- return false;
- }
- return true;
- }
-
- /**
- * Destroy session data
- *
- * @param string $id The id.
- *
- * @return boolean
- */
- public function destroy($id)
- {
- $query = sprintf("DELETE FROM %s WHERE id = %s",
- $this->options['table'],
- $this->db->quote(md5($id)));
-
- $result = $this->db->query($query);
- if (DB::isError($result)) {
- new DB_Error($result->code, PEAR_ERROR_DIE);
- return false;
- }
- return true;
- }
-
- /**
- * Garbage collection
- *
- * @param int $maxlifetime The session's maximum lifetime.
- *
- * @return boolean
- * @todo Find out why the DB is not used for garbage collection.
- */
- public function gc($maxlifetime)
- {
- $query = sprintf("DELETE FROM %s WHERE expiry < %d",
- $this->options['table'],
- time());
-
- $result = $this->db->query($query);
- if (DB::isError($result)) {
- new DB_Error($result->code, PEAR_ERROR_DIE);
- return false;
- }
-
- if ($this->options['autooptimize']) {
- switch($this->db->type) {
- case 'mysql':
- $query = sprintf("OPTIMIZE TABLE %s", $this->options['table']);
- break;
- case 'pgsql':
- $query = sprintf("VACUUM %s", $this->options['table']);
- break;
- default:
- $query = null;
- break;
- }
- if (isset($query)) {
- $result = $this->db->query($query);
- if (DB::isError($result)) {
- new DB_Error($result->code, PEAR_ERROR_DIE);
- return false;
- }
- }
- }
- return true;
- }
-
- /**
- * Replicate session data to specified target
- *
- * @param string $target Target to replicate to
- * @param string $id Id of record to replicate,
- * if not specified current session id will be used
- *
- * @return boolean
- */
- public function replicate($target, $id = null)
- {
- if (is_null($id)) {
- $id = HTTP_Session2::id();
- }
-
- // Check if table row already exists
- $query = sprintf("SELECT COUNT(id) FROM %s WHERE id = %s",
- $target,
- $this->db->quoteSmart(md5($id)));
- $result = $this->db->getOne($query);
- if (DB::isError($result)) {
- new DB_Error($result->code, PEAR_ERROR_DIE);
- return false;
- }
-
- // Insert new row into target table
- if (0 == intval($result)) {
- $query = "INSERT INTO $target SELECT * FROM";
- $query .= " " . $this->options['table'];
- $query .= " WHERE id = " . $this->db->quoteSmart(md5($id));
- } else {
- // Update existing row
- $query = "UPDATE $target dst,";
- $query .= " " . $this->options['table'];
- $query .= " src SET dst.expiry = src.expiry,";
- $query .= " dst.data = src.data";
- $query .= " WHERE dst.id = src.id";
- $query .= " AND src.id = " . $this->db->quoteSmart(md5($id));
- }
-
- $result = $this->db->query($query);
- if (DB::isError($result)) {
- new DB_Error($result->code, PEAR_ERROR_DIE);
- return false;
- }
-
- return true;
- }
-}
+++ /dev/null
-<?php
-/**
- * +-----------------------------------------------------------------------+
- * | Copyright (c) 2004, Tony Bibbs |
- * | All rights reserved. |
- * | |
- * | Redistribution and use in source and binary forms, with or without |
- * | modification, are permitted provided that the following conditions |
- * | are met: |
- * | |
- * | o Redistributions of source code must retain the above copyright |
- * | notice, this list of conditions and the following disclaimer. |
- * | o Redistributions in binary form must reproduce the above copyright |
- * | notice, this list of conditions and the following disclaimer in the |
- * | documentation and/or other materials provided with the distribution.|
- * | o The names of the authors may not be used to endorse or promote |
- * | products derived from this software without specific prior written |
- * | permission. |
- * | |
- * | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
- * | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
- * | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
- * | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT |
- * | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
- * | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
- * | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
- * | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
- * | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
- * | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
- * | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
- * | |
- * +-----------------------------------------------------------------------+
- * | Author: Alexander Radivanovich <info@wwwlab.net> |
- * | Tony Bibbs <tony@geeklog.net> |
- * +-----------------------------------------------------------------------+
- *
- * PHP Version 5
- *
- * @category HTTP
- * @package HTTP_Session2
- * @author Alexander Radivaniovich <info@wwwlab.net>
- * @license http://www.opensource.org/licenses/bsd-license.php The BSD License
- * @version CVS: $Id: Interface.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- * @link http://pear.php.net/package/HTTP_Session2
- */
-
-/**
- * Container class for storing session data data
- *
- * @category HTTP
- * @package HTTP_Session2
- * @author Alexander Radivaniovich <info@wwwlab.net>
- * @version Release: @package_version@
- * @link http://pear.php.net/package/HTTP_Session2
- */
-interface HTTP_Session2_Container_Interface
-{
- /**
- * open
- *
- * @param string $save_path Path to save sessions in.
- * @param string $session_name Name of the session.
- *
- * @return void
- */
- public function open($save_path, $session_name);
-
- /**
- * close
- *
- * @return void
- */
- public function close();
-
- /**
- * read
- *
- * @param string $id The session ID.
- *
- * @return void
- */
- public function read($id);
-
- /**
- * write
- *
- * @param string $id The session ID.
- * @param string $data The data to save/write.
- *
- * @return void
- */
- public function write($id, $data);
-
- /**
- * destroy
- *
- * @param string $id The session ID.
- *
- * @return void
- */
- public function destroy($id);
-
- /**
- * gc
- *
- * @param int $maxlifetime The session's maximum lifetime.
- *
- * @return void
- */
- public function gc($maxlifetime);
-
- /**
- * Replicate session data to specified target
- *
- * @param string $target Target to replicate to
- * @param string $id Id of record to replicate,
- * if not specified current session id will be used
- *
- * @return boolean
- */
- public function replicate($target, $id = null);
-}
\ No newline at end of file
+++ /dev/null
-<?php
-/**
- * HTTP_Session2_Container_MDB2
- *
- * PHP Version 5
- *
- * @category HTTP
- * @package HTTP_Session2
- * @author Till Klampaeckel <till@php.net>
- * @license http://www.opensource.org/licenses/bsd-license.php The BSD License
- * @version CVS: $Id: MDB2.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- * @link http://pear.php.net/package/HTTP_Session2
- */
-
-/**
- * HTTP/Session2/Container.php
- * @ignore
- */
-require_once 'HTTP/Session2/Container.php';
-
-/**
- * HTTP/Session2/Exception.php
- */
-require_once 'HTTP/Session2/Exception.php';
-
-/**
- * MDB2.php
- * @ignore
- */
-require_once 'MDB2.php';
-
-/**
- * Database container for session data
- *
- * Create the following table to store session data
- * <code>
- * CREATE TABLE `sessiondata` (
- * `id` CHAR(32) NOT NULL,
- * `expiry` INT UNSIGNED NOT NULL DEFAULT 0,
- * `data` TEXT NOT NULL,
- * PRIMARY KEY (`id`)
- * );
- * </code>
- *
- * @category HTTP
- * @package HTTP_Session2
- * @author Alexander Radivanovich <info@wwwlab.net>
- * @license http://www.opensource.org/licenses/bsd-license.php The BSD License
- * @version Release: @package_version@
- * @link http://pear.php.net/package/HTTP_Session2
- * @uses MDB2
- * @uses MDB2_Driver_*
- */
-class HTTP_Session2_Container_MDB2 extends HTTP_Session2_Container
-{
-
- /**
- * MDB2 connection object
- *
- * @var object DB
- */
- private $db = null;
-
- /**
- * Session data cache id
- *
- * @var mixed
- */
- private $crc = false;
-
- /**
- * Constrtuctor method
- *
- * $options is an array with the options.<br>
- * The options are:
- * <ul>
- * <li>'dsn' - The DSN string</li>
- * <li>'table' - Table with session data, default is 'sessiondata'</li>
- * <li>'autooptimize' - Boolean, 'true' to optimize
- * the table on garbage collection, default is 'false'.</li>
- * </ul>
- *
- * @param array $options The options
- *
- * @return object
- */
- public function __construct($options)
- {
- parent::__construct($options);
- }
-
- /**
- * Connect to database by using the given DSN string
- *
- * @param mixed $dsn DSN string or MDB2 object
- *
- * @return boolean
- * @throws HTTP_Session2_Exception An exception?!
- */
- protected function connect($dsn)
- {
- // pseudo singleton approach
- if (is_object($this->db)) {
- return true;
- }
- if (is_string($dsn) || is_array($dsn)) {
- $this->db = MDB2::connect($dsn);
- } else if (is_object($dsn) && ($dsn instanceof MDB2_Driver_Common)) {
- $this->db = $dsn;
- } else if (MDB2::isError($dsn)) {
- throw new HTTP_Session2_Exception($dsn->getMessage(), $dsn->getCode());
- } else {
- $msg = "The given dsn was not valid in file ";
- $msg .= __FILE__ . " at line " . __LINE__;
- throw new HTTP_Session2_Exception($msg);
- }
- if (MDB2::isError($this->db)) {
- throw new HTTP_Session2_Exception($this->db->getMessage(),
- $this->db->getCode());
- }
- return true;
- }
-
- /**
- * Set some default options
- *
- * @return void
- */
- protected function setDefaults()
- {
- $this->options['dsn'] = null;
- $this->options['table'] = 'sessiondata';
- $this->options['autooptimize'] = false;
- }
-
- /**
- * Establish connection to a database
- *
- * @param string $save_path The path to save/write sessions.
- * @param string $session_name The session name.
- *
- * @return boolean
- * @uses self::connect();
- * @uses self::$options
- */
- public function open($save_path, $session_name)
- {
- return $this->connect($this->options['dsn']);
- }
-
- /**
- * Free resources
- *
- * @return boolean
- */
- public function close()
- {
- if (is_object($this->db)) {
- $this->db->disconnect();
- }
- return true;
- }
-
- /**
- * Read session data
- *
- * @param string $id The Id!
- *
- * @return mixed
- * @throws HTTP_Session2_Exception An exception!?
- * @todo Get rid off sprintf()
- */
- public function read($id)
- {
- $query = sprintf("SELECT data FROM %s WHERE id = %s AND expiry >= %d",
- $this->options['table'],
- $this->db->quote(md5($id)),
- time());
-
- $result = $this->db->queryOne($query);
- if (MDB2::isError($result)) {
- throw new HTTP_Session2_Exception($result->getMessage(),
- $result->getCode());
- }
- $this->crc = strlen($result) . crc32($result);
- return $result;
- }
-
- /**
- * Write session data
- *
- * @param string $id The id.
- * @param string $data The data.
- *
- * @return boolean
- * @todo Remove sprintf(), they are expensive.
- */
- public function write($id, $data)
- {
- if ((false !== $this->crc)
- && ($this->crc === strlen($data) . crc32($data))) {
- /* $_SESSION hasn't been touched, no need to update the blob column */
- $query = "UPDATE %s SET expiry = %d WHERE id = %s AND expiry >= %d";
- $query = sprintf($query,
- $this->options['table'],
- time() + ini_get('session.gc_maxlifetime'),
- $this->db->quote(md5($id)),
- time());
- } else {
- /* Check if table row already exists */
- $query = sprintf("SELECT COUNT(id) FROM %s WHERE id = '%s'",
- $this->options['table'],
- md5($id));
-
- $result = $this->db->queryOne($query);
- if (MDB2::isError($result)) {
- throw new HTTP_Session2_Exception($result->getUserInfo(),
- $result->getCode());
- }
- if (0 == intval($result)) {
- /* Insert new row into table */
- $query = "INSERT INTO %s (id, expiry, data) VALUES (%s, %d, %s)";
- $query = sprintf($query,
- $this->options['table'],
- $this->db->quote(md5($id)),
- time() + ini_get('session.gc_maxlifetime'),
- $this->db->quote($data));
- } else {
- /* Update existing row */
- $query = "UPDATE %s SET expiry = %d, data = %s";
- $query .= " WHERE id = %s AND expiry >= %d";
- $query = sprintf($query,
- $this->options['table'],
- time() + ini_get('session.gc_maxlifetime'),
- $this->db->quote($data),
- $this->db->quote(md5($id)),
- time());
- }
- }
- $result = $this->db->query($query);
- if (MDB2::isError($result)) {
- throw new HTTP_Session2_Exception($result->getUserInfo(),
- $result->getCode());
- }
- return true;
- }
-
- /**
- * Destroy session data
- *
- * @param string $id The id.
- *
- * @return boolean
- * @throws HTTP_Session2_Exception An exception containing MDB2 data.
- */
- public function destroy($id)
- {
- $query = sprintf("DELETE FROM %s WHERE id = %s",
- $this->options['table'],
- $this->db->quote(md5($id)));
-
- $result = $this->db->query($query);
- if (MDB2::isError($result)) {
- throw new HTTP_Session2_Exception ($result->getMessage(),
- $result->getCode());
- }
- return true;
- }
-
- /**
- * Garbage collection
- *
- * Currently supported are mysql, mysqli and pgsql.
- *
- * @param int $maxlifetime The session's maximum lifetime.
- *
- * @return boolean
- * @throws HTTP_Session2_Exception An exception that contains MDB2 data.
- * @todo Fix database-specific garbage collection.
- */
- public function gc($maxlifetime)
- {
- $query = sprintf("DELETE FROM %s WHERE expiry < %d",
- $this->options['table'],
- time());
-
- $result = $this->db->query($query);
- if (MDB2::isError($result)) {
- throw new HTTP_Session2_Exception($result->getMessage(),
- $result->getCode());
- }
-
- if ($this->options['autooptimize']) {
- switch($this->db->phptype) {
- case 'mysql':
- case 'mysqli':
- $query = sprintf('OPTIMIZE TABLE %s',
- $this->db->quoteIdentifier($this->options['table']));
- break;
- case 'pgsql':
- $query = sprintf('VACUUM %s',
- $this->db->quoteIdentifier($this->options['table']));
- break;
- default:
- $query = null;
- break;
- }
- if ($query !== null) {
- $result = $this->db->query($query);
- if (MDB2::isError($result)) {
- throw new HTTP_Session2_Exception($result->getMessage(),
- $result->getCode());
- }
- }
- }
- return true;
- }
-
- /**
- * Replicate session data to specified target
- *
- * @param string $target Target to replicate to
- * @param string $id Id of record to replicate,
- * if not specified current session id will be used
- *
- * @return boolean
- */
- public function replicate($target, $id = null)
- {
- if (is_null($id)) {
- $id = HTTP_Session2::id();
- }
-
- // Check if table row already exists
- $query = "SELECT COUNT(id) FROM $target";
- $query .= " WHERE id = " . $this->db->quote(md5($id), 'text');
- $result = $this->db->queryOne($query);
- if (MDB2::isError($result)) {
- $this->db->raiseError($result->code, PEAR_ERROR_DIE);
- return false;
- }
-
- // Insert new row into dest table
- if (0 == intval($result)) {
- $query = sprintf("INSERT INTO %s SELECT * FROM %s WHERE id = %s",
- $target,
- $this->options['table'],
- $this->db->quote(md5($id), 'text'));
-
- } else {
- // Update existing row
- $query = "UPDATE $target dst, " . $this->options['table'];
- $query .= " src SET dst.expiry = src.expiry,";
- $query .= " dst.data = src.data";
- $query .= " WHERE dst.id = src.id";
- $query .= " AND src.id = " . $this->db->quote(md5($id), 'text');
- }
-
- $result = $this->db->query($query);
- if (MDB2::isError($result)) {
- $this->db->raiseError($result->code, PEAR_ERROR_DIE);
- return false;
- }
-
- return true;
- }
-}
+++ /dev/null
-<?php
-/**
- * HTTP_Session2_Container_Memcache
- *
- * PHP Version 5
- *
- * @category HTTP
- * @package HTTP_Session2
- * @author Chad Wagner <chad.wagner@gmail.com>
- * @author Torsten Roehr <torsten.roehr@gmx.de>
- * @license http://www.opensource.org/licenses/bsd-license.php The BSD License
- * @version CVS: $Id: Memcache.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- * @link http://pear.php.net/package/HTTP_Session2
- */
-
-require_once 'HTTP/Session2/Container.php';
-
-/**
- * HTTP/Session2/Exception.php
- */
-require_once 'HTTP/Session2/Exception.php';
-
-/**
- * Memcache container for session data
- *
- * @category HTTP
- * @package HTTP_Session2
- * @author Chad Wagner <chad.wagner@gmail.com>
- * @author Torsten Roehr <torsten.roehr@gmx.de>
- * @license http://www.opensource.org/licenses/bsd-license.php The BSD License
- * @version Release: @package_version@
- * @link http://pear.php.net/package/HTTP_Session2
- * @since Class available since Release 0.6.2
- */
-class HTTP_Session2_Container_Memcache extends HTTP_Session2_Container
-{
- /**
- * Memcache connection object
- *
- * @var object Memcache
- */
- private $mc;
-
- /**
- * Constructor method
- *
- * $options is an array with the options.<br>
- * The options are:
- * <ul>
- * <li>'memcache' - Memcache object
- * <li>'prefix' - Key prefix, default is 'sessiondata:'</li>
- * </ul>
- *
- * @param array $options Options
- *
- * @return object
- */
- public function __construct($options)
- {
- parent::__construct($options);
- }
-
- /**
- * Connect by using the given DSN string
- *
- * @param object $mc Memcache object
- *
- * @return boolean
- * @throws HTTP_Session2_Exception
- */
- protected function connect($mc)
- {
- if ($mc instanceof Memcache) {
- $this->mc = $mc;
- } else {
- throw new HTTP_Session2_Exception(
- 'The given memcache object was not valid in file '
- . __FILE__ . ' at line ' . __LINE__, 41);
- }
-
- return true;
- }
-
- /**
- * Set some default options
- *
- * @return void
- */
- protected function setDefaults()
- {
- $this->options['prefix'] = 'sessiondata:';
- $this->options['memcache'] = null;
- }
-
- /**
- * Establish connection to a database
- *
- * @param string $save_path Save path
- * @param string $session_name Session name
- *
- * @return boolean
- */
- public function open($save_path, $session_name)
- {
- return $this->connect($this->options['memcache']);
- }
-
- /**
- * Free resources
- *
- * @return boolean
- */
- public function close()
- {
- return true;
- }
-
- /**
- * Read session data
- *
- * @param string $id Session id
- *
- * @return mixed
- */
- public function read($id)
- {
- return $this->mc->get($this->options['prefix'] . $id);
- }
-
- /**
- * Write session data
- *
- * @param string $id Session id
- * @param mixed $data Session data
- *
- * @return boolean
- */
- public function write($id, $data)
- {
- $this->mc->set($this->options['prefix'] . $id,
- $data,
- MEMCACHE_COMPRESSED,
- time() + ini_get('session.gc_maxlifetime'));
-
- return true;
- }
-
- /**
- * Destroy session data
- *
- * @param string $id Session id
- *
- * @return boolean
- */
- public function destroy($id)
- {
- $this->mc->delete($this->options['prefix'] . $id);
- return true;
- }
-
- /**
- * Garbage collection
- *
- * @param int $maxlifetime Maximum lifetime
- *
- * @return boolean
- */
- public function gc($maxlifetime)
- {
- return true;
- }
-
- /**
- * Replicate session data to specified target
- *
- * @param string $target Target to replicate to
- * @param string $id Id of record to replicate,
- * if not specified current session id will be used
- *
- * @return boolean
- */
- public function replicate($target, $id = null)
- {
- $msg = 'The replicate feature is not available yet';
- $msg .= ' for the Memcache container.';
-
- throw new HTTP_Session2_Exception($msg);
- }
-}
-?>
+++ /dev/null
-<?php
-/**
- * HTTP_Session2_Exception
- *
- * Base exception class for HTTP_Session2
- *
- * Copyright (c) 2007, Till Klampaeckel
- *
- * All rights reserved.
-
- * Redistribution and use in source and binary forms, with or without modification,
- * are permitted provided that the following conditions are met:
- *
- * * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * * Neither the name of PEAR nor the names of its contributors may be used to
- * endorse or promote products derived from this software without specific prior
- * written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * PHP version 5
- *
- * @category HTTP
- * @package HTTP_Session2
- * @author Till Klampaeckel <till@php.net>
- * @license http://www.opensource.org/licenses/bsd-license.php The BSD License
- * @version CVS: $Id: Exception.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- * @link http://pear.php.net/package/HTTP_Session2
- */
-
-/**
- * PEAR/Exception.php
- * @ignore
- */
-require_once 'PEAR/Exception.php';
-
-/**
- * HTTP_Session2_Exception
- *
- * PHP version 5
- *
- * @category HTTP
- * @package HTTP_Session2
- * @author Till Klampaeckel <till@php.net>
- * @license http://www.opensource.org/licenses/bsd-license.php The BSD License
- * @version Release: @package_version@
- * @link http://pear.php.net/package/HTTP_Session2
- */
-class HTTP_Session2_Exception extends PEAR_Exception
-{
-}
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * A framework for authentication and authorization in PHP applications
- *
- * LiveUser is an authentication/permission framework designed
- * to be flexible and easily extendable.
- *
- * Since it is impossible to have a
- * "one size fits all" it takes a container
- * approach which should enable it to
- * be versatile enough to meet most needs.
- *
- * PHP version 4 and 5
- *
- * LICENSE: This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library 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
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
- * MA 02111-1307 USA
- *
- *
- * @category authentication
- * @package LiveUser
- * @author Markus Wolff <wolff@21st.de>
- * @author Helgi Þormar Þorbjörnsson <dufuz@php.net>
- * @author Lukas Smith <smith@pooteeweet.org>
- * @author Arnaud Limbourg <arnaud@php.net>
- * @author Pierre-Alain Joye <pajoye@php.net>
- * @author Bjoern Kraus <krausbn@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version CVS: $Id: LiveUser.php,v 1.1.1.1 2008/04/28 15:20:46 jamie Exp $
- * @link http://pear.php.net/LiveUser
- */
-
-/**
- * Include PEAR_ErrorStack
- * and Event_Dispatcher classes
- */
-require_once 'PEAR.php';
-require_once 'PEAR/ErrorStack.php';
-require_once 'Event/Dispatcher.php';
-
-/**#@+
- * Error related constants definition
- *
- * @var int
- */
-define('LIVEUSER_ERROR', -1);
-define('LIVEUSER_ERROR_NOT_SUPPORTED', -2);
-define('LIVEUSER_ERROR_CONFIG', -3);
-define('LIVEUSER_ERROR_MISSING_DEPS', -4);
-define('LIVEUSER_ERROR_COOKIE', -7);
-define('LIVEUSER_ERROR_MISSING_FILE', -8);
-define('LIVEUSER_ERROR_FAILED_INSTANTIATION', -9);
-define('LIVEUSER_ERROR_INIT_ERROR', -10);
-define('LIVEUSER_ERROR_MISSING_CLASS', -11);
-define('LIVEUSER_ERROR_WRONG_CREDENTIALS', -12);
-define('LIVEUSER_ERROR_UNKNOWN_EVENT', -13);
-define('LIVEUSER_ERROR_NOT_CALLABLE', -14);
-define('LIVEUSER_ERROR_SESSION_STARTED', -15);
-/**#@-*/
-
-/**#@+
- * Statuses of the current object.
- *
- * @see LiveUser::getStatus
- * @var int
- */
-define('LIVEUSER_STATUS_OK', 1);
-define('LIVEUSER_STATUS_IDLED', -1);
-define('LIVEUSER_STATUS_EXPIRED', -2);
-define('LIVEUSER_STATUS_ISINACTIVE', -3);
-define('LIVEUSER_STATUS_PERMINITERROR', -4);
-define('LIVEUSER_STATUS_AUTHINITERROR', -5);
-define('LIVEUSER_STATUS_UNKNOWN', -6);
-define('LIVEUSER_STATUS_AUTHNOTFOUND', -7);
-define('LIVEUSER_STATUS_LOGGEDOUT', -8);
-define('LIVEUSER_STATUS_AUTHFAILED', -9);
-define('LIVEUSER_STATUS_UNFROZEN', -10);
-define('LIVEUSER_STATUS_EMPTY_HANDLE', -11);
-/**#@-*/
-
-/**
- * The higest possible right level.
- *
- * Levels are only used in the complex container.
- *
- * @var int
- */
-define('LIVEUSER_MAX_LEVEL', 3);
-
-/**#@+
- * Usertypes
- *
- * @var int
- */
-/**
- * lowest user type id
- */
-define('LIVEUSER_ANONYMOUS_TYPE_ID', 0);
-/**
- * User type id
- * It is the highest user type id
- */
-define('LIVEUSER_USER_TYPE_ID', 1);
-/**
- * lowest admin type id
- */
-define('LIVEUSER_ADMIN_TYPE_ID', 2);
-/**
- * look up area admin areas to determine which rights are automatically granted
- */
-define('LIVEUSER_AREAADMIN_TYPE_ID', 3);
-/**
- * from this admin level on all rights are automatically granted
- */
-define('LIVEUSER_SUPERADMIN_TYPE_ID', 4);
-/**
- * higest admin type id
- */
-define('LIVEUSER_MASTERADMIN_TYPE_ID', 5);
-/**#@-*/
-
-/**#@+
- * Section types
- *
- * @var int
- */
-define('LIVEUSER_SECTION_APPLICATION', 1);
-define('LIVEUSER_SECTION_AREA', 2);
-define('LIVEUSER_SECTION_GROUP', 3);
-define('LIVEUSER_SECTION_RIGHT', 4);
-/**#@-*/
-
-// 60 * 60 * 24 == number of seconds in a day
-define('LIVEUSER_DAY_SECONDS', 86400);
-
-// 60 * 60 * 24 * 365 * 30 == number of seconds between 1970 and about 2000
-define('LIVEUSER_COOKIE_DELETE_TIME', 946080000);
-
-/**
- * This is a manager class for a user login system using the LiveUser
- * class. It creates a LiveUser object, takes care of the whole login
- * process and stores the LiveUser object in a session.
- *
- * You can also configure this class to try to connect to more than
- * one server that can store user information - each server requiring
- * a different backend class.
- *
- * An example would be to create a login
- * system for a live website that first queries the local database and
- * if the requested user is not found, it tries to find it in your
- * company's LDAP server. It means you don't have to create several
- * user accounts for your employees so that they can access closed
- * sections of your website - everyone can use one account.
- *
- * NOTE: No browser output may be made before using this class, because
- * it will try to send HTTP headers such as cookies and redirects.
- *
- * Requirements:
- * - Should run on PHP version 4.2.0 (required for PEAR_Errorstack or higher,
- * tested only from 4.2.1 onwards
- *
- * Thanks to:
- * Bjoern Schotte, Kristian Koehntopp, Antonio Guerra
- *
- * @category authentication
- * @package LiveUser
- * @author Markus Wolff <wolff@21st.de>
- * @author Bjoern Kraus <krausbn@php.net>
- * @author Lukas Smith <smith@pooteeweet.org>
- * @author Pierre-Alain Joye <pajoye@php.net>
- * @author Arnaud Limbourg <arnaud@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version Release: @package_version@
- * @link http://pear.php.net/LiveUser
- */
-class LiveUser
-{
- /**
- * LiveUser options set in the configuration file.
- *
- * @var array
- * @access private
- */
- var $_options = array(
- 'debug' => false,
- 'session' => array(
- 'name' => 'PHPSESSID',
- 'varname' => 'ludata',
- 'force_start' => true,
- ),
- 'session_save_handler' => false,
- 'session_cookie_params' => false,
- 'cache_perm' => false,
- 'login' => array(
- 'force' => false,
- 'regenid' => false
- ),
- 'logout' => array(
- 'destroy' => true
- )
- );
-
- /**
- * The auth container object.
- *
- * @var object
- * @access private
- */
- var $_auth = null;
-
- /**
- * The permission container object.
- *
- * @var object
- * @access private
- */
- var $_perm = null;
-
- /**
- * Nested array with the auth containers that shall be queried for user information.
- * Format:
- * <code>
- * array('name' => array("option1" => "value", ....))
- * </code>
- * Typical options are:
- * <ul>
- * - server: The adress of the server being queried (ie. "localhost").
- * - handle: The user name used to login for the server.
- * - password: The password used to login for the server.
- * - database: Name of the database containing user information (this is
- * usually used only by RDBMS).
- * - baseDN: Obviously, this is what you need when using an LDAP server.
- * - connection: Present only if an existing connection shall be used. This
- * contains a reference to an already existing connection resource or object.
- * - type: The container type. This option must always be present, otherwise
- * the LiveUser class cannot include the correct container class definition.
- * - name: The name of the auth container. You can freely define this name,
- * it can be used from within the permission container to see from which
- * auth container a specific user is coming from.
- *</ul>
- *
- * @var array
- * @access private
- */
- var $_authContainers = array();
-
- /**
- * Array of settings the permission container will use to retrieve
- * the user rights.
- * If set to false, no permission container will be used.
- * If that is the case, all calls to checkRight() will return false.
- * The array element 'type' must be present so the LiveUser class can
- * include the correct class definition (example: "DB_Complex").
- *
- * @var bool|array
- * @access private
- */
- var $_permContainer = false;
-
- /**
- * Current status of the LiveUser object.
- *
- * @var string
- * @access private
- * @see LIVEUSER_STATUS_* constants
- */
- var $_status = LIVEUSER_STATUS_UNKNOWN;
-
- /**
- * Error stack
- *
- * @var PEAR_ErrorStack
- * @access private
- */
- var $stack = null;
-
- /**
- * PEAR::Log object
- * used for error logging by ErrorStack.
- *
- * @var Log
- * @access public
- */
- var $log = null;
-
- /**
- * Error codes to message mapping array.
- *
- * @var array
- * @access private
- */
- var $_errorMessages = array(
- LIVEUSER_ERROR => 'Unknown error',
- LIVEUSER_ERROR_NOT_SUPPORTED => 'Feature not supported by the container: %feature%',
- LIVEUSER_ERROR_CONFIG => 'There is an error in the configuration parameters',
- LIVEUSER_ERROR_MISSING_DEPS => 'Missing package depedencies: %msg%',
- LIVEUSER_ERROR_COOKIE => 'There was an error processing the Remember Me cookie',
- LIVEUSER_ERROR_MISSING_FILE => 'The file %file% is missing',
- LIVEUSER_ERROR_FAILED_INSTANTIATION => 'Cannot instantiate class %class%',
- LIVEUSER_ERROR_INIT_ERROR => 'Container was not initialized properly: %container%',
- LIVEUSER_ERROR_MISSING_CLASS => 'Class %class% does not exist in file %file%',
- LIVEUSER_ERROR_WRONG_CREDENTIALS => 'The handle and/or password you submitted are not known',
- LIVEUSER_ERROR_UNKNOWN_EVENT => 'The event %event% is not known',
- LIVEUSER_ERROR_NOT_CALLABLE => 'Callback %callback% is not callable',
- LIVEUSER_ERROR_SESSION_STARTED => 'The session cannot be started because the output already begun (i.e. headers were sent)'
- );
-
- /**
- * Stores the event dispatcher which
- * handles notifications.
- *
- * @var Event_Dispatcher
- * @access protected
- */
- var $dispatcher = null;
-
- /**
- * Constructor. Use the factory or singleton methods.
- *
- * @param bool|object $debug Boolean that indicates if a log instance
- * should be created or an instance of a class
- * that implements the PEAR:Log interface.
- * @return void
- * @access protected
- * @see LiveUser::factory
- * @see LiveUser::singleton
- */
- function LiveUser(&$debug)
- {
- $this->stack = &PEAR_ErrorStack::singleton('LiveUser');
-
- if ($debug) {
- $log =& LiveUser::PEARLogFactory($debug);
- if ($log) {
- $this->log =& $log;
- $this->stack->setLogger($this->log);
- }
- }
-
- $this->stack->setErrorMessageTemplate($this->_errorMessages);
-
- $this->dispatcher =& Event_Dispatcher::getInstance();
- }
-
- /**
- * Returns an instance of the LiveUser class.
- *
- * This array contains private options defined by
- * the following associative keys:
- *
- * <code>
- *
- * array(
- * 'debug' => false/true or an instance of a class that implements the PEAR::Log interface
- * 'session' => array(
- * 'name' => 'liveuser session name',
- * 'varname' => 'liveuser session var name'
- * ),
- * // The session_save_handler options are optional. If they are specified,
- * // session_set_save_handler() will be called with the parameters
- * 'session_save_handler' => array(
- * 'open' => 'name of the open function/method',
- * 'close' => 'name of the close function/method',
- * 'read' => 'name of the read function/method',
- * 'write' => 'name of the write function/method',
- * 'destroy' => 'name of the destroy function/method',
- * 'gc' => 'name of the gc function/method',
- * ),
- * // The session_cookie_params options are optional. If they are specified,
- * // session_set_cookie_params() will be called with the parameters
- * 'session_cookie_params' => array(
- * 'lifetime' => 'Cookie lifetime in days',
- * 'path' => 'Cookie path',
- * 'domain' => 'Cookie domain',
- * 'secure' => 'Cookie send only over secure connections',
- * ),
- * 'cache_perm' => if the permission data should be cached inside the session
- * 'login' => array(
- * 'force' => 'Should the user be forced to login'
- * 'regenid' => 'Should the session be regenerated on login'
- * ),
- * 'logout' => array(
- * 'destroy' => 'Whether to destroy the session on logout' false or true
- * ),
- * // The cookie options are optional. If they are specified, the Remember Me
- * // feature is activated.
- * 'cookie' => array(
- * 'name' => 'Name of Remember Me cookie',
- * 'lifetime' => 'Cookie lifetime in days',
- * 'path' => 'Cookie path',
- * 'domain' => 'Cookie domain',
- * 'secret' => 'Secret key used for cookie value encryption',
- * 'savedir' => '/absolute/path/to/writeable/directory' // No trailing slash (/) !
- * 'secure' => 'Cookie send only over secure connections',
- * ),
- * 'authContainers' => array(
- * 'name' => array(
- * 'type' => 'auth container name',
- * 'expireTime' => 'maximum lifetime of a session in seconds',
- * 'idleTime' => 'maximum amount of time between two request',
- * 'passwordEncryptionMode'=> 'what encryption method to use',
- * 'secret' => 'secret to use in password encryption',
- * 'storage' => array(
- * 'dbc' => 'db connection object, use this or dsn',
- * 'dsn' => 'database dsn, use this or connection',
- * 'handles' => 'array of handle fields to find a user on login; works with DB, MDB, MDB2 and PDO containers',
- * ),
- * 'externalValues' => array(
- * 'values' => 'reference to an array',
- * 'keysToCheck' => 'array of keys to check in the array passed'
- * ),
- * ),
- * ),
- * 'permContainer' => array(
- * 'type' => 'perm container name',
- * 'storage' => array(
- * 'storage container name' => array(
- * 'dbc' => 'db connection object, use this or dsn',
- * 'dsn' => 'database dsn, use this or connection',
- * 'prefix' => 'table prefix'
- * 'tables' => 'array containing additional tables or fields in existing tables',
- * 'fields' => 'array containing any additional or non-default field types',
- * 'alias' => 'array containing any additional or non-default field alias',
- * 'force_seq' => 'if the use of (emulated) sequences should forced instead of using autoincrement where applicable',
- * ),
- * ),
- * ),
- *
- * </code>
- *
- * Other options in the configuration file relative to
- * the Auth and Perm containers depend on what the
- * containers expect. Refer to the Containers documentation.
- * The examples for containers provided are just general
- * do not reflect all the options for all containers.
- *
- * @param array Config array to configure.
- * @return LiveUser Returns an object of either LiveUser or false on error
- * if so use LiveUser::getErrors() to get the errors
- *
- * @access public
- * @see LiveUser::getErrors
- */
- function &factory(&$conf)
- {
- $debug = false;
- if (array_key_exists('debug', $conf)) {
- $debug =& $conf['debug'];
- }
-
- $obj = &new LiveUser($debug);
-
- if (is_array($conf)) {
- $obj->readConfig($conf);
- }
-
- return $obj;
- }
-
- /**
- * This uses the singleton pattern, making sure you have one and
- * only instance of the class.
- *
- * <b>In PHP4 you MUST call this method with the
- * $var = &LiveUser::singleton() syntax.
- * Without the ampersand (&) in front of the method name, you will not get
- * a reference, you will get a copy.</b>
- *
- * @param array Config array to configure.
- * @param string Signature by which the given instance can be referenced later
- * @return LiveUser Returns an object of either LiveUser or false on failure
- *
- * @access public
- * @see LiveUser::factory
- * @see LiveUser::getErrors
- */
- function &singleton(&$conf, $signature = null)
- {
- static $instances;
- if (!isset($instances)) {
- $instances = array();
- }
-
- if (is_null($signature)) {
- if (empty($instances)) {
- $signature = uniqid('LU');
- } else {
- $signature = key($instances);
- }
- }
-
- if (!array_key_exists($signature, $instances)) {
- $instances[$signature] =& LiveUser::factory($conf);
- }
-
- return $instances[$signature];
- }
-
- /**
- * Wrapper method to get errors from the Error Stack.
- *
- * @return array|bool an array of the errors or false if there are no errors
- *
- * @access public
- */
- function getErrors()
- {
- if (is_object($this->stack)) {
- return $this->stack->getErrors();
- }
- return false;
- }
-
- /**
- * Loads a PEAR class.
- *
- * @param string classname to load
- * @param bool if errors should be supressed from the stack
- * @return bool true success or false on failure
- *
- * @access public
- */
- function loadClass($classname, $supress_error = false)
- {
- if (!LiveUser::classExists($classname)) {
- $filename = str_replace('_', '/', $classname).'.php';
- @include_once($filename);
- if (!LiveUser::classExists($classname) && !$supress_error) {
- if (!LiveUser::fileExists($filename)) {
- $msg = 'File for the class does not exist ' . $classname;
- } else {
- $msg = 'Parse error in the file for class' . $classname;
- }
- PEAR_ErrorStack::staticPush('LiveUser', LIVEUSER_ERROR_CONFIG,
- 'exception', array(), $msg);
- return false;
- }
- }
- return true;
- }
-
- /**
- * Creates an instance of an auth container class.
- *
- * @param array Array containing the configuration.
- * @param string Name of the container we'll be using.
- * @param string Prefix of the class that will be used.
- * @return object|false Returns an instance of an auth container
- * class or false on error
- *
- * @access public
- */
- function &authFactory(&$conf, $containerName, $classprefix = 'LiveUser_')
- {
- $auth = false;
- $classname = $classprefix.'Auth_' . $conf['type'];
- if (LiveUser::loadClass($classname)) {
- $auth = &new $classname();
- if ($auth->init($conf, $containerName) === false) {
- $auth = false;
- }
- }
- return $auth;
- }
-
- /**
- * Creates an instance of an perm container class.
- *
- * @param array Array containing the configuration.
- * @param string Prefix of the class that will be used.
- * @return object|false Returns an instance of a perm container
- * class or false on error
- *
- * @access public
- */
- function &permFactory(&$conf, $classprefix = 'LiveUser_')
- {
- $perm = false;
- $classname = $classprefix.'Perm_' . $conf['type'];
- if (LiveUser::loadClass($classname)) {
- $perm = &new $classname();
- if ($perm->init($conf) === false) {
- $perm = false;
- }
- }
-
- return $perm;
- }
-
- /**
- * Returns an instance of a storage Container class.
- *
- * @param array configuration array to pass to the storage container
- * @param string Prefix of the class that will be used.
- * @return object|false will return an instance of a Storage container
- * or false upon error
- *
- * @access protected
- */
- function &storageFactory(&$confArray, $classprefix = 'LiveUser_Perm_')
- {
- end($confArray);
- $key = key($confArray);
- $count = count($confArray);
- $storageName = $classprefix.'Storage_' . $key;
- if (!LiveUser::loadClass($storageName, true)) {
- if ($count <= 1) {
- $storage = false;
- return $storage;
- // if the storage container does not exist try the next one in the stack
- } elseif ($count > 1) {
- // since we are using pass by ref we cannot pop from the original array
- $keys = array_keys($confArray);
- array_pop($keys);
- $newConfArray = array();
- foreach ($keys as $key) {
- $newConfArray[$key] =& $confArray[$key];
- }
- $storage =& LiveUser::storageFactory($newConfArray, $classprefix);
- return $storage;
- }
- }
- $storageConf =& $confArray[$key];
- $newConfArray = array();
- foreach ($confArray as $keyNew => $foo) {
- if ($key !== $keyNew) {
- $newConfArray[$keyNew] =& $confArray[$keyNew];
- }
- }
- $storage = &new $storageName();
- if ($storage->init($storageConf, $newConfArray) === false) {
- $storage = false;
- }
- return $storage;
- }
-
- /**
- * Clobbers two arrays together.
- *
- * Function taken from the user notes of array_merge_recursive function
- * used in LiveUser::readConfig() and may be called statically
- *
- * @param array array that should be clobbered
- * @param array array that should be clobbered
- * @return array|false array on success and false on error
- *
- * @access public
- * @author kc@hireability.com
- */
- function arrayMergeClobber($a1, $a2)
- {
- if (!is_array($a1) || !is_array($a2)) {
- return false;
- }
- foreach ($a2 as $key => $val) {
- if (is_array($val) && array_key_exists($key, $a1) && is_array($a1[$key])) {
- $a1[$key] = LiveUser::arrayMergeClobber($a1[$key], $val);
- } else {
- $a1[$key] = $val;
- }
- }
- return $a1;
- }
-
- /**
- * Checks if a file exists in the include path.
- *
- * @param string filename
- * @return bool true success and false on error
- *
- * @access public
- */
- function fileExists($file)
- {
- // safe_mode does notwork with is_readable()
- if (ini_get('safe_mode')) {
- $fp = @fopen($file, 'r', true);
- if (is_resource($fp)) {
- @fclose($fp);
- return true;
- }
- } else {
- $dirs = explode(PATH_SEPARATOR, ini_get('include_path'));
- foreach ($dirs as $dir) {
- if (is_readable($dir . DIRECTORY_SEPARATOR . $file)) {
- return true;
- }
- }
- }
- return false;
- }
-
- /**
- * Checks if a class exists without triggering __autoload
- *
- * @param string classname
- * @return bool true success and false on error
- *
- * @access public
- */
- function classExists($classname)
- {
- if (version_compare(phpversion(), "5.0", ">=")) {
- return class_exists($classname, false);
- }
- return class_exists($classname);
- }
-
- /**
- * Reads the configuration array.
- *
- * @param array|file Conf array or file path to configuration
- * @param string Name of array containing the configuration
- * @return bool true on success or false on failure
- *
- * @access public
- * @see LiveUser::factory
- */
- function readConfig($conf)
- {
- if (array_key_exists('authContainers', $conf)) {
- $this->_authContainers =& $conf['authContainers'];
- }
- if (array_key_exists('permContainer', $conf)) {
- $this->_permContainer =& $conf['permContainer'];
- }
-
- $this->_options = LiveUser::arrayMergeClobber($this->_options, $conf);
- if (array_key_exists('cookie', $this->_options) && $this->_options['cookie']) {
- $cookie_default = array(
- 'name' => 'ludata',
- 'lifetime' => '365',
- 'path' => '/',
- 'domain' => '',
- 'secret' => 'secret',
- );
- if (is_array($this->_options['cookie'])) {
- $this->_options['cookie'] =
- LiveUser::arrayMergeClobber($cookie_default, $this->_options['cookie']);
- } else {
- $this->_options['cookie'] = $cookie_default;
- }
- }
-
- return true;
- }
-
- /**
- * Determines if loading of PEAR::Log is necessary.
- *
- * If an object is passed it is returned, otherwise Log is loaded
- * and instantiated.
- *
- * @param bool|Log Boolean that indicates if a log instance
- * should be created or an instance of a class
- * that implements the PEAR:Log interface.
- * @return log instance of the given log class
- *
- * @access protected
- */
- function &PEARLogFactory(&$log)
- {
- if (empty($log) || is_object($log)) {
- return $log;
- }
-
- require_once 'Log.php';
- $log =& Log::factory('composite');
- if (!is_a($log, 'Log_composite')) {
- $this->stack->push(
- LIVEUSER_ERROR_CONFIG, 'exception', array(),
- 'Could not create Log instance'
- );
- $return = false;
- return $return;
- }
- $conf = array(
- 'colors' => array(
- PEAR_LOG_EMERG => 'red',
- PEAR_LOG_ALERT => 'orange',
- PEAR_LOG_CRIT => 'yellowgreen',
- PEAR_LOG_ERR => 'green',
- PEAR_LOG_WARNING => 'blue',
- PEAR_LOG_NOTICE => 'indigo',
- PEAR_LOG_INFO => 'violet',
- PEAR_LOG_DEBUG => 'black',
- ),
- );
- $winlog =& Log::factory('win', 'LiveUser', 'LiveUser', $conf);
- if (!is_a($winlog, 'Log_win')) {
- $this->stack->push(
- LIVEUSER_ERROR_CONFIG, 'exception', array(),
- 'Could not create Log "window" instance'
- );
- $return = false;
- return $return;
- }
- $log->addChild($winlog);
-
- return $log;
- }
-
- /**
- * Decrypts a password so that it can be compared with the user input.
- * Uses the algorithm defined in the passwordEncryptionMode parameter.
- *
- * @param string the encrypted password
- * @param string the encryption mode
- * @return string The decrypted password
- */
- function decryptPW($encryptedPW, $passwordEncryptionMode, $secret)
- {
- if (empty($encryptedPW) && $encryptedPW !== 0) {
- return '';
- }
-
- $passwordEncryptionMode = strtolower($passwordEncryptionMode);
-
- if ($passwordEncryptionMode === 'plain') {
- return $encryptedPW;
- }
-
- if ($passwordEncryptionMode === 'rc4') {
- return LiveUser::cryptRC4($decryptedPW, $secret, false);
- }
-
- PEAR_ErrorStack::staticPush('LiveUser', LIVEUSER_ERROR_NOT_SUPPORTED, 'error', array(),
- 'Could not find the requested decryption function : ' . $passwordEncryptionMode);
- return false;
- }
-
- /**
- * Encrypts a password for storage in a backend container.
- * Uses the algorithm defined in the passwordEncryptionMode parameter.
- *
- * @param string password to encrypt
- * @param string the encryption mode
- * @param string token to use to encrypt data
- * @return string The encrypted password
- */
- function encryptPW($plainPW, $passwordEncryptionMode, $secret)
- {
- if (empty($plainPW) && $plainPW !== 0) {
- return '';
- }
-
- $passwordEncryptionMode = strtolower($passwordEncryptionMode);
-
- if ($passwordEncryptionMode == 'plain') {
- return $plainPW;
- }
-
- if ($passwordEncryptionMode == 'md5') {
- return md5($plainPW);
- }
-
- if (extension_loaded('hash') && in_array($passwordEncryptionMode, hash_algos())) {
- return hash($passwordEncryptionMode, $plainPW);
- }
-
- if ($passwordEncryptionMode == 'rc4') {
- return LiveUser::cryptRC4($plainPW, $secret, true);
- }
-
- if (function_exists('sha1') && $passwordEncryptionMode == 'sha1') {
- return sha1($plainPW);
- }
-
- PEAR_ErrorStack::staticPush('LiveUser', LIVEUSER_ERROR_NOT_SUPPORTED, 'error', array(),
- 'Could not find the requested encryption function : ' . $passwordEncryptionMode);
- return false;
- }
-
- /**
- * Creates an instance of the PEAR::Crypt_Rc4 class.
- *
- * @param string token to use to encrypt data
- * @return Crypt_RC4 returns an instance of the Crypt_RC4 class
- *
- * @access public
- */
- function &cryptRC4Factory($secret)
- {
- $rc4 = false;
- if (LiveUser::loadClass('Crypt_Rc4')) {
- $rc4 =& new Crypt_Rc4($secret);
- }
- return $rc4;
- }
-
- /**
- * Crypts data using mcrypt or userland if not available.
- *
- * @param string data
- * @param string secret key
- * @param bool true if it should be crypted,
- * false if it should be decrypted
- * @return string (de-)crypted data
- *
- * @access public
- */
- function cryptRC4($data, $secret, $crypt = true)
- {
- if (function_exists('mcrypt_module_open')) {
- $td = mcrypt_module_open('tripledes', '', 'ecb', '');
- $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size ($td), MCRYPT_RAND);
- mcrypt_generic_init($td, $secret, $iv);
- if ($crypt) {
- $data = mcrypt_generic($td, $data);
- } else {
- $data = mdecrypt_generic($td, $data);
- }
- mcrypt_generic_deinit($td);
- mcrypt_module_close($td);
- } else {
- $rc4 =& LiveUser::cryptRC4Factory($secret);
- if (!$rc4) {
- $this->stack->push(
- LIVEUSER_ERROR_CONFIG, 'exception', array(),
- 'RememberMe feature requires either the mcrypt extension or PEAR::Crypt_RC4'
- );
- return false;
- }
- if ($crypt) {
- $rc4->crypt($data);
- } else {
- $rc4->decrypt($data);
- }
- }
-
- return $data;
- }
-
- /**
- * Sets an option after the configuration array has been loaded.
- *
- * You can override a specific option calling this method.
- *
- * @param string option name
- * @param mixed value for the option
- * @return bool true on success or false on failure
- *
- * @access public
- * @see LiveUser::_options
- */
- function setOption($option, $value)
- {
- if (array_key_exists($option, $this->_options)) {
- $this->_options[$option] = $value;
- return true;
- }
- $this->stack->push(LIVEUSER_ERROR_CONFIG, 'exception', array(),
- "unknown option $option");
- return false;
- }
-
- /**
- * Returns the value of an option from the configuration array.
- *
- * @param string option name
- * @return mixed the option value or false on failure
- *
- * @access public
- */
- function getOption($option)
- {
- if (array_key_exists($option, $this->_options)) {
- return $this->_options[$option];
- }
- $this->stack->push(LIVEUSER_ERROR_CONFIG, 'exception', array(),
- "unknown option $option");
- return false;
- }
-
- /**
- * Sets the session handler and name and starts the session if headers have
- * not been send yet.
- *
- * @return bool true on success or false on failure
- *
- * @access private
- */
- function _startSession()
- {
- // set session save handler if needed
- if ($this->_options['session_save_handler']) {
- session_set_save_handler(
- $this->_options['session_save_handler']['open'],
- $this->_options['session_save_handler']['close'],
- $this->_options['session_save_handler']['read'],
- $this->_options['session_save_handler']['write'],
- $this->_options['session_save_handler']['destroy'],
- $this->_options['session_save_handler']['gc']
- );
- }
- if ($this->_options['session_cookie_params']) {
- session_set_cookie_params((
- (LIVEUSER_DAY_SECONDS * $this->_options['session_cookie_params']['lifetime'])),
- $this->_options['session_cookie_params']['path'],
- $this->_options['session_cookie_params']['domain'],
- $this->_options['session_cookie_params']['secure']);
- }
- // Set the name of the current session
- session_name($this->_options['session']['name']);
- // Check if we can safely start the session
- if (headers_sent()) {
- $this->stack->push(
- LIVEUSER_ERROR_SESSION_STARTED, 'exception'
- );
- return;
- }
- // If there's no session yet, start it now
- @session_start();
-
- return true;
- }
-
- /**
- * Tries to retrieve the auth object from session and checks possible timeouts.
- *
- * @return bool true if init process well, false if something went wrong.
- *
- * @access public
- */
- function init()
- {
- if ($this->_options['session']['force_start']) {
- $this->_startSession();
- }
-
- // Try to fetch auth object from session
- $isReturningUser = $this->_unfreeze();
-
- // current timestamp
- $now = time();
-
- if ($this->isLoggedIn()) {
- if ($isReturningUser) {
- // Check if authentication session is expired.
- if ($this->getProperty('expireTime') > 0
- && ($this->getProperty('currentLogin') + $this->getProperty('expireTime')) < $now
- ) {
- $this->logout(false);
- $this->_status = LIVEUSER_STATUS_EXPIRED;
- $this->dispatcher->post($this, 'onExpired');
- // Check if maximum idle time is reached.
- } elseif ($this->getProperty('idleTime') > 0
- && array_key_exists('idle', $_SESSION[$this->_options['session']['varname']])
- && ($_SESSION[$this->_options['session']['varname']]['idle'] + $this->getProperty('idleTime')) < $now
- ) {
- $this->logout(false);
- $this->_status = LIVEUSER_STATUS_IDLED;
- $this->dispatcher->post($this, 'onIdled');
- }
- }
- }
-
- // set idle time and status
- if ($this->isLoggedIn()) {
- $_SESSION[$this->_options['session']['varname']]['idle'] = $now;
- $this->_status = LIVEUSER_STATUS_OK;
- // Force user login.
- } elseif ($this->_options['login']['force']) {
- $this->dispatcher->post($this, 'forceLogin');
- }
-
- return true;
- }
-
- /**
- * Tries to log the user in by trying all the Auth containers defined
- * in the configuration file until there is a success or a failure.
- *
- * @param string handle of the user trying to authenticate
- * @param string password of the user trying to authenticate
- * @param bool set if remember me is set, requires cookie otion
- * @param bool|int if the user data should be read using the auth user id
- * @return bool true on success or false on failure
- *
- * @access public
- */
- function login($handle = '', $passwd = '', $remember = false, $auth_user_id = false)
- {
- if ($remember && $auth_user_id) {
- $this->_status = LIVEUSER_STATUS_AUTHINITERROR;
- $this->stack->push(LIVEUSER_ERROR, 'exception',
- array('msg' => 'Remember me feature is incompatible logging in via the auth_user_id'));
- return false;
- }
-
- if (empty($handle) && $remember) {
- $result = $this->readRememberCookie();
- if (!is_array($result)) {
- if ($this->_status == LIVEUSER_STATUS_UNKNOWN) {
- $this->_status = LIVEUSER_STATUS_EMPTY_HANDLE;
- }
- return false;
- }
- $handle = $result['handle'];
- $passwd = $result['passwd'];
- }
-
- $this->_status = LIVEUSER_STATUS_AUTHFAILED;
- $this->_auth = $this->_perm = null;
-
- //loop into auth containers
- $containerNames = array_keys($this->_authContainers);
- foreach ($containerNames as $containerName) {
- $auth =& LiveUser::authFactory($this->_authContainers[$containerName], $containerName);
- if ($auth === false) {
- $this->_status = LIVEUSER_STATUS_AUTHINITERROR;
- $this->stack->push(LIVEUSER_ERROR, 'exception',
- array('msg' => 'Could not instanciate auth container: '.$containerName));
- return false;
- }
- $login = $auth->login($handle, $passwd, $auth_user_id);
- if ($login === false) {
- $this->_status = LIVEUSER_STATUS_AUTHINITERROR;
- $this->stack->push(LIVEUSER_ERROR, 'exception',
- array('msg' => 'Could not execute login method: '.$containerName));
- return false;
- }
- if ($auth->loggedIn) {
- $this->_auth =& $auth;
- if ($remember) {
- $this->setRememberCookie($handle, $passwd);
- }
- $this->_status = LIVEUSER_STATUS_OK;
- // Create permission object
- if (is_array($this->_permContainer)) {
- $perm =& LiveUser::permFactory($this->_permContainer);
- if ($perm === false) {
- $this->_status = LIVEUSER_STATUS_PERMINITERROR;
- $this->stack->push(LIVEUSER_ERROR, 'exception',
- array('msg' => 'Could not instanciate perm container of type: ' . $this->_permContainer['type']));
- return false;
- }
- if (!$perm->mapUser($auth->getProperty('auth_user_id'), $containerName)) {
- $this->dispatcher->post($this, 'onFailedMapping');
- } else {
- $this->_perm =& $perm;
- }
- }
- $this->_freeze();
- break;
- } elseif (!is_null($login) && !$auth->getProperty('is_active')) {
- $this->_status = LIVEUSER_STATUS_ISINACTIVE;
- break;
- }
- }
-
- if (!$this->isLoggedIn()) {
- $this->dispatcher->post($this, 'onFailedLogin');
- return false;
- }
-
- // user has just logged in
- if (!$this->_options['session']['force_start']) {
- $this->_startSession();
- }
- if ($this->_options['login']['regenid']) {
- session_regenerate_id();
- }
- $this->dispatcher->post($this, 'onLogin');
-
- return true;
- }
-
- /**
- * Gets auth and perm container objects back from session and tries
- * to give them an active database/whatever connection again.
- *
- * @return bool true on success or false on failure
- *
- * @access private
- */
- function _unfreeze()
- {
- if (!$this->_options['session']['force_start']) {
- if (!array_key_exists($this->_options['session']['name'], $_REQUEST)) {
- return false;
- }
- $this->_startSession();
- }
-
- if (isset($_SESSION[$this->_options['session']['varname']])
- && array_key_exists('auth', $_SESSION[$this->_options['session']['varname']])
- && is_array($_SESSION[$this->_options['session']['varname']]['auth'])
- && array_key_exists('auth_name', $_SESSION[$this->_options['session']['varname']])
- && strlen($_SESSION[$this->_options['session']['varname']]['auth_name']) > 0
- ) {
- $containerName = $_SESSION[$this->_options['session']['varname']]['auth_name'];
- $auth =& LiveUser::authFactory($this->_authContainers[$containerName], $containerName);
- if ($auth === false) {
- $this->stack->push(LIVEUSER_ERROR, 'exception',
- array('msg' => 'Could not instanciate auth container: '.$containerName));
- return false;
- }
- if ($auth->unfreeze($_SESSION[$this->_options['session']['varname']]['auth'])) {
- $auth->containerName = $_SESSION[$this->_options['session']['varname']]['auth_name'];
- $this->_auth = &$auth;
- if (array_key_exists('perm', $_SESSION[$this->_options['session']['varname']])
- && $_SESSION[$this->_options['session']['varname']]['perm']
- ) {
- $perm =& LiveUser::permFactory($this->_permContainer);
- if ($perm === false) {
- $this->stack->push(LIVEUSER_ERROR, 'exception',
- array('msg' => 'Could not instanciate perm container of type: ' . $this->_permContainer));
- return $perm;
- }
- if ($this->_options['cache_perm']) {
- $result = $perm->unfreeze($this->_options['session']['varname']);
- } else {
- $result = $perm->mapUser($auth->getProperty('auth_user_id'), $auth->containerName);
- }
- if ($result) {
- $this->_perm = &$perm;
- }
- }
- $this->_status = LIVEUSER_STATUS_UNFROZEN;
- $this->dispatcher->post($this, 'onUnfreeze');
- return true;
- }
- }
-
- return false;
- }
-
- /**
- * Stores all properties in the session.
- *
- * @return bool true on sucess or false on failure
- *
- * @access private
- */
- function _freeze()
- {
- if (is_a($this->_auth, 'LiveUser_Auth_Common') && $this->isLoggedIn()) {
- // Bind objects to session
- $_SESSION[$this->_options['session']['varname']] = array();
- $_SESSION[$this->_options['session']['varname']]['auth'] = $this->_auth->freeze();
- $_SESSION[$this->_options['session']['varname']]['auth_name'] = $this->_auth->containerName;
- if (is_a($this->_perm, 'LiveUser_Perm_Simple')) {
- $_SESSION[$this->_options['session']['varname']]['perm'] = true;
- if ($this->_options['cache_perm']) {
- $this->_perm->freeze($this->_options['session']['varname']);
- }
- }
- return true;
- }
- $this->stack->push(LIVEUSER_ERROR_CONFIG, 'exception', array(),
- 'No data available to store inside session');
- return false;
- }
-
- /**
- * Properly disconnect resources in the active container.
- *
- * @return bool true on success or false on failure
- *
- * @access public
- */
- function disconnect()
- {
- if (is_a($this->_auth, 'LiveUser_Auth_Common')) {
- $result = $this->_auth->disconnect();
- if ($result === false) {
- return false;
- }
- $this->_auth = null;
- }
- if (is_a($this->_perm, 'LiveUser_Perm_Simple')) {
- $result = $this->_perm->disconnect();
- if ($result === false) {
- return false;
- }
- $this->_perm = null;
- }
- return true;
- }
-
- /**
- * If cookies are allowed, this method checks if the user wanted
- * a cookie to be set so he doesn't have to enter handle and password
- * for his next login. If true, it will set the cookie.
- *
- * @param string handle of the user trying to authenticate
- * @param string password of the user trying to authenticate
- * @return bool true if the cookie can be set, false otherwise
- *
- * @access public
- */
- function setRememberCookie($handle, $passwd)
- {
- if (!array_key_exists('cookie', $this->_options)) {
- return false;
- }
-
- $store_id = md5($handle . $passwd);
-
- $dir = $this->_options['cookie']['savedir'];
- $file = $dir . '/' . $store_id . '.lu';
-
- if (!is_writable($dir)) {
- $this->stack->push(LIVEUSER_ERROR_CONFIG, 'exception', array(),
- 'Cannot create file, please check path and permissions');
- return false;
- }
-
- $fh = @fopen($file, 'wb');
- if (!$fh) {
- $this->stack->push(LIVEUSER_ERROR_CONFIG, 'exception', array(),
- 'Cannot open file for writting');
- return false;
- }
-
- $passwd_id = md5($passwd);
- $crypted_data = LiveUser::cryptRC4(
- serialize(array($passwd_id, $passwd)),
- $this->_options['cookie']['secret'],
- true
- );
-
- $write = fwrite($fh, $crypted_data);
- fclose($fh);
- if (!$write) {
- $this->stack->push(LIVEUSER_ERROR_CONFIG, 'exception', array(),
- 'Cannot save cookie data');
- return false;
- }
-
- $setcookie = setcookie(
- $this->_options['cookie']['name'],
- $store_id . $passwd_id . $handle,
- (time() + (LIVEUSER_DAY_SECONDS * $this->_options['cookie']['lifetime'])),
- $this->_options['cookie']['path'],
- $this->_options['cookie']['domain'],
- $this->_options['cookie']['secure']
- );
-
- if (!$setcookie) {
- @unlink($file);
- $this->stack->push(LIVEUSER_ERROR_CONFIG, 'exception', array(),
- 'Unable to set cookie');
- return false;
- }
-
- return true;
- }
-
- /**
- * Handles the retrieval of the login data from the rememberMe cookie.
- *
- * @return bool true on success or false on failure
- *
- * @access public
- */
- function readRememberCookie()
- {
- if (!array_key_exists('cookie', $this->_options)
- || !array_key_exists($this->_options['cookie']['name'], $_COOKIE)
- ) {
- return false;
- }
-
- if (strlen($_COOKIE[$this->_options['cookie']['name']]) < 65
- || preg_match('/[^a-z0-9]/i', substr($_COOKIE[$this->_options['cookie']['name']], 0, 64))
- ) {
- $this->deleteRememberCookie();
- }
- $cookieData = $_COOKIE[$this->_options['cookie']['name']];
-
- $store_id = substr($cookieData, 0, 32);
- $passwd_id = substr($cookieData, 32, 32);
- $handle = substr($cookieData, 64);
-
- $dir = $this->_options['cookie']['savedir'];
-
- $fh = @fopen($dir . '/' . $store_id . '.lu', 'rb');
- if (!$fh) {
- $this->deleteRememberCookie();
- $this->stack->push(LIVEUSER_ERROR_CONFIG, 'exception', array(),
- 'Cannot open file for reading');
- return false;
- }
-
- $fields = fread($fh, 4096);
- fclose($fh);
- if (!$fields) {
- $this->deleteRememberCookie();
- $this->stack->push(LIVEUSER_ERROR_CONFIG, 'exception', array(),
- 'Cannot read file');
- return false;
- }
-
- $serverData = @unserialize(
- LiveUser::cryptRC4($fields, $this->_options['cookie']['secret'], false)
- );
-
- if (!is_array($serverData) || count($serverData) != 2) {
- $this->deleteRememberCookie();
- $this->stack->push(LIVEUSER_ERROR_COOKIE, 'exception', array(),
- 'Incorrect array structure');
- return false;
- }
-
- if ($serverData[0] != $passwd_id) {
- // Delete cookie if it's not valid, keeping it messes up the
- // authentication process
- $this->deleteRememberCookie();
- $this->stack->push(LIVEUSER_ERROR_COOKIE, 'error', array(),
- 'Passwords hashes do not match in cookie in LiveUser::readRememberMeCookie()');
- return false;
- }
-
- return array('handle' => $handle, 'passwd' => $serverData[1]);
- }
-
- /**
- * Deletes the rememberMe cookie.
- *
- * @return bool true on success or false on failure
- *
- * @access public
- */
- function deleteRememberCookie()
- {
- if (!array_key_exists('cookie', $this->_options)
- || !array_key_exists($this->_options['cookie']['name'], $_COOKIE)
- ) {
- return false;
- }
-
- if (preg_match('/[^a-z0-9]/i', substr($_COOKIE[$this->_options['cookie']['name']], 0, 32))) {
- $this->stack->push(LIVEUSER_ERROR_COOKIE, 'error', array(),
- 'Malformed rememberme cookie identifer in LiveUser::deleteRememberCookie()');
- return false;
- }
- $cookieData = $_COOKIE[$this->_options['cookie']['name']];
-
- $store_id = substr($cookieData, 0, 32);
- @unlink($this->_options['cookie']['savedir'] . '/'.$store_id.'.lu');
-
- unset($_COOKIE[$this->_options['cookie']['name']]);
- setcookie($this->_options['cookie']['name'],
- false,
- LIVEUSER_COOKIE_DELETE_TIME,
- $this->_options['cookie']['path'],
- $this->_options['cookie']['domain'],
- $this->_options['cookie']['secure']
- );
-
- return true;
- }
-
- /**
- * This logs the user out and destroys the session object if the
- * configuration option is set.
- *
- * @param bool set to false if no events should be fired b yhte logout
- * @return bool true on success or false on failure
- *
- * @access public
- */
- function logout($direct = true)
- {
- $this->_status = LIVEUSER_STATUS_LOGGEDOUT;
-
- if ($direct) {
- // trigger event 'onLogout' as replacement for logout callback function
- $this->dispatcher->post($this, 'onLogout');
- // If there's a cookie and the session hasn't idled or expired, kill that one too...
- $this->deleteRememberCookie();
- }
-
- // If the session should be destroyed, do so now...
- if ($this->_options['logout']['destroy']) {
- session_unset();
- session_destroy();
- if ($this->_options['session']['force_start']) {
- $this->_startSession();
- }
- } elseif (array_key_exists($this->_options['session']['varname'], $_SESSION)) {
- unset($_SESSION[$this->_options['session']['varname']]);
- }
-
- $this->disconnect();
-
- if ($direct) {
- // trigger event 'postLogout', can be used to do a redirect
- $this->dispatcher->post($this, 'postLogout');
- }
-
- return true;
- }
-
- /**
- * Wrapper method for the permission object's own checkRight method.
- * Use this method to determine if a user has a given right or set
- * of rights.
- *
- * @param array|int A right id or an array of rights.
- * @return int|false level if the user has the right/rights false if not
- *
- * @access public
- */
- function checkRight($rights)
- {
- if (is_null($rights)) {
- return LIVEUSER_MAX_LEVEL;
- }
-
- if (is_a($this->_perm, 'LiveUser_Perm_Simple')) {
- if (is_array($rights)) {
- // assume user has the right in order to have min() work
- $hasright = LIVEUSER_MAX_LEVEL;
- foreach ($rights as $currentright) {
- $level = $this->_perm->checkRight($currentright);
- if (!$level) {
- return false;
- }
- $hasright = min($hasright, $level);
- }
- return $hasright;
- } else {
- return $this->_perm->checkRight($rights);
- }
- } elseif ($rights === 0 && is_a($this->_auth, 'LiveUser_Auth_Common')) {
- return LIVEUSER_MAX_LEVEL;
- }
-
- return false;
- }
-
- /**
- * Wrapper method for the permission object's own checkRight and checkLevel methods
- *
- * @param array|int A right id or an array of rights.
- * @param array|int Id or array of Ids of the owner of the
- ressource for which the right is requested.
- * @param array|int Id or array of Ids of the group of the
- * ressource for which the right is requested.
- * @return bool true on success or false on failure
- *
- * @access public
- */
- function checkRightLevel($rights, $owner_user_id, $owner_group_id)
- {
- $level = $this->checkRight($rights);
- if (is_a($this->_perm, 'LiveUser_Perm_Complex')) {
- $level = $this->_perm->checkLevel($level, $owner_user_id, $owner_group_id);
- }
-
- return (bool)$level;
- }
-
- /**
- * Wrapper method for the permission object's own checkGroup method.
- *
- * @param array|int A group id or an array of groups.
- * @return bool true on success or false on failure
- *
- * @access public
- */
- function checkGroup($groups)
- {
- if (is_null($groups)) {
- return true;
- }
-
- if (is_a($this->_perm, 'LiveUser_Perm_Medium')) {
- if (is_array($groups)) {
- foreach ($groups as $group) {
- if (!$this->_perm->checkGroup($group)) {
- return false;
- }
- }
- return true;
- } else {
- return $this->_perm->checkGroup($groups);
- }
- }
-
- return false;
- }
-
- /**
- * Checks if a user is logged in.
- *
- * @return bool true if user is logged in, false if not
- *
- * @access public
- */
- function isLoggedIn()
- {
- if (!is_a($this->_auth, 'LiveUser_Auth_Common')) {
- return false;
- }
-
- return $this->_auth->loggedIn;
- }
-
- /**
- * Function that determines if the user exists but hasn't yet been declared
- * "active" by an administrator.
- *
- * Use this to check if this was the reason
- * why a user was not able to login.
- * true == user account is NOT active
- * false == user account is active
- *
- * @return bool true if the user account is *not* active
- * false if the user account *is* active
- *
- * @access public
- */
- function isInactive()
- {
- return $this->_status == LIVEUSER_STATUS_ISINACTIVE;
- }
-
- /**
- * Wrapper method to access properties from the auth and
- * permission containers.
- *
- * @param string Name of the property to be returned.
- * @param string 'auth' or 'perm'
- * @return mixed a scalarvalue, an object or an array.
- *
- * @access public
- */
- function getProperty($what, $container = 'auth')
- {
- $that = null;
- if ($container == 'auth' && is_a($this->_auth, 'LiveUser_Auth_Common')
- && !is_null($this->_auth->getProperty($what))
- ) {
- $that = $this->_auth->getProperty($what);
- } elseif (is_a($this->_perm, 'LiveUser_Perm_Simple')
- && !is_null($this->_perm->getProperty($what))
- ) {
- $that = $this->_perm->getProperty($what);
- }
- return $that;
- }
-
- /**
- * Updates the properties of the containers from the original source.
- *
- * @param bool if the auth container should be updated
- * @param bool if the perm container should be updated
- * @return bool true on success and false on failure
- *
- * @access public
- */
- function updateProperty($auth, $perm = null)
- {
- if (!is_a($this->_auth, 'LiveUser_Auth_Common')) {
- $this->stack->push(LIVEUSER_ERROR, 'error', array(),
- 'Cannot update container if no auth container instance is available');
- return false;
- }
- if ($auth && !$this->_auth->readUserData(null, null, $this->_auth->getProperty('auth_user_id'))) {
- return false;
- }
- if (is_null($perm)) {
- $perm = is_a($this->_perm, 'LiveUser_Perm_Simple');
- }
- if ($perm) {
- if (!is_a($this->_perm, 'LiveUser_Perm_Simple')) {
- $this->stack->push(LIVEUSER_ERROR, 'error', array(),
- 'Cannot update container if no perm container instance is available');
- return false;
- }
- if (!$this->_perm->mapUser($this->_auth->getProperty('auth_user_id'), $this->_auth->containerName)) {
- return false;
- }
- }
- $this->_freeze();
- return true;
- }
-
- /**
- * Get the current status.
- *
- * @return int a LIVEUSER_STATUS_* constant
- *
- * @access public
- * @see LIVEUSER_STATUS_* constants
- */
- function getStatus()
- {
- return $this->_status;
- }
-
- /**
- * Make a string representation of the object.
- *
- * @return string returns a string representation of the class
- *
- * @access private
- */
- function __toString()
- {
- return get_class($this) . ' logged in: ' . ($this->isLoggedIn() ? 'Yes' : 'No');
- }
-
- /**
- * Return a textual status message for a LiveUser status code.
- *
- * @param int|array integer status code,
- null to get the current status code-message map,
- or an array with a new status code-message map
- * @return string error message
- *
- * @access public
- */
- function statusMessage($value = null)
- {
- // make the variable static so that it only has to do the defining on the first call
- static $statusMessages;
-
- if (is_array($value)) {
- $statusMessages = $value;
- return true;
- }
-
- if (!isset($statusMessages)) {
- $statusMessages = array(
- LIVEUSER_STATUS_OK => 'Authentication OK',
- LIVEUSER_STATUS_IDLED => 'Maximum idle time is reached',
- LIVEUSER_STATUS_EXPIRED => 'User session has expired',
- LIVEUSER_STATUS_ISINACTIVE => 'User account is inactive',
- LIVEUSER_STATUS_PERMINITERROR => 'Cannot instantiate permission container',
- LIVEUSER_STATUS_AUTHINITERROR => 'Cannot instantiate the authentication container, this is a configuration problem',
- LIVEUSER_STATUS_AUTHNOTFOUND => 'Cannot retrieve Auth object from session',
- LIVEUSER_STATUS_UNKNOWN => 'An undefined error occurred or init() was not called',
- LIVEUSER_STATUS_LOGGEDOUT => 'User was logged out correctly',
- LIVEUSER_STATUS_AUTHFAILED => 'Authentication failed, handle/password is probably wrong',
- LIVEUSER_STATUS_UNFROZEN => 'Object fetched from the session, the user was already logged in',
- LIVEUSER_STATUS_EMPTY_HANDLE => 'No handle was passed to LiveUser directly or indirectly',
- );
- }
-
- if (is_null($value)) {
- return $statusMessages;
- }
-
- // return the textual error message corresponding to the code
- return array_key_exists($value, $statusMessages)
- ? $statusMessages[$value] : $statusMessages[LIVEUSER_STATUS_UNKNOWN];
- }
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/**
- * $Header: /usr/local/cvsroot/prod/app.gaslightmedia.com/glmPEAR/Log.php,v 1.1 2010/01/27 22:33:04 jamie Exp $
- * $Horde: horde/lib/Log.php,v 1.15 2000/06/29 23:39:45 jon Exp $
- *
- * @version $Revision: 1.1 $
- * @package Log
- */
-
-define('PEAR_LOG_EMERG', 0); /* System is unusable */
-define('PEAR_LOG_ALERT', 1); /* Immediate action required */
-define('PEAR_LOG_CRIT', 2); /* Critical conditions */
-define('PEAR_LOG_ERR', 3); /* Error conditions */
-define('PEAR_LOG_WARNING', 4); /* Warning conditions */
-define('PEAR_LOG_NOTICE', 5); /* Normal but significant */
-define('PEAR_LOG_INFO', 6); /* Informational */
-define('PEAR_LOG_DEBUG', 7); /* Debug-level messages */
-
-define('PEAR_LOG_ALL', 0xffffffff); /* All messages */
-define('PEAR_LOG_NONE', 0x00000000); /* No message */
-
-/* Log types for PHP's native error_log() function. */
-define('PEAR_LOG_TYPE_SYSTEM', 0); /* Use PHP's system logger */
-define('PEAR_LOG_TYPE_MAIL', 1); /* Use PHP's mail() function */
-define('PEAR_LOG_TYPE_DEBUG', 2); /* Use PHP's debugging connection */
-define('PEAR_LOG_TYPE_FILE', 3); /* Append to a file */
-define('PEAR_LOG_TYPE_SAPI', 4); /* Use the SAPI logging handler */
-
-/**
- * The Log:: class implements both an abstraction for various logging
- * mechanisms and the Subject end of a Subject-Observer pattern.
- *
- * @author Chuck Hagenbuch <chuck@horde.org>
- * @author Jon Parise <jon@php.net>
- * @since Horde 1.3
- * @package Log
- */
-class Log
-{
- /**
- * Indicates whether or not the log can been opened / connected.
- *
- * @var boolean
- * @access protected
- */
- var $_opened = false;
-
- /**
- * Instance-specific unique identification number.
- *
- * @var integer
- * @access protected
- */
- var $_id = 0;
-
- /**
- * The label that uniquely identifies this set of log messages.
- *
- * @var string
- * @access protected
- */
- var $_ident = '';
-
- /**
- * The default priority to use when logging an event.
- *
- * @var integer
- * @access protected
- */
- var $_priority = PEAR_LOG_INFO;
-
- /**
- * The bitmask of allowed log levels.
- *
- * @var integer
- * @access protected
- */
- var $_mask = PEAR_LOG_ALL;
-
- /**
- * Holds all Log_observer objects that wish to be notified of new messages.
- *
- * @var array
- * @access protected
- */
- var $_listeners = array();
-
- /**
- * Maps canonical format keys to position arguments for use in building
- * "line format" strings.
- *
- * @var array
- * @access protected
- */
- var $_formatMap = array('%{timestamp}' => '%1$s',
- '%{ident}' => '%2$s',
- '%{priority}' => '%3$s',
- '%{message}' => '%4$s',
- '%{file}' => '%5$s',
- '%{line}' => '%6$s',
- '%{function}' => '%7$s',
- '%{class}' => '%8$s',
- '%\{' => '%%{');
-
- /**
- * Attempts to return a concrete Log instance of type $handler.
- *
- * @param string $handler The type of concrete Log subclass to return.
- * Attempt to dynamically include the code for
- * this subclass. Currently, valid values are
- * 'console', 'syslog', 'sql', 'file', and 'mcal'.
- *
- * @param string $name The name of the actually log file, table, or
- * other specific store to use. Defaults to an
- * empty string, with which the subclass will
- * attempt to do something intelligent.
- *
- * @param string $ident The identity reported to the log system.
- *
- * @param array $conf A hash containing any additional configuration
- * information that a subclass might need.
- *
- * @param int $level Log messages up to and including this level.
- *
- * @return object Log The newly created concrete Log instance, or
- * null on an error.
- * @access public
- * @since Log 1.0
- */
- function &factory($handler, $name = '', $ident = '', $conf = array(),
- $level = PEAR_LOG_DEBUG)
- {
- $handler = strtolower($handler);
- $class = 'Log_' . $handler;
- $classfile = 'Log/' . $handler . '.php';
-
- /*
- * Attempt to include our version of the named class, but don't treat
- * a failure as fatal. The caller may have already included their own
- * version of the named class.
- */
- if (!class_exists($class, false)) {
- include_once $classfile;
- }
-
- /* If the class exists, return a new instance of it. */
- if (class_exists($class, false)) {
- $obj = new $class($name, $ident, $conf, $level);
- return $obj;
- }
-
- $null = null;
- return $null;
- }
-
- /**
- * Attempts to return a reference to a concrete Log instance of type
- * $handler, only creating a new instance if no log instance with the same
- * parameters currently exists.
- *
- * You should use this if there are multiple places you might create a
- * logger, you don't want to create multiple loggers, and you don't want to
- * check for the existance of one each time. The singleton pattern does all
- * the checking work for you.
- *
- * <b>You MUST call this method with the $var = &Log::singleton() syntax.
- * Without the ampersand (&) in front of the method name, you will not get
- * a reference, you will get a copy.</b>
- *
- * @param string $handler The type of concrete Log subclass to return.
- * Attempt to dynamically include the code for
- * this subclass. Currently, valid values are
- * 'console', 'syslog', 'sql', 'file', and 'mcal'.
- *
- * @param string $name The name of the actually log file, table, or
- * other specific store to use. Defaults to an
- * empty string, with which the subclass will
- * attempt to do something intelligent.
- *
- * @param string $ident The identity reported to the log system.
- *
- * @param array $conf A hash containing any additional configuration
- * information that a subclass might need.
- *
- * @param int $level Log messages up to and including this level.
- *
- * @return object Log The newly created concrete Log instance, or
- * null on an error.
- * @access public
- * @since Log 1.0
- */
- function &singleton($handler, $name = '', $ident = '', $conf = array(),
- $level = PEAR_LOG_DEBUG)
- {
- static $instances;
- if (!isset($instances)) $instances = array();
-
- $signature = serialize(array($handler, $name, $ident, $conf, $level));
- if (!isset($instances[$signature])) {
- $instances[$signature] = &Log::factory($handler, $name, $ident,
- $conf, $level);
- }
-
- return $instances[$signature];
- }
-
- /**
- * Abstract implementation of the open() method.
- * @since Log 1.0
- */
- function open()
- {
- return false;
- }
-
- /**
- * Abstract implementation of the close() method.
- * @since Log 1.0
- */
- function close()
- {
- return false;
- }
-
- /**
- * Abstract implementation of the flush() method.
- * @since Log 1.8.2
- */
- function flush()
- {
- return false;
- }
-
- /**
- * Abstract implementation of the log() method.
- * @since Log 1.0
- */
- function log($message, $priority = null)
- {
- return false;
- }
-
- /**
- * A convenience function for logging a emergency event. It will log a
- * message at the PEAR_LOG_EMERG log level.
- *
- * @param mixed $message String or object containing the message
- * to log.
- *
- * @return boolean True if the message was successfully logged.
- *
- * @access public
- * @since Log 1.7.0
- */
- function emerg($message)
- {
- return $this->log($message, PEAR_LOG_EMERG);
- }
-
- /**
- * A convenience function for logging an alert event. It will log a
- * message at the PEAR_LOG_ALERT log level.
- *
- * @param mixed $message String or object containing the message
- * to log.
- *
- * @return boolean True if the message was successfully logged.
- *
- * @access public
- * @since Log 1.7.0
- */
- function alert($message)
- {
- return $this->log($message, PEAR_LOG_ALERT);
- }
-
- /**
- * A convenience function for logging a critical event. It will log a
- * message at the PEAR_LOG_CRIT log level.
- *
- * @param mixed $message String or object containing the message
- * to log.
- *
- * @return boolean True if the message was successfully logged.
- *
- * @access public
- * @since Log 1.7.0
- */
- function crit($message)
- {
- return $this->log($message, PEAR_LOG_CRIT);
- }
-
- /**
- * A convenience function for logging a error event. It will log a
- * message at the PEAR_LOG_ERR log level.
- *
- * @param mixed $message String or object containing the message
- * to log.
- *
- * @return boolean True if the message was successfully logged.
- *
- * @access public
- * @since Log 1.7.0
- */
- function err($message)
- {
- return $this->log($message, PEAR_LOG_ERR);
- }
-
- /**
- * A convenience function for logging a warning event. It will log a
- * message at the PEAR_LOG_WARNING log level.
- *
- * @param mixed $message String or object containing the message
- * to log.
- *
- * @return boolean True if the message was successfully logged.
- *
- * @access public
- * @since Log 1.7.0
- */
- function warning($message)
- {
- return $this->log($message, PEAR_LOG_WARNING);
- }
-
- /**
- * A convenience function for logging a notice event. It will log a
- * message at the PEAR_LOG_NOTICE log level.
- *
- * @param mixed $message String or object containing the message
- * to log.
- *
- * @return boolean True if the message was successfully logged.
- *
- * @access public
- * @since Log 1.7.0
- */
- function notice($message)
- {
- return $this->log($message, PEAR_LOG_NOTICE);
- }
-
- /**
- * A convenience function for logging a information event. It will log a
- * message at the PEAR_LOG_INFO log level.
- *
- * @param mixed $message String or object containing the message
- * to log.
- *
- * @return boolean True if the message was successfully logged.
- *
- * @access public
- * @since Log 1.7.0
- */
- function info($message)
- {
- return $this->log($message, PEAR_LOG_INFO);
- }
-
- /**
- * A convenience function for logging a debug event. It will log a
- * message at the PEAR_LOG_DEBUG log level.
- *
- * @param mixed $message String or object containing the message
- * to log.
- *
- * @return boolean True if the message was successfully logged.
- *
- * @access public
- * @since Log 1.7.0
- */
- function debug($message)
- {
- return $this->log($message, PEAR_LOG_DEBUG);
- }
-
- /**
- * Returns the string representation of the message data.
- *
- * If $message is an object, _extractMessage() will attempt to extract
- * the message text using a known method (such as a PEAR_Error object's
- * getMessage() method). If a known method, cannot be found, the
- * serialized representation of the object will be returned.
- *
- * If the message data is already a string, it will be returned unchanged.
- *
- * @param mixed $message The original message data. This may be a
- * string or any object.
- *
- * @return string The string representation of the message.
- *
- * @access protected
- */
- function _extractMessage($message)
- {
- /*
- * If we've been given an object, attempt to extract the message using
- * a known method. If we can't find such a method, default to the
- * "human-readable" version of the object.
- *
- * We also use the human-readable format for arrays.
- */
- if (is_object($message)) {
- if (method_exists($message, 'getmessage')) {
- $message = $message->getMessage();
- } else if (method_exists($message, 'tostring')) {
- $message = $message->toString();
- } else if (method_exists($message, '__tostring')) {
- $message = (string)$message;
- } else {
- $message = var_export($message, true);
- }
- } else if (is_array($message)) {
- if (isset($message['message'])) {
- if (is_scalar($message['message'])) {
- $message = $message['message'];
- } else {
- $message = var_export($message['message'], true);
- }
- } else {
- $message = var_export($message, true);
- }
- } else if (is_bool($message) || $message === NULL) {
- $message = var_export($message, true);
- }
-
- /* Otherwise, we assume the message is a string. */
- return $message;
- }
-
- /**
- * Using debug_backtrace(), returns the file, line, and enclosing function
- * name of the source code context from which log() was invoked.
- *
- * @param int $depth The initial number of frames we should step
- * back into the trace.
- *
- * @return array Array containing four strings: the filename, the line,
- * the function name, and the class name from which log()
- * was called.
- *
- * @access private
- * @since Log 1.9.4
- */
- function _getBacktraceVars($depth)
- {
- /* Start by generating a backtrace from the current call (here). */
- $bt = debug_backtrace();
-
- /*
- * If we were ultimately invoked by the composite handler, we need to
- * increase our depth one additional level to compensate.
- */
- $class = isset($bt[$depth+1]['class']) ? $bt[$depth+1]['class'] : null;
- if ($class !== null && strcasecmp($class, 'Log_composite') == 0) {
- $depth++;
- $class = isset($bt[$depth + 1]) ? $bt[$depth + 1]['class'] : null;
- }
-
- /*
- * We're interested in the frame which invoked the log() function, so
- * we need to walk back some number of frames into the backtrace. The
- * $depth parameter tells us where to start looking. We go one step
- * further back to find the name of the encapsulating function from
- * which log() was called.
- */
- $file = isset($bt[$depth]) ? $bt[$depth]['file'] : null;
- $line = isset($bt[$depth]) ? $bt[$depth]['line'] : 0;
- $func = isset($bt[$depth + 1]) ? $bt[$depth + 1]['function'] : null;
-
- /*
- * However, if log() was called from one of our "shortcut" functions,
- * we're going to need to go back an additional step.
- */
- if (in_array($func, array('emerg', 'alert', 'crit', 'err', 'warning',
- 'notice', 'info', 'debug'))) {
- $file = isset($bt[$depth + 1]) ? $bt[$depth + 1]['file'] : null;
- $line = isset($bt[$depth + 1]) ? $bt[$depth + 1]['line'] : 0;
- $func = isset($bt[$depth + 2]) ? $bt[$depth + 2]['function'] : null;
- $class = isset($bt[$depth + 2]) ? $bt[$depth + 2]['class'] : null;
- }
-
- /*
- * If we couldn't extract a function name (perhaps because we were
- * executed from the "main" context), provide a default value.
- */
- if (is_null($func)) {
- $func = '(none)';
- }
-
- /* Return a 4-tuple containing (file, line, function, class). */
- return array($file, $line, $func, $class);
- }
-
- /**
- * Produces a formatted log line based on a format string and a set of
- * variables representing the current log record and state.
- *
- * @return string Formatted log string.
- *
- * @access protected
- * @since Log 1.9.4
- */
- function _format($format, $timestamp, $priority, $message)
- {
- /*
- * If the format string references any of the backtrace-driven
- * variables (%5 %6,%7,%8), generate the backtrace and fetch them.
- */
- if (preg_match('/%[5678]/', $format)) {
- list($file, $line, $func, $class) = $this->_getBacktraceVars(2);
- }
-
- /*
- * Build the formatted string. We use the sprintf() function's
- * "argument swapping" capability to dynamically select and position
- * the variables which will ultimately appear in the log string.
- */
- return sprintf($format,
- $timestamp,
- $this->_ident,
- $this->priorityToString($priority),
- $message,
- isset($file) ? $file : '',
- isset($line) ? $line : '',
- isset($func) ? $func : '',
- isset($class) ? $class : '');
- }
-
- /**
- * Returns the string representation of a PEAR_LOG_* integer constant.
- *
- * @param int $priority A PEAR_LOG_* integer constant.
- *
- * @return string The string representation of $level.
- *
- * @access public
- * @since Log 1.0
- */
- function priorityToString($priority)
- {
- $levels = array(
- PEAR_LOG_EMERG => 'emergency',
- PEAR_LOG_ALERT => 'alert',
- PEAR_LOG_CRIT => 'critical',
- PEAR_LOG_ERR => 'error',
- PEAR_LOG_WARNING => 'warning',
- PEAR_LOG_NOTICE => 'notice',
- PEAR_LOG_INFO => 'info',
- PEAR_LOG_DEBUG => 'debug'
- );
-
- return $levels[$priority];
- }
-
- /**
- * Returns the the PEAR_LOG_* integer constant for the given string
- * representation of a priority name. This function performs a
- * case-insensitive search.
- *
- * @param string $name String containing a priority name.
- *
- * @return string The PEAR_LOG_* integer contstant corresponding
- * the the specified priority name.
- *
- * @access public
- * @since Log 1.9.0
- */
- function stringToPriority($name)
- {
- $levels = array(
- 'emergency' => PEAR_LOG_EMERG,
- 'alert' => PEAR_LOG_ALERT,
- 'critical' => PEAR_LOG_CRIT,
- 'error' => PEAR_LOG_ERR,
- 'warning' => PEAR_LOG_WARNING,
- 'notice' => PEAR_LOG_NOTICE,
- 'info' => PEAR_LOG_INFO,
- 'debug' => PEAR_LOG_DEBUG
- );
-
- return $levels[strtolower($name)];
- }
-
- /**
- * Calculate the log mask for the given priority.
- *
- * This method may be called statically.
- *
- * @param integer $priority The priority whose mask will be calculated.
- *
- * @return integer The calculated log mask.
- *
- * @access public
- * @since Log 1.7.0
- */
- function MASK($priority)
- {
- return (1 << $priority);
- }
-
- /**
- * Calculate the log mask for all priorities up to the given priority.
- *
- * This method may be called statically.
- *
- * @param integer $priority The maximum priority covered by this mask.
- *
- * @return integer The resulting log mask.
- *
- * @access public
- * @since Log 1.7.0
- *
- * @deprecated deprecated since Log 1.9.4; use Log::MAX() instead
- */
- function UPTO($priority)
- {
- return Log::MAX($priority);
- }
-
- /**
- * Calculate the log mask for all priorities greater than or equal to the
- * given priority. In other words, $priority will be the lowest priority
- * matched by the resulting mask.
- *
- * This method may be called statically.
- *
- * @param integer $priority The minimum priority covered by this mask.
- *
- * @return integer The resulting log mask.
- *
- * @access public
- * @since Log 1.9.4
- */
- function MIN($priority)
- {
- return PEAR_LOG_ALL ^ ((1 << $priority) - 1);
- }
-
- /**
- * Calculate the log mask for all priorities less than or equal to the
- * given priority. In other words, $priority will be the highests priority
- * matched by the resulting mask.
- *
- * This method may be called statically.
- *
- * @param integer $priority The maximum priority covered by this mask.
- *
- * @return integer The resulting log mask.
- *
- * @access public
- * @since Log 1.9.4
- */
- function MAX($priority)
- {
- return ((1 << ($priority + 1)) - 1);
- }
-
- /**
- * Set and return the level mask for the current Log instance.
- *
- * @param integer $mask A bitwise mask of log levels.
- *
- * @return integer The current level mask.
- *
- * @access public
- * @since Log 1.7.0
- */
- function setMask($mask)
- {
- $this->_mask = $mask;
-
- return $this->_mask;
- }
-
- /**
- * Returns the current level mask.
- *
- * @return interger The current level mask.
- *
- * @access public
- * @since Log 1.7.0
- */
- function getMask()
- {
- return $this->_mask;
- }
-
- /**
- * Check if the given priority is included in the current level mask.
- *
- * @param integer $priority The priority to check.
- *
- * @return boolean True if the given priority is included in the current
- * log mask.
- *
- * @access protected
- * @since Log 1.7.0
- */
- function _isMasked($priority)
- {
- return (Log::MASK($priority) & $this->_mask);
- }
-
- /**
- * Returns the current default priority.
- *
- * @return integer The current default priority.
- *
- * @access public
- * @since Log 1.8.4
- */
- function getPriority()
- {
- return $this->_priority;
- }
-
- /**
- * Sets the default priority to the specified value.
- *
- * @param integer $priority The new default priority.
- *
- * @access public
- * @since Log 1.8.4
- */
- function setPriority($priority)
- {
- $this->_priority = $priority;
- }
-
- /**
- * Adds a Log_observer instance to the list of observers that are listening
- * for messages emitted by this Log instance.
- *
- * @param object $observer The Log_observer instance to attach as a
- * listener.
- *
- * @param boolean True if the observer is successfully attached.
- *
- * @access public
- * @since Log 1.0
- */
- function attach(&$observer)
- {
- if (!is_a($observer, 'Log_observer')) {
- return false;
- }
-
- $this->_listeners[$observer->_id] = &$observer;
-
- return true;
- }
-
- /**
- * Removes a Log_observer instance from the list of observers.
- *
- * @param object $observer The Log_observer instance to detach from
- * the list of listeners.
- *
- * @param boolean True if the observer is successfully detached.
- *
- * @access public
- * @since Log 1.0
- */
- function detach($observer)
- {
- if (!is_a($observer, 'Log_observer') ||
- !isset($this->_listeners[$observer->_id])) {
- return false;
- }
-
- unset($this->_listeners[$observer->_id]);
-
- return true;
- }
-
- /**
- * Informs each registered observer instance that a new message has been
- * logged.
- *
- * @param array $event A hash describing the log event.
- *
- * @access protected
- */
- function _announce($event)
- {
- foreach ($this->_listeners as $id => $listener) {
- if ($event['priority'] <= $this->_listeners[$id]->_priority) {
- $this->_listeners[$id]->notify($event);
- }
- }
- }
-
- /**
- * Indicates whether this is a composite class.
- *
- * @return boolean True if this is a composite class.
- *
- * @access public
- * @since Log 1.0
- */
- function isComposite()
- {
- return false;
- }
-
- /**
- * Sets this Log instance's identification string.
- *
- * @param string $ident The new identification string.
- *
- * @access public
- * @since Log 1.6.3
- */
- function setIdent($ident)
- {
- $this->_ident = $ident;
- }
-
- /**
- * Returns the current identification string.
- *
- * @return string The current Log instance's identification string.
- *
- * @access public
- * @since Log 1.6.3
- */
- function getIdent()
- {
- return $this->_ident;
- }
-}
+++ /dev/null
-<?php
-// vim: set et ts=4 sw=4 fdm=marker:
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2007 Manuel Lemos, Tomas V.V.Cox, |
-// | Stig. S. Bakken, Lukas Smith |
-// | All rights reserved. |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
-// | API as well as database abstraction for PHP applications. |
-// | This LICENSE is in the BSD license style. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | |
-// | Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution. |
-// | |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
-// | POSSIBILITY OF SUCH DAMAGE. |
-// +----------------------------------------------------------------------+
-// | Author: Lukas Smith <smith@pooteeweet.org> |
-// +----------------------------------------------------------------------+
-//
-// $Id: MDB2.php,v 1.1.1.1 2008/04/28 15:20:46 jamie Exp $
-//
-
-/**
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-
-require_once 'PEAR.php';
-
-// {{{ Error constants
-
-/**
- * The method mapErrorCode in each MDB2_dbtype implementation maps
- * native error codes to one of these.
- *
- * If you add an error code here, make sure you also add a textual
- * version of it in MDB2::errorMessage().
- */
-
-define('MDB2_OK', true);
-define('MDB2_ERROR', -1);
-define('MDB2_ERROR_SYNTAX', -2);
-define('MDB2_ERROR_CONSTRAINT', -3);
-define('MDB2_ERROR_NOT_FOUND', -4);
-define('MDB2_ERROR_ALREADY_EXISTS', -5);
-define('MDB2_ERROR_UNSUPPORTED', -6);
-define('MDB2_ERROR_MISMATCH', -7);
-define('MDB2_ERROR_INVALID', -8);
-define('MDB2_ERROR_NOT_CAPABLE', -9);
-define('MDB2_ERROR_TRUNCATED', -10);
-define('MDB2_ERROR_INVALID_NUMBER', -11);
-define('MDB2_ERROR_INVALID_DATE', -12);
-define('MDB2_ERROR_DIVZERO', -13);
-define('MDB2_ERROR_NODBSELECTED', -14);
-define('MDB2_ERROR_CANNOT_CREATE', -15);
-define('MDB2_ERROR_CANNOT_DELETE', -16);
-define('MDB2_ERROR_CANNOT_DROP', -17);
-define('MDB2_ERROR_NOSUCHTABLE', -18);
-define('MDB2_ERROR_NOSUCHFIELD', -19);
-define('MDB2_ERROR_NEED_MORE_DATA', -20);
-define('MDB2_ERROR_NOT_LOCKED', -21);
-define('MDB2_ERROR_VALUE_COUNT_ON_ROW', -22);
-define('MDB2_ERROR_INVALID_DSN', -23);
-define('MDB2_ERROR_CONNECT_FAILED', -24);
-define('MDB2_ERROR_EXTENSION_NOT_FOUND',-25);
-define('MDB2_ERROR_NOSUCHDB', -26);
-define('MDB2_ERROR_ACCESS_VIOLATION', -27);
-define('MDB2_ERROR_CANNOT_REPLACE', -28);
-define('MDB2_ERROR_CONSTRAINT_NOT_NULL',-29);
-define('MDB2_ERROR_DEADLOCK', -30);
-define('MDB2_ERROR_CANNOT_ALTER', -31);
-define('MDB2_ERROR_MANAGER', -32);
-define('MDB2_ERROR_MANAGER_PARSE', -33);
-define('MDB2_ERROR_LOADMODULE', -34);
-define('MDB2_ERROR_INSUFFICIENT_DATA', -35);
-// }}}
-// {{{ Verbose constants
-/**
- * These are just helper constants to more verbosely express parameters to prepare()
- */
-
-define('MDB2_PREPARE_MANIP', false);
-define('MDB2_PREPARE_RESULT', null);
-
-// }}}
-// {{{ Fetchmode constants
-
-/**
- * This is a special constant that tells MDB2 the user hasn't specified
- * any particular get mode, so the default should be used.
- */
-define('MDB2_FETCHMODE_DEFAULT', 0);
-
-/**
- * Column data indexed by numbers, ordered from 0 and up
- */
-define('MDB2_FETCHMODE_ORDERED', 1);
-
-/**
- * Column data indexed by column names
- */
-define('MDB2_FETCHMODE_ASSOC', 2);
-
-/**
- * Column data as object properties
- */
-define('MDB2_FETCHMODE_OBJECT', 3);
-
-/**
- * For multi-dimensional results: normally the first level of arrays
- * is the row number, and the second level indexed by column number or name.
- * MDB2_FETCHMODE_FLIPPED switches this order, so the first level of arrays
- * is the column name, and the second level the row number.
- */
-define('MDB2_FETCHMODE_FLIPPED', 4);
-
-// }}}
-// {{{ Portability mode constants
-
-/**
- * Portability: turn off all portability features.
- * @see MDB2_Driver_Common::setOption()
- */
-define('MDB2_PORTABILITY_NONE', 0);
-
-/**
- * Portability: convert names of tables and fields to case defined in the
- * "field_case" option when using the query*(), fetch*() and tableInfo() methods.
- * @see MDB2_Driver_Common::setOption()
- */
-define('MDB2_PORTABILITY_FIX_CASE', 1);
-
-/**
- * Portability: right trim the data output by query*() and fetch*().
- * @see MDB2_Driver_Common::setOption()
- */
-define('MDB2_PORTABILITY_RTRIM', 2);
-
-/**
- * Portability: force reporting the number of rows deleted.
- * @see MDB2_Driver_Common::setOption()
- */
-define('MDB2_PORTABILITY_DELETE_COUNT', 4);
-
-/**
- * Portability: not needed in MDB2 (just left here for compatibility to DB)
- * @see MDB2_Driver_Common::setOption()
- */
-define('MDB2_PORTABILITY_NUMROWS', 8);
-
-/**
- * Portability: makes certain error messages in certain drivers compatible
- * with those from other DBMS's.
- *
- * + mysql, mysqli: change unique/primary key constraints
- * MDB2_ERROR_ALREADY_EXISTS -> MDB2_ERROR_CONSTRAINT
- *
- * + odbc(access): MS's ODBC driver reports 'no such field' as code
- * 07001, which means 'too few parameters.' When this option is on
- * that code gets mapped to MDB2_ERROR_NOSUCHFIELD.
- *
- * @see MDB2_Driver_Common::setOption()
- */
-define('MDB2_PORTABILITY_ERRORS', 16);
-
-/**
- * Portability: convert empty values to null strings in data output by
- * query*() and fetch*().
- * @see MDB2_Driver_Common::setOption()
- */
-define('MDB2_PORTABILITY_EMPTY_TO_NULL', 32);
-
-/**
- * Portability: removes database/table qualifiers from associative indexes
- * @see MDB2_Driver_Common::setOption()
- */
-define('MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES', 64);
-
-/**
- * Portability: turn on all portability features.
- * @see MDB2_Driver_Common::setOption()
- */
-define('MDB2_PORTABILITY_ALL', 127);
-
-// }}}
-// {{{ Globals for class instance tracking
-
-/**
- * These are global variables that are used to track the various class instances
- */
-
-$GLOBALS['_MDB2_databases'] = array();
-$GLOBALS['_MDB2_dsninfo_default'] = array(
- 'phptype' => false,
- 'dbsyntax' => false,
- 'username' => false,
- 'password' => false,
- 'protocol' => false,
- 'hostspec' => false,
- 'port' => false,
- 'socket' => false,
- 'database' => false,
- 'mode' => false,
-);
-
-// }}}
-// {{{ class MDB2
-
-/**
- * The main 'MDB2' class is simply a container class with some static
- * methods for creating DB objects as well as some utility functions
- * common to all parts of DB.
- *
- * The object model of MDB2 is as follows (indentation means inheritance):
- *
- * MDB2 The main MDB2 class. This is simply a utility class
- * with some 'static' methods for creating MDB2 objects as
- * well as common utility functions for other MDB2 classes.
- *
- * MDB2_Driver_Common The base for each MDB2 implementation. Provides default
- * | implementations (in OO lingo virtual methods) for
- * | the actual DB implementations as well as a bunch of
- * | query utility functions.
- * |
- * +-MDB2_Driver_mysql The MDB2 implementation for MySQL. Inherits MDB2_Driver_Common.
- * When calling MDB2::factory or MDB2::connect for MySQL
- * connections, the object returned is an instance of this
- * class.
- * +-MDB2_Driver_pgsql The MDB2 implementation for PostGreSQL. Inherits MDB2_Driver_Common.
- * When calling MDB2::factory or MDB2::connect for PostGreSQL
- * connections, the object returned is an instance of this
- * class.
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2
-{
- // {{{ function setOptions(&$db, $options)
-
- /**
- * set option array in an exiting database object
- *
- * @param MDB2_Driver_Common MDB2 object
- * @param array An associative array of option names and their values.
- *
- * @return mixed MDB2_OK or a PEAR Error object
- *
- * @access public
- */
- function setOptions(&$db, $options)
- {
- if (is_array($options)) {
- foreach ($options as $option => $value) {
- $test = $db->setOption($option, $value);
- if (PEAR::isError($test)) {
- return $test;
- }
- }
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function classExists($classname)
-
- /**
- * Checks if a class exists without triggering __autoload
- *
- * @param string classname
- *
- * @return bool true success and false on error
- * @static
- * @access public
- */
- function classExists($classname)
- {
- if (version_compare(phpversion(), "5.0", ">=")) {
- return class_exists($classname, false);
- }
- return class_exists($classname);
- }
-
- // }}}
- // {{{ function loadClass($class_name, $debug)
-
- /**
- * Loads a PEAR class.
- *
- * @param string classname to load
- * @param bool if errors should be suppressed
- *
- * @return mixed true success or PEAR_Error on failure
- *
- * @access public
- */
- function loadClass($class_name, $debug)
- {
- if (!MDB2::classExists($class_name)) {
- $file_name = str_replace('_', DIRECTORY_SEPARATOR, $class_name).'.php';
- if ($debug) {
- $include = include_once($file_name);
- } else {
- $include = @include_once($file_name);
- }
- if (!$include) {
- if (!MDB2::fileExists($file_name)) {
- $msg = "unable to find package '$class_name' file '$file_name'";
- } else {
- $msg = "unable to load class '$class_name' from file '$file_name'";
- }
- $err =& MDB2::raiseError(MDB2_ERROR_NOT_FOUND, null, null, $msg);
- return $err;
- }
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function &factory($dsn, $options = false)
-
- /**
- * Create a new MDB2 object for the specified database type
- *
- * IMPORTANT: In order for MDB2 to work properly it is necessary that
- * you make sure that you work with a reference of the original
- * object instead of a copy (this is a PHP4 quirk).
- *
- * For example:
- * $db =& MDB2::factory($dsn);
- * ^^
- * And not:
- * $db = MDB2::factory($dsn);
- *
- * @param mixed 'data source name', see the MDB2::parseDSN
- * method for a description of the dsn format.
- * Can also be specified as an array of the
- * format returned by MDB2::parseDSN.
- * @param array An associative array of option names and
- * their values.
- *
- * @return mixed a newly created MDB2 object, or false on error
- *
- * @access public
- */
- function &factory($dsn, $options = false)
- {
- $dsninfo = MDB2::parseDSN($dsn);
- if (empty($dsninfo['phptype'])) {
- $err =& MDB2::raiseError(MDB2_ERROR_NOT_FOUND,
- null, null, 'no RDBMS driver specified');
- return $err;
- }
- $class_name = 'MDB2_Driver_'.$dsninfo['phptype'];
-
- $debug = (!empty($options['debug']));
- $err = MDB2::loadClass($class_name, $debug);
- if (PEAR::isError($err)) {
- return $err;
- }
-
- $db =& new $class_name();
- $db->setDSN($dsninfo);
- $err = MDB2::setOptions($db, $options);
- if (PEAR::isError($err)) {
- return $err;
- }
-
- return $db;
- }
-
- // }}}
- // {{{ function &connect($dsn, $options = false)
-
- /**
- * Create a new MDB2 connection object and connect to the specified
- * database
- *
- * IMPORTANT: In order for MDB2 to work properly it is necessary that
- * you make sure that you work with a reference of the original
- * object instead of a copy (this is a PHP4 quirk).
- *
- * For example:
- * $db =& MDB2::connect($dsn);
- * ^^
- * And not:
- * $db = MDB2::connect($dsn);
- * ^^
- *
- * @param mixed 'data source name', see the MDB2::parseDSN
- * method for a description of the dsn format.
- * Can also be specified as an array of the
- * format returned by MDB2::parseDSN.
- * @param array An associative array of option names and
- * their values.
- *
- * @return mixed a newly created MDB2 connection object, or a MDB2
- * error object on error
- *
- * @access public
- * @see MDB2::parseDSN
- */
- function &connect($dsn, $options = false)
- {
- $db =& MDB2::factory($dsn, $options);
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $err = $db->connect();
- if (PEAR::isError($err)) {
- $dsn = $db->getDSN('string', 'xxx');
- $db->disconnect();
- $err->addUserInfo($dsn);
- return $err;
- }
-
- return $db;
- }
-
- // }}}
- // {{{ function &singleton($dsn = null, $options = false)
-
- /**
- * Returns a MDB2 connection with the requested DSN.
- * A new MDB2 connection object is only created if no object with the
- * requested DSN exists yet.
- *
- * IMPORTANT: In order for MDB2 to work properly it is necessary that
- * you make sure that you work with a reference of the original
- * object instead of a copy (this is a PHP4 quirk).
- *
- * For example:
- * $db =& MDB2::singleton($dsn);
- * ^^
- * And not:
- * $db = MDB2::singleton($dsn);
- * ^^
- *
- * @param mixed 'data source name', see the MDB2::parseDSN
- * method for a description of the dsn format.
- * Can also be specified as an array of the
- * format returned by MDB2::parseDSN.
- * @param array An associative array of option names and
- * their values.
- *
- * @return mixed a newly created MDB2 connection object, or a MDB2
- * error object on error
- *
- * @access public
- * @see MDB2::parseDSN
- */
- function &singleton($dsn = null, $options = false)
- {
- if ($dsn) {
- $dsninfo = MDB2::parseDSN($dsn);
- $dsninfo = array_merge($GLOBALS['_MDB2_dsninfo_default'], $dsninfo);
- $keys = array_keys($GLOBALS['_MDB2_databases']);
- for ($i=0, $j=count($keys); $i<$j; ++$i) {
- if (isset($GLOBALS['_MDB2_databases'][$keys[$i]])) {
- $tmp_dsn = $GLOBALS['_MDB2_databases'][$keys[$i]]->getDSN('array');
- if (count(array_diff_assoc($tmp_dsn, $dsninfo)) == 0) {
- MDB2::setOptions($GLOBALS['_MDB2_databases'][$keys[$i]], $options);
- return $GLOBALS['_MDB2_databases'][$keys[$i]];
- }
- }
- }
- } elseif (is_array($GLOBALS['_MDB2_databases']) && reset($GLOBALS['_MDB2_databases'])) {
- $db =& $GLOBALS['_MDB2_databases'][key($GLOBALS['_MDB2_databases'])];
- return $db;
- }
- $db =& MDB2::factory($dsn, $options);
- return $db;
- }
-
- // }}}
- // {{{ function areEquals()
-
- /**
- * It looks like there's a memory leak in array_diff() in PHP 5.1.x,
- * so use this method instead.
- * @see http://pear.php.net/bugs/bug.php?id=11790
- *
- * @param array $arr1
- * @param array $arr2
- * @return boolean
- */
- function areEquals($arr1, $arr2)
- {
- if (count($arr1) != count($arr2)) {
- return false;
- }
- foreach (array_keys($arr1) as $k) {
- if (!array_key_exists($k, $arr2) || $arr1[$k] != $arr2[$k]) {
- return false;
- }
- }
- return true;
- }
-
- // }}}
- // {{{ function loadFile($file)
-
- /**
- * load a file (like 'Date')
- *
- * @param string name of the file in the MDB2 directory (without '.php')
- *
- * @return string name of the file that was included
- *
- * @access public
- */
- function loadFile($file)
- {
- $file_name = 'MDB2'.DIRECTORY_SEPARATOR.$file.'.php';
- if (!MDB2::fileExists($file_name)) {
- return MDB2::raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'unable to find: '.$file_name);
- }
- if (!include_once($file_name)) {
- return MDB2::raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'unable to load driver class: '.$file_name);
- }
- return $file_name;
- }
-
- // }}}
- // {{{ function apiVersion()
-
- /**
- * Return the MDB2 API version
- *
- * @return string the MDB2 API version number
- *
- * @access public
- */
- function apiVersion()
- {
- return '2.5.0a2';
- }
-
- // }}}
- // {{{ function &raiseError($code = null, $mode = null, $options = null, $userinfo = null)
-
- /**
- * This method is used to communicate an error and invoke error
- * callbacks etc. Basically a wrapper for PEAR::raiseError
- * without the message string.
- *
- * @param mixed int error code
- *
- * @param int error mode, see PEAR_Error docs
- *
- * @param mixed If error mode is PEAR_ERROR_TRIGGER, this is the
- * error level (E_USER_NOTICE etc). If error mode is
- * PEAR_ERROR_CALLBACK, this is the callback function,
- * either as a function name, or as an array of an
- * object and method name. For other error modes this
- * parameter is ignored.
- *
- * @param string Extra debug information. Defaults to the last
- * query and native error code.
- *
- * @return PEAR_Error instance of a PEAR Error object
- *
- * @access private
- * @see PEAR_Error
- */
- function &raiseError($code = null,
- $mode = null,
- $options = null,
- $userinfo = null,
- $dummy1 = null,
- $dummy2 = null,
- $dummy3 = false)
- {
- $err =& PEAR::raiseError(null, $code, $mode, $options, $userinfo, 'MDB2_Error', true);
- return $err;
- }
-
- // }}}
- // {{{ function isError($data, $code = null)
-
- /**
- * Tell whether a value is a MDB2 error.
- *
- * @param mixed the value to test
- * @param int if is an error object, return true
- * only if $code is a string and
- * $db->getMessage() == $code or
- * $code is an integer and $db->getCode() == $code
- *
- * @return bool true if parameter is an error
- *
- * @access public
- */
- function isError($data, $code = null)
- {
- if (is_a($data, 'MDB2_Error')) {
- if (is_null($code)) {
- return true;
- } elseif (is_string($code)) {
- return $data->getMessage() === $code;
- } else {
- $code = (array)$code;
- return in_array($data->getCode(), $code);
- }
- }
- return false;
- }
-
- // }}}
- // {{{ function isConnection($value)
-
- /**
- * Tell whether a value is a MDB2 connection
- *
- * @param mixed value to test
- *
- * @return bool whether $value is a MDB2 connection
- *
- * @access public
- */
- function isConnection($value)
- {
- return is_a($value, 'MDB2_Driver_Common');
- }
-
- // }}}
- // {{{ function isResult($value)
-
- /**
- * Tell whether a value is a MDB2 result
- *
- * @param mixed value to test
- *
- * @return bool whether $value is a MDB2 result
- *
- * @access public
- */
- function isResult($value)
- {
- return is_a($value, 'MDB2_Result');
- }
-
- // }}}
- // {{{ function isResultCommon($value)
-
- /**
- * Tell whether a value is a MDB2 result implementing the common interface
- *
- * @param mixed value to test
- *
- * @return bool whether $value is a MDB2 result implementing the common interface
- *
- * @access public
- */
- function isResultCommon($value)
- {
- return is_a($value, 'MDB2_Result_Common');
- }
-
- // }}}
- // {{{ function isStatement($value)
-
- /**
- * Tell whether a value is a MDB2 statement interface
- *
- * @param mixed value to test
- *
- * @return bool whether $value is a MDB2 statement interface
- *
- * @access public
- */
- function isStatement($value)
- {
- return is_a($value, 'MDB2_Statement_Common');
- }
-
- // }}}
- // {{{ function errorMessage($value = null)
-
- /**
- * Return a textual error message for a MDB2 error code
- *
- * @param int|array integer error code,
- null to get the current error code-message map,
- or an array with a new error code-message map
- *
- * @return string error message, or false if the error code was
- * not recognized
- *
- * @access public
- */
- function errorMessage($value = null)
- {
- static $errorMessages;
-
- if (is_array($value)) {
- $errorMessages = $value;
- return MDB2_OK;
- }
-
- if (!isset($errorMessages)) {
- $errorMessages = array(
- MDB2_OK => 'no error',
- MDB2_ERROR => 'unknown error',
- MDB2_ERROR_ALREADY_EXISTS => 'already exists',
- MDB2_ERROR_CANNOT_CREATE => 'can not create',
- MDB2_ERROR_CANNOT_ALTER => 'can not alter',
- MDB2_ERROR_CANNOT_REPLACE => 'can not replace',
- MDB2_ERROR_CANNOT_DELETE => 'can not delete',
- MDB2_ERROR_CANNOT_DROP => 'can not drop',
- MDB2_ERROR_CONSTRAINT => 'constraint violation',
- MDB2_ERROR_CONSTRAINT_NOT_NULL=> 'null value violates not-null constraint',
- MDB2_ERROR_DIVZERO => 'division by zero',
- MDB2_ERROR_INVALID => 'invalid',
- MDB2_ERROR_INVALID_DATE => 'invalid date or time',
- MDB2_ERROR_INVALID_NUMBER => 'invalid number',
- MDB2_ERROR_MISMATCH => 'mismatch',
- MDB2_ERROR_NODBSELECTED => 'no database selected',
- MDB2_ERROR_NOSUCHFIELD => 'no such field',
- MDB2_ERROR_NOSUCHTABLE => 'no such table',
- MDB2_ERROR_NOT_CAPABLE => 'MDB2 backend not capable',
- MDB2_ERROR_NOT_FOUND => 'not found',
- MDB2_ERROR_NOT_LOCKED => 'not locked',
- MDB2_ERROR_SYNTAX => 'syntax error',
- MDB2_ERROR_UNSUPPORTED => 'not supported',
- MDB2_ERROR_VALUE_COUNT_ON_ROW => 'value count on row',
- MDB2_ERROR_INVALID_DSN => 'invalid DSN',
- MDB2_ERROR_CONNECT_FAILED => 'connect failed',
- MDB2_ERROR_NEED_MORE_DATA => 'insufficient data supplied',
- MDB2_ERROR_EXTENSION_NOT_FOUND=> 'extension not found',
- MDB2_ERROR_NOSUCHDB => 'no such database',
- MDB2_ERROR_ACCESS_VIOLATION => 'insufficient permissions',
- MDB2_ERROR_LOADMODULE => 'error while including on demand module',
- MDB2_ERROR_TRUNCATED => 'truncated',
- MDB2_ERROR_DEADLOCK => 'deadlock detected',
- );
- }
-
- if (is_null($value)) {
- return $errorMessages;
- }
-
- if (PEAR::isError($value)) {
- $value = $value->getCode();
- }
-
- return isset($errorMessages[$value]) ?
- $errorMessages[$value] : $errorMessages[MDB2_ERROR];
- }
-
- // }}}
- // {{{ function parseDSN($dsn)
-
- /**
- * Parse a data source name.
- *
- * Additional keys can be added by appending a URI query string to the
- * end of the DSN.
- *
- * The format of the supplied DSN is in its fullest form:
- * <code>
- * phptype(dbsyntax)://username:password@protocol+hostspec/database?option=8&another=true
- * </code>
- *
- * Most variations are allowed:
- * <code>
- * phptype://username:password@protocol+hostspec:110//usr/db_file.db?mode=0644
- * phptype://username:password@hostspec/database_name
- * phptype://username:password@hostspec
- * phptype://username@hostspec
- * phptype://hostspec/database
- * phptype://hostspec
- * phptype(dbsyntax)
- * phptype
- * </code>
- *
- * @param string Data Source Name to be parsed
- *
- * @return array an associative array with the following keys:
- * + phptype: Database backend used in PHP (mysql, odbc etc.)
- * + dbsyntax: Database used with regards to SQL syntax etc.
- * + protocol: Communication protocol to use (tcp, unix etc.)
- * + hostspec: Host specification (hostname[:port])
- * + database: Database to use on the DBMS server
- * + username: User name for login
- * + password: Password for login
- *
- * @access public
- * @author Tomas V.V.Cox <cox@idecnet.com>
- */
- function parseDSN($dsn)
- {
- $parsed = $GLOBALS['_MDB2_dsninfo_default'];
-
- if (is_array($dsn)) {
- $dsn = array_merge($parsed, $dsn);
- if (!$dsn['dbsyntax']) {
- $dsn['dbsyntax'] = $dsn['phptype'];
- }
- return $dsn;
- }
-
- // Find phptype and dbsyntax
- if (($pos = strpos($dsn, '://')) !== false) {
- $str = substr($dsn, 0, $pos);
- $dsn = substr($dsn, $pos + 3);
- } else {
- $str = $dsn;
- $dsn = null;
- }
-
- // Get phptype and dbsyntax
- // $str => phptype(dbsyntax)
- if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
- $parsed['phptype'] = $arr[1];
- $parsed['dbsyntax'] = !$arr[2] ? $arr[1] : $arr[2];
- } else {
- $parsed['phptype'] = $str;
- $parsed['dbsyntax'] = $str;
- }
-
- if (!count($dsn)) {
- return $parsed;
- }
-
- // Get (if found): username and password
- // $dsn => username:password@protocol+hostspec/database
- if (($at = strrpos($dsn,'@')) !== false) {
- $str = substr($dsn, 0, $at);
- $dsn = substr($dsn, $at + 1);
- if (($pos = strpos($str, ':')) !== false) {
- $parsed['username'] = rawurldecode(substr($str, 0, $pos));
- $parsed['password'] = rawurldecode(substr($str, $pos + 1));
- } else {
- $parsed['username'] = rawurldecode($str);
- }
- }
-
- // Find protocol and hostspec
-
- // $dsn => proto(proto_opts)/database
- if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) {
- $proto = $match[1];
- $proto_opts = $match[2] ? $match[2] : false;
- $dsn = $match[3];
-
- // $dsn => protocol+hostspec/database (old format)
- } else {
- if (strpos($dsn, '+') !== false) {
- list($proto, $dsn) = explode('+', $dsn, 2);
- }
- if ( strpos($dsn, '//') === 0
- && strpos($dsn, '/', 2) !== false
- && $parsed['phptype'] == 'oci8'
- ) {
- //oracle's "Easy Connect" syntax:
- //"username/password@[//]host[:port][/service_name]"
- //e.g. "scott/tiger@//mymachine:1521/oracle"
- $proto_opts = $dsn;
- $dsn = null;
- } elseif (strpos($dsn, '/') !== false) {
- list($proto_opts, $dsn) = explode('/', $dsn, 2);
- } else {
- $proto_opts = $dsn;
- $dsn = null;
- }
- }
-
- // process the different protocol options
- $parsed['protocol'] = (!empty($proto)) ? $proto : 'tcp';
- $proto_opts = rawurldecode($proto_opts);
- if (strpos($proto_opts, ':') !== false) {
- list($proto_opts, $parsed['port']) = explode(':', $proto_opts);
- }
- if ($parsed['protocol'] == 'tcp') {
- $parsed['hostspec'] = $proto_opts;
- } elseif ($parsed['protocol'] == 'unix') {
- $parsed['socket'] = $proto_opts;
- }
-
- // Get dabase if any
- // $dsn => database
- if ($dsn) {
- // /database
- if (($pos = strpos($dsn, '?')) === false) {
- $parsed['database'] = $dsn;
- // /database?param1=value1¶m2=value2
- } else {
- $parsed['database'] = substr($dsn, 0, $pos);
- $dsn = substr($dsn, $pos + 1);
- if (strpos($dsn, '&') !== false) {
- $opts = explode('&', $dsn);
- } else { // database?param1=value1
- $opts = array($dsn);
- }
- foreach ($opts as $opt) {
- list($key, $value) = explode('=', $opt);
- if (!isset($parsed[$key])) {
- // don't allow params overwrite
- $parsed[$key] = rawurldecode($value);
- }
- }
- }
- }
-
- return $parsed;
- }
-
- // }}}
- // {{{ function fileExists($file)
-
- /**
- * Checks if a file exists in the include path
- *
- * @param string filename
- *
- * @return bool true success and false on error
- *
- * @access public
- */
- function fileExists($file)
- {
- // safe_mode does notwork with is_readable()
- if (!@ini_get('safe_mode')) {
- $dirs = explode(PATH_SEPARATOR, ini_get('include_path'));
- foreach ($dirs as $dir) {
- if (is_readable($dir . DIRECTORY_SEPARATOR . $file)) {
- return true;
- }
- }
- } else {
- $fp = @fopen($file, 'r', true);
- if (is_resource($fp)) {
- @fclose($fp);
- return true;
- }
- }
- return false;
- }
- // }}}
-}
-
-// }}}
-// {{{ class MDB2_Error extends PEAR_Error
-
-/**
- * MDB2_Error implements a class for reporting portable database error
- * messages.
- *
- * @package MDB2
- * @category Database
- * @author Stig Bakken <ssb@fast.no>
- */
-class MDB2_Error extends PEAR_Error
-{
- // {{{ constructor: function MDB2_Error($code = MDB2_ERROR, $mode = PEAR_ERROR_RETURN, $level = E_USER_NOTICE, $debuginfo = null)
-
- /**
- * MDB2_Error constructor.
- *
- * @param mixed MDB2 error code, or string with error message.
- * @param int what 'error mode' to operate in
- * @param int what error level to use for $mode & PEAR_ERROR_TRIGGER
- * @param mixed additional debug info, such as the last query
- */
- function MDB2_Error($code = MDB2_ERROR, $mode = PEAR_ERROR_RETURN,
- $level = E_USER_NOTICE, $debuginfo = null, $dummy = null)
- {
- if (is_null($code)) {
- $code = MDB2_ERROR;
- }
- $this->PEAR_Error('MDB2 Error: '.MDB2::errorMessage($code), $code,
- $mode, $level, $debuginfo);
- }
-
- // }}}
-}
-
-// }}}
-// {{{ class MDB2_Driver_Common extends PEAR
-
-/**
- * MDB2_Driver_Common: Base class that is extended by each MDB2 driver
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Driver_Common extends PEAR
-{
- // {{{ Variables (Properties)
-
- /**
- * index of the MDB2 object within the $GLOBALS['_MDB2_databases'] array
- * @var int
- * @access public
- */
- var $db_index = 0;
-
- /**
- * DSN used for the next query
- * @var array
- * @access protected
- */
- var $dsn = array();
-
- /**
- * DSN that was used to create the current connection
- * @var array
- * @access protected
- */
- var $connected_dsn = array();
-
- /**
- * connection resource
- * @var mixed
- * @access protected
- */
- var $connection = 0;
-
- /**
- * if the current opened connection is a persistent connection
- * @var bool
- * @access protected
- */
- var $opened_persistent;
-
- /**
- * the name of the database for the next query
- * @var string
- * @access protected
- */
- var $database_name = '';
-
- /**
- * the name of the database currently selected
- * @var string
- * @access protected
- */
- var $connected_database_name = '';
-
- /**
- * server version information
- * @var string
- * @access protected
- */
- var $connected_server_info = '';
-
- /**
- * list of all supported features of the given driver
- * @var array
- * @access public
- */
- var $supported = array(
- 'sequences' => false,
- 'indexes' => false,
- 'affected_rows' => false,
- 'summary_functions' => false,
- 'order_by_text' => false,
- 'transactions' => false,
- 'savepoints' => false,
- 'current_id' => false,
- 'limit_queries' => false,
- 'LOBs' => false,
- 'replace' => false,
- 'sub_selects' => false,
- 'auto_increment' => false,
- 'primary_key' => false,
- 'result_introspection' => false,
- 'prepared_statements' => false,
- 'identifier_quoting' => false,
- 'pattern_escaping' => false,
- 'new_link' => false,
- );
-
- /**
- * Array of supported options that can be passed to the MDB2 instance.
- *
- * The options can be set during object creation, using
- * MDB2::connect(), MDB2::factory() or MDB2::singleton(). The options can
- * also be set after the object is created, using MDB2::setOptions() or
- * MDB2_Driver_Common::setOption().
- * The list of available option includes:
- * <ul>
- * <li>$options['ssl'] -> boolean: determines if ssl should be used for connections</li>
- * <li>$options['field_case'] -> CASE_LOWER|CASE_UPPER: determines what case to force on field/table names</li>
- * <li>$options['disable_query'] -> boolean: determines if queries should be executed</li>
- * <li>$options['result_class'] -> string: class used for result sets</li>
- * <li>$options['buffered_result_class'] -> string: class used for buffered result sets</li>
- * <li>$options['result_wrap_class'] -> string: class used to wrap result sets into</li>
- * <li>$options['result_buffering'] -> boolean should results be buffered or not?</li>
- * <li>$options['fetch_class'] -> string: class to use when fetch mode object is used</li>
- * <li>$options['persistent'] -> boolean: persistent connection?</li>
- * <li>$options['debug'] -> integer: numeric debug level</li>
- * <li>$options['debug_handler'] -> string: function/method that captures debug messages</li>
- * <li>$options['debug_expanded_output'] -> bool: BC option to determine if more context information should be send to the debug handler</li>
- * <li>$options['default_text_field_length'] -> integer: default text field length to use</li>
- * <li>$options['lob_buffer_length'] -> integer: LOB buffer length</li>
- * <li>$options['log_line_break'] -> string: line-break format</li>
- * <li>$options['idxname_format'] -> string: pattern for index name</li>
- * <li>$options['seqname_format'] -> string: pattern for sequence name</li>
- * <li>$options['savepoint_format'] -> string: pattern for auto generated savepoint names</li>
- * <li>$options['statement_format'] -> string: pattern for prepared statement names</li>
- * <li>$options['seqcol_name'] -> string: sequence column name</li>
- * <li>$options['quote_identifier'] -> boolean: if identifier quoting should be done when check_option is used</li>
- * <li>$options['use_transactions'] -> boolean: if transaction use should be enabled</li>
- * <li>$options['decimal_places'] -> integer: number of decimal places to handle</li>
- * <li>$options['portability'] -> integer: portability constant</li>
- * <li>$options['modules'] -> array: short to long module name mapping for __call()</li>
- * <li>$options['emulate_prepared'] -> boolean: force prepared statements to be emulated</li>
- * <li>$options['datatype_map'] -> array: map user defined datatypes to other primitive datatypes</li>
- * <li>$options['datatype_map_callback'] -> array: callback function/method that should be called</li>
- * <li>$options['bindname_format'] -> string: regular expression pattern for named parameters
- * </ul>
- *
- * @var array
- * @access public
- * @see MDB2::connect()
- * @see MDB2::factory()
- * @see MDB2::singleton()
- * @see MDB2_Driver_Common::setOption()
- */
- var $options = array(
- 'ssl' => false,
- 'field_case' => CASE_LOWER,
- 'disable_query' => false,
- 'result_class' => 'MDB2_Result_%s',
- 'buffered_result_class' => 'MDB2_BufferedResult_%s',
- 'result_wrap_class' => false,
- 'result_buffering' => true,
- 'fetch_class' => 'stdClass',
- 'persistent' => false,
- 'debug' => 0,
- 'debug_handler' => 'MDB2_defaultDebugOutput',
- 'debug_expanded_output' => false,
- 'default_text_field_length' => 4096,
- 'lob_buffer_length' => 8192,
- 'log_line_break' => "\n",
- 'idxname_format' => '%s_idx',
- 'seqname_format' => '%s_seq',
- 'savepoint_format' => 'MDB2_SAVEPOINT_%s',
- 'statement_format' => 'MDB2_STATEMENT_%1$s_%2$s',
- 'seqcol_name' => 'sequence',
- 'quote_identifier' => false,
- 'use_transactions' => true,
- 'decimal_places' => 2,
- 'portability' => MDB2_PORTABILITY_ALL,
- 'modules' => array(
- 'ex' => 'Extended',
- 'dt' => 'Datatype',
- 'mg' => 'Manager',
- 'rv' => 'Reverse',
- 'na' => 'Native',
- 'fc' => 'Function',
- ),
- 'emulate_prepared' => false,
- 'datatype_map' => array(),
- 'datatype_map_callback' => array(),
- 'nativetype_map_callback' => array(),
- 'lob_allow_url_include' => false,
- 'bindname_format' => '(?:\d+)|(?:[a-zA-Z][a-zA-Z0-9_]*)',
- );
-
- /**
- * string array
- * @var string
- * @access protected
- */
- var $string_quoting = array('start' => "'", 'end' => "'", 'escape' => false, 'escape_pattern' => false);
-
- /**
- * identifier quoting
- * @var array
- * @access protected
- */
- var $identifier_quoting = array('start' => '"', 'end' => '"', 'escape' => '"');
-
- /**
- * sql comments
- * @var array
- * @access protected
- */
- var $sql_comments = array(
- array('start' => '--', 'end' => "\n", 'escape' => false),
- array('start' => '/*', 'end' => '*/', 'escape' => false),
- );
-
- /**
- * comparision wildcards
- * @var array
- * @access protected
- */
- var $wildcards = array('%', '_');
-
- /**
- * column alias keyword
- * @var string
- * @access protected
- */
- var $as_keyword = ' AS ';
-
- /**
- * warnings
- * @var array
- * @access protected
- */
- var $warnings = array();
-
- /**
- * string with the debugging information
- * @var string
- * @access public
- */
- var $debug_output = '';
-
- /**
- * determine if there is an open transaction
- * @var bool
- * @access protected
- */
- var $in_transaction = false;
-
- /**
- * the smart transaction nesting depth
- * @var int
- * @access protected
- */
- var $nested_transaction_counter = null;
-
- /**
- * the first error that occured inside a nested transaction
- * @var MDB2_Error|bool
- * @access protected
- */
- var $has_transaction_error = false;
-
- /**
- * result offset used in the next query
- * @var int
- * @access protected
- */
- var $offset = 0;
-
- /**
- * result limit used in the next query
- * @var int
- * @access protected
- */
- var $limit = 0;
-
- /**
- * Database backend used in PHP (mysql, odbc etc.)
- * @var string
- * @access public
- */
- var $phptype;
-
- /**
- * Database used with regards to SQL syntax etc.
- * @var string
- * @access public
- */
- var $dbsyntax;
-
- /**
- * the last query sent to the driver
- * @var string
- * @access public
- */
- var $last_query;
-
- /**
- * the default fetchmode used
- * @var int
- * @access protected
- */
- var $fetchmode = MDB2_FETCHMODE_ORDERED;
-
- /**
- * array of module instances
- * @var array
- * @access protected
- */
- var $modules = array();
-
- /**
- * determines of the PHP4 destructor emulation has been enabled yet
- * @var array
- * @access protected
- */
- var $destructor_registered = true;
-
- // }}}
- // {{{ constructor: function __construct()
-
- /**
- * Constructor
- */
- function __construct()
- {
- end($GLOBALS['_MDB2_databases']);
- $db_index = key($GLOBALS['_MDB2_databases']) + 1;
- $GLOBALS['_MDB2_databases'][$db_index] = &$this;
- $this->db_index = $db_index;
- }
-
- // }}}
- // {{{ function MDB2_Driver_Common()
-
- /**
- * PHP 4 Constructor
- */
- function MDB2_Driver_Common()
- {
- $this->destructor_registered = false;
- $this->__construct();
- }
-
- // }}}
- // {{{ destructor: function __destruct()
-
- /**
- * Destructor
- */
- function __destruct()
- {
- $this->disconnect(false);
- }
-
- // }}}
- // {{{ function free()
-
- /**
- * Free the internal references so that the instance can be destroyed
- *
- * @return bool true on success, false if result is invalid
- *
- * @access public
- */
- function free()
- {
- unset($GLOBALS['_MDB2_databases'][$this->db_index]);
- unset($this->db_index);
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function __toString()
-
- /**
- * String conversation
- *
- * @return string representation of the object
- *
- * @access public
- */
- function __toString()
- {
- $info = get_class($this);
- $info.= ': (phptype = '.$this->phptype.', dbsyntax = '.$this->dbsyntax.')';
- if ($this->connection) {
- $info.= ' [connected]';
- }
- return $info;
- }
-
- // }}}
- // {{{ function errorInfo($error = null)
-
- /**
- * This method is used to collect information about an error
- *
- * @param mixed error code or resource
- *
- * @return array with MDB2 errorcode, native error code, native message
- *
- * @access public
- */
- function errorInfo($error = null)
- {
- return array($error, null, null);
- }
-
- // }}}
- // {{{ function &raiseError($code = null, $mode = null, $options = null, $userinfo = null)
-
- /**
- * This method is used to communicate an error and invoke error
- * callbacks etc. Basically a wrapper for PEAR::raiseError
- * without the message string.
- *
- * @param mixed integer error code, or a PEAR error object (all other
- * parameters are ignored if this parameter is an object
- * @param int error mode, see PEAR_Error docs
- * @param mixed If error mode is PEAR_ERROR_TRIGGER, this is the
- * error level (E_USER_NOTICE etc). If error mode is
- * PEAR_ERROR_CALLBACK, this is the callback function,
- * either as a function name, or as an array of an
- * object and method name. For other error modes this
- * parameter is ignored.
- * @param string Extra debug information. Defaults to the last
- * query and native error code.
- * @param string name of the method that triggered the error
- *
- * @return PEAR_Error instance of a PEAR Error object
- *
- * @access public
- * @see PEAR_Error
- */
- function &raiseError($code = null, $mode = null, $options = null, $userinfo = null, $method = null)
- {
- $userinfo = "[Error message: $userinfo]\n";
- // The error is yet a MDB2 error object
- if (PEAR::isError($code)) {
- // because we use the static PEAR::raiseError, our global
- // handler should be used if it is set
- if (is_null($mode) && !empty($this->_default_error_mode)) {
- $mode = $this->_default_error_mode;
- $options = $this->_default_error_options;
- }
- if (is_null($userinfo)) {
- $userinfo = $code->getUserinfo();
- }
- $code = $code->getCode();
- } elseif ($code == MDB2_ERROR_NOT_FOUND) {
- // extension not loaded: don't call $this->errorInfo() or the script
- // will die
- } elseif (isset($this->connection)) {
- if (!empty($this->last_query)) {
- $userinfo.= "[Last executed query: {$this->last_query}]\n";
- }
- $native_errno = $native_msg = null;
- list($code, $native_errno, $native_msg) = $this->errorInfo($code);
- if (!is_null($native_errno) && $native_errno !== '') {
- $userinfo.= "[Native code: $native_errno]\n";
- }
- if (!is_null($native_msg) && $native_msg !== '') {
- $userinfo.= "[Native message: ". strip_tags($native_msg) ."]\n";
- }
- if (!is_null($method)) {
- $userinfo = $method.': '.$userinfo;
- }
- }
-
- $err =& PEAR::raiseError(null, $code, $mode, $options, $userinfo, 'MDB2_Error', true);
- if ($err->getMode() !== PEAR_ERROR_RETURN
- && isset($this->nested_transaction_counter) && !$this->has_transaction_error) {
- $this->has_transaction_error =& $err;
- }
- return $err;
- }
-
- // }}}
- // {{{ function resetWarnings()
-
- /**
- * reset the warning array
- *
- * @return void
- *
- * @access public
- */
- function resetWarnings()
- {
- $this->warnings = array();
- }
-
- // }}}
- // {{{ function getWarnings()
-
- /**
- * Get all warnings in reverse order.
- * This means that the last warning is the first element in the array
- *
- * @return array with warnings
- *
- * @access public
- * @see resetWarnings()
- */
- function getWarnings()
- {
- return array_reverse($this->warnings);
- }
-
- // }}}
- // {{{ function setFetchMode($fetchmode, $object_class = 'stdClass')
-
- /**
- * Sets which fetch mode should be used by default on queries
- * on this connection
- *
- * @param int MDB2_FETCHMODE_ORDERED, MDB2_FETCHMODE_ASSOC
- * or MDB2_FETCHMODE_OBJECT
- * @param string the class name of the object to be returned
- * by the fetch methods when the
- * MDB2_FETCHMODE_OBJECT mode is selected.
- * If no class is specified by default a cast
- * to object from the assoc array row will be
- * done. There is also the possibility to use
- * and extend the 'MDB2_row' class.
- *
- * @return mixed MDB2_OK or MDB2 Error Object
- *
- * @access public
- * @see MDB2_FETCHMODE_ORDERED, MDB2_FETCHMODE_ASSOC, MDB2_FETCHMODE_OBJECT
- */
- function setFetchMode($fetchmode, $object_class = 'stdClass')
- {
- switch ($fetchmode) {
- case MDB2_FETCHMODE_OBJECT:
- $this->options['fetch_class'] = $object_class;
- case MDB2_FETCHMODE_ORDERED:
- case MDB2_FETCHMODE_ASSOC:
- $this->fetchmode = $fetchmode;
- break;
- default:
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'invalid fetchmode mode', __FUNCTION__);
- }
-
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function setOption($option, $value)
-
- /**
- * set the option for the db class
- *
- * @param string option name
- * @param mixed value for the option
- *
- * @return mixed MDB2_OK or MDB2 Error Object
- *
- * @access public
- */
- function setOption($option, $value)
- {
- if (array_key_exists($option, $this->options)) {
- $this->options[$option] = $value;
- return MDB2_OK;
- }
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- "unknown option $option", __FUNCTION__);
- }
-
- // }}}
- // {{{ function getOption($option)
-
- /**
- * Returns the value of an option
- *
- * @param string option name
- *
- * @return mixed the option value or error object
- *
- * @access public
- */
- function getOption($option)
- {
- if (array_key_exists($option, $this->options)) {
- return $this->options[$option];
- }
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- "unknown option $option", __FUNCTION__);
- }
-
- // }}}
- // {{{ function debug($message, $scope = '', $is_manip = null)
-
- /**
- * set a debug message
- *
- * @param string message that should be appended to the debug variable
- * @param string usually the method name that triggered the debug call:
- * for example 'query', 'prepare', 'execute', 'parameters',
- * 'beginTransaction', 'commit', 'rollback'
- * @param array contains context information about the debug() call
- * common keys are: is_manip, time, result etc.
- *
- * @return void
- *
- * @access public
- */
- function debug($message, $scope = '', $context = array())
- {
- if ($this->options['debug'] && $this->options['debug_handler']) {
- if (!$this->options['debug_expanded_output']) {
- if (!empty($context['when']) && $context['when'] !== 'pre') {
- return null;
- }
- $context = empty($context['is_manip']) ? false : $context['is_manip'];
- }
- return call_user_func_array($this->options['debug_handler'], array(&$this, $scope, $message, $context));
- }
- return null;
- }
-
- // }}}
- // {{{ function getDebugOutput()
-
- /**
- * output debug info
- *
- * @return string content of the debug_output class variable
- *
- * @access public
- */
- function getDebugOutput()
- {
- return $this->debug_output;
- }
-
- // }}}
- // {{{ function escape($text)
-
- /**
- * Quotes a string so it can be safely used in a query. It will quote
- * the text so it can safely be used within a query.
- *
- * @param string the input string to quote
- * @param bool escape wildcards
- *
- * @return string quoted string
- *
- * @access public
- */
- function escape($text, $escape_wildcards = false)
- {
- if ($escape_wildcards) {
- $text = $this->escapePattern($text);
- }
-
- $text = str_replace($this->string_quoting['end'], $this->string_quoting['escape'] . $this->string_quoting['end'], $text);
- return $text;
- }
-
- // }}}
- // {{{ function escapePattern($text)
-
- /**
- * Quotes pattern (% and _) characters in a string)
- *
- * @param string the input string to quote
- *
- * @return string quoted string
- *
- * @access public
- */
- function escapePattern($text)
- {
- if ($this->string_quoting['escape_pattern']) {
- $text = str_replace($this->string_quoting['escape_pattern'], $this->string_quoting['escape_pattern'] . $this->string_quoting['escape_pattern'], $text);
- foreach ($this->wildcards as $wildcard) {
- $text = str_replace($wildcard, $this->string_quoting['escape_pattern'] . $wildcard, $text);
- }
- }
- return $text;
- }
-
- // }}}
- // {{{ function quoteIdentifier($str, $check_option = false)
-
- /**
- * Quote a string so it can be safely used as a table or column name
- *
- * Delimiting style depends on which database driver is being used.
- *
- * NOTE: just because you CAN use delimited identifiers doesn't mean
- * you SHOULD use them. In general, they end up causing way more
- * problems than they solve.
- *
- * NOTE: if you have table names containing periods, don't use this method
- * (@see bug #11906)
- *
- * Portability is broken by using the following characters inside
- * delimited identifiers:
- * + backtick (<kbd>`</kbd>) -- due to MySQL
- * + double quote (<kbd>"</kbd>) -- due to Oracle
- * + brackets (<kbd>[</kbd> or <kbd>]</kbd>) -- due to Access
- *
- * Delimited identifiers are known to generally work correctly under
- * the following drivers:
- * + mssql
- * + mysql
- * + mysqli
- * + oci8
- * + pgsql
- * + sqlite
- *
- * InterBase doesn't seem to be able to use delimited identifiers
- * via PHP 4. They work fine under PHP 5.
- *
- * @param string identifier name to be quoted
- * @param bool check the 'quote_identifier' option
- *
- * @return string quoted identifier string
- *
- * @access public
- */
- function quoteIdentifier($str, $check_option = false)
- {
- if ($check_option && !$this->options['quote_identifier']) {
- return $str;
- }
- $str = str_replace($this->identifier_quoting['end'], $this->identifier_quoting['escape'] . $this->identifier_quoting['end'], $str);
- $parts = explode('.', $str);
- foreach (array_keys($parts) as $k) {
- $parts[$k] = $this->identifier_quoting['start'] . $parts[$k] . $this->identifier_quoting['end'];
- }
- return implode('.', $parts);
- }
-
- // }}}
- // {{{ function getAsKeyword()
-
- /**
- * Gets the string to alias column
- *
- * @return string to use when aliasing a column
- */
- function getAsKeyword()
- {
- return $this->as_keyword;
- }
-
- // }}}
- // {{{ function getConnection()
-
- /**
- * Returns a native connection
- *
- * @return mixed a valid MDB2 connection object,
- * or a MDB2 error object on error
- *
- * @access public
- */
- function getConnection()
- {
- $result = $this->connect();
- if (PEAR::isError($result)) {
- return $result;
- }
- return $this->connection;
- }
-
- // }}}
- // {{{ function _fixResultArrayValues(&$row, $mode)
-
- /**
- * Do all necessary conversions on result arrays to fix DBMS quirks
- *
- * @param array the array to be fixed (passed by reference)
- * @param array bit-wise addition of the required portability modes
- *
- * @return void
- *
- * @access protected
- */
- function _fixResultArrayValues(&$row, $mode)
- {
- switch ($mode) {
- case MDB2_PORTABILITY_EMPTY_TO_NULL:
- foreach ($row as $key => $value) {
- if ($value === '') {
- $row[$key] = null;
- }
- }
- break;
- case MDB2_PORTABILITY_RTRIM:
- foreach ($row as $key => $value) {
- if (is_string($value)) {
- $row[$key] = rtrim($value);
- }
- }
- break;
- case MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES:
- $tmp_row = array();
- foreach ($row as $key => $value) {
- $tmp_row[preg_replace('/^(?:.*\.)?([^.]+)$/', '\\1', $key)] = $value;
- }
- $row = $tmp_row;
- break;
- case (MDB2_PORTABILITY_RTRIM + MDB2_PORTABILITY_EMPTY_TO_NULL):
- foreach ($row as $key => $value) {
- if ($value === '') {
- $row[$key] = null;
- } elseif (is_string($value)) {
- $row[$key] = rtrim($value);
- }
- }
- break;
- case (MDB2_PORTABILITY_RTRIM + MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES):
- $tmp_row = array();
- foreach ($row as $key => $value) {
- if (is_string($value)) {
- $value = rtrim($value);
- }
- $tmp_row[preg_replace('/^(?:.*\.)?([^.]+)$/', '\\1', $key)] = $value;
- }
- $row = $tmp_row;
- break;
- case (MDB2_PORTABILITY_EMPTY_TO_NULL + MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES):
- $tmp_row = array();
- foreach ($row as $key => $value) {
- if ($value === '') {
- $value = null;
- }
- $tmp_row[preg_replace('/^(?:.*\.)?([^.]+)$/', '\\1', $key)] = $value;
- }
- $row = $tmp_row;
- break;
- case (MDB2_PORTABILITY_RTRIM + MDB2_PORTABILITY_EMPTY_TO_NULL + MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES):
- $tmp_row = array();
- foreach ($row as $key => $value) {
- if ($value === '') {
- $value = null;
- } elseif (is_string($value)) {
- $value = rtrim($value);
- }
- $tmp_row[preg_replace('/^(?:.*\.)?([^.]+)$/', '\\1', $key)] = $value;
- }
- $row = $tmp_row;
- break;
- }
- }
-
- // }}}
- // {{{ function &loadModule($module, $property = null, $phptype_specific = null)
-
- /**
- * loads a module
- *
- * @param string name of the module that should be loaded
- * (only used for error messages)
- * @param string name of the property into which the class will be loaded
- * @param bool if the class to load for the module is specific to the
- * phptype
- *
- * @return object on success a reference to the given module is returned
- * and on failure a PEAR error
- *
- * @access public
- */
- function &loadModule($module, $property = null, $phptype_specific = null)
- {
- if (!$property) {
- $property = strtolower($module);
- }
-
- if (!isset($this->{$property})) {
- $version = $phptype_specific;
- if ($phptype_specific !== false) {
- $version = true;
- $class_name = 'MDB2_Driver_'.$module.'_'.$this->phptype;
- $file_name = str_replace('_', DIRECTORY_SEPARATOR, $class_name).'.php';
- }
- if ($phptype_specific === false
- || (!MDB2::classExists($class_name) && !MDB2::fileExists($file_name))
- ) {
- $version = false;
- $class_name = 'MDB2_'.$module;
- $file_name = str_replace('_', DIRECTORY_SEPARATOR, $class_name).'.php';
- }
-
- $err = MDB2::loadClass($class_name, $this->getOption('debug'));
- if (PEAR::isError($err)) {
- return $err;
- }
-
- // load module in a specific version
- if ($version) {
- if (method_exists($class_name, 'getClassName')) {
- $class_name_new = call_user_func(array($class_name, 'getClassName'), $this->db_index);
- if ($class_name != $class_name_new) {
- $class_name = $class_name_new;
- $err = MDB2::loadClass($class_name, $this->getOption('debug'));
- if (PEAR::isError($err)) {
- return $err;
- }
- }
- }
- }
-
- if (!MDB2::classExists($class_name)) {
- $err =& $this->raiseError(MDB2_ERROR_LOADMODULE, null, null,
- "unable to load module '$module' into property '$property'", __FUNCTION__);
- return $err;
- }
- $this->{$property} = new $class_name($this->db_index);
- $this->modules[$module] =& $this->{$property};
- if ($version) {
- // this will be used in the connect method to determine if the module
- // needs to be loaded with a different version if the server
- // version changed in between connects
- $this->loaded_version_modules[] = $property;
- }
- }
-
- return $this->{$property};
- }
-
- // }}}
- // {{{ function __call($method, $params)
-
- /**
- * Calls a module method using the __call magic method
- *
- * @param string Method name.
- * @param array Arguments.
- *
- * @return mixed Returned value.
- */
- function __call($method, $params)
- {
- $module = null;
- if (preg_match('/^([a-z]+)([A-Z])(.*)$/', $method, $match)
- && isset($this->options['modules'][$match[1]])
- ) {
- $module = $this->options['modules'][$match[1]];
- $method = strtolower($match[2]).$match[3];
- if (!isset($this->modules[$module]) || !is_object($this->modules[$module])) {
- $result =& $this->loadModule($module);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- } else {
- foreach ($this->modules as $key => $foo) {
- if (is_object($this->modules[$key])
- && method_exists($this->modules[$key], $method)
- ) {
- $module = $key;
- break;
- }
- }
- }
- if (!is_null($module)) {
- return call_user_func_array(array(&$this->modules[$module], $method), $params);
- }
- trigger_error(sprintf('Call to undefined function: %s::%s().', get_class($this), $method), E_USER_ERROR);
- }
-
- // }}}
- // {{{ function beginTransaction($savepoint = null)
-
- /**
- * Start a transaction or set a savepoint.
- *
- * @param string name of a savepoint to set
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function beginTransaction($savepoint = null)
- {
- $this->debug('Starting transaction', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'transactions are not supported', __FUNCTION__);
- }
-
- // }}}
- // {{{ function commit($savepoint = null)
-
- /**
- * Commit the database changes done during a transaction that is in
- * progress or release a savepoint. This function may only be called when
- * auto-committing is disabled, otherwise it will fail. Therefore, a new
- * transaction is implicitly started after committing the pending changes.
- *
- * @param string name of a savepoint to release
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function commit($savepoint = null)
- {
- $this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'commiting transactions is not supported', __FUNCTION__);
- }
-
- // }}}
- // {{{ function rollback($savepoint = null)
-
- /**
- * Cancel any database changes done during a transaction or since a specific
- * savepoint that is in progress. This function may only be called when
- * auto-committing is disabled, otherwise it will fail. Therefore, a new
- * transaction is implicitly started after canceling the pending changes.
- *
- * @param string name of a savepoint to rollback to
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function rollback($savepoint = null)
- {
- $this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'rolling back transactions is not supported', __FUNCTION__);
- }
-
- // }}}
- // {{{ function inTransaction($ignore_nested = false)
-
- /**
- * If a transaction is currently open.
- *
- * @param bool if the nested transaction count should be ignored
- * @return int|bool - an integer with the nesting depth is returned if a
- * nested transaction is open
- * - true is returned for a normal open transaction
- * - false is returned if no transaction is open
- *
- * @access public
- */
- function inTransaction($ignore_nested = false)
- {
- if (!$ignore_nested && isset($this->nested_transaction_counter)) {
- return $this->nested_transaction_counter;
- }
- return $this->in_transaction;
- }
-
- // }}}
- // {{{ function setTransactionIsolation($isolation)
-
- /**
- * Set the transacton isolation level.
- *
- * @param string standard isolation level
- * READ UNCOMMITTED (allows dirty reads)
- * READ COMMITTED (prevents dirty reads)
- * REPEATABLE READ (prevents nonrepeatable reads)
- * SERIALIZABLE (prevents phantom reads)
- * @param array some transaction options:
- * 'wait' => 'WAIT' | 'NO WAIT'
- * 'rw' => 'READ WRITE' | 'READ ONLY'
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- * @since 2.1.1
- */
- function setTransactionIsolation($isolation, $options = array())
- {
- $this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true));
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'isolation level setting is not supported', __FUNCTION__);
- }
-
- // }}}
- // {{{ function beginNestedTransaction($savepoint = false)
-
- /**
- * Start a nested transaction.
- *
- * @return mixed MDB2_OK on success/savepoint name, a MDB2 error on failure
- *
- * @access public
- * @since 2.1.1
- */
- function beginNestedTransaction()
- {
- if ($this->in_transaction) {
- ++$this->nested_transaction_counter;
- $savepoint = sprintf($this->options['savepoint_format'], $this->nested_transaction_counter);
- if ($this->supports('savepoints') && $savepoint) {
- return $this->beginTransaction($savepoint);
- }
- return MDB2_OK;
- }
- $this->has_transaction_error = false;
- $result = $this->beginTransaction();
- $this->nested_transaction_counter = 1;
- return $result;
- }
-
- // }}}
- // {{{ function completeNestedTransaction($force_rollback = false, $release = false)
-
- /**
- * Finish a nested transaction by rolling back if an error occured or
- * committing otherwise.
- *
- * @param bool if the transaction should be rolled back regardless
- * even if no error was set within the nested transaction
- * @return mixed MDB_OK on commit/counter decrementing, false on rollback
- * and a MDB2 error on failure
- *
- * @access public
- * @since 2.1.1
- */
- function completeNestedTransaction($force_rollback = false)
- {
- if ($this->nested_transaction_counter > 1) {
- $savepoint = sprintf($this->options['savepoint_format'], $this->nested_transaction_counter);
- if ($this->supports('savepoints') && $savepoint) {
- if ($force_rollback || $this->has_transaction_error) {
- $result = $this->rollback($savepoint);
- if (!PEAR::isError($result)) {
- $result = false;
- $this->has_transaction_error = false;
- }
- } else {
- $result = $this->commit($savepoint);
- }
- } else {
- $result = MDB2_OK;
- }
- --$this->nested_transaction_counter;
- return $result;
- }
-
- $this->nested_transaction_counter = null;
- $result = MDB2_OK;
-
- // transaction has not yet been rolled back
- if ($this->in_transaction) {
- if ($force_rollback || $this->has_transaction_error) {
- $result = $this->rollback();
- if (!PEAR::isError($result)) {
- $result = false;
- }
- } else {
- $result = $this->commit();
- }
- }
- $this->has_transaction_error = false;
- return $result;
- }
-
- // }}}
- // {{{ function failNestedTransaction($error = null, $immediately = false)
-
- /**
- * Force setting nested transaction to failed.
- *
- * @param mixed value to return in getNestededTransactionError()
- * @param bool if the transaction should be rolled back immediately
- * @return bool MDB2_OK
- *
- * @access public
- * @since 2.1.1
- */
- function failNestedTransaction($error = null, $immediately = false)
- {
- if (is_null($error)) {
- $error = $this->has_transaction_error ? $this->has_transaction_error : true;
- } elseif (!$error) {
- $error = true;
- }
- $this->has_transaction_error = $error;
- if (!$immediately) {
- return MDB2_OK;
- }
- return $this->rollback();
- }
-
- // }}}
- // {{{ function getNestedTransactionError()
-
- /**
- * The first error that occured since the transaction start.
- *
- * @return MDB2_Error|bool MDB2 error object if an error occured or false.
- *
- * @access public
- * @since 2.1.1
- */
- function getNestedTransactionError()
- {
- return $this->has_transaction_error;
- }
-
- // }}}
- // {{{ connect()
-
- /**
- * Connect to the database
- *
- * @return true on success, MDB2 Error Object on failure
- */
- function connect()
- {
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ setCharset($charset, $connection = null)
-
- /**
- * Set the charset on the current connection
- *
- * @param string charset
- * @param resource connection handle
- *
- * @return true on success, MDB2 Error Object on failure
- */
- function setCharset($charset, $connection = null)
- {
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ function disconnect($force = true)
-
- /**
- * Log out and disconnect from the database.
- *
- * @param bool if the disconnect should be forced even if the
- * connection is opened persistently
- *
- * @return mixed true on success, false if not connected and error
- * object on error
- *
- * @access public
- */
- function disconnect($force = true)
- {
- $this->connection = 0;
- $this->connected_dsn = array();
- $this->connected_database_name = '';
- $this->opened_persistent = null;
- $this->connected_server_info = '';
- $this->in_transaction = null;
- $this->nested_transaction_counter = null;
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function setDatabase($name)
-
- /**
- * Select a different database
- *
- * @param string name of the database that should be selected
- *
- * @return string name of the database previously connected to
- *
- * @access public
- */
- function setDatabase($name)
- {
- $previous_database_name = (isset($this->database_name)) ? $this->database_name : '';
- $this->database_name = $name;
- $this->disconnect(false);
- return $previous_database_name;
- }
-
- // }}}
- // {{{ function getDatabase()
-
- /**
- * Get the current database
- *
- * @return string name of the database
- *
- * @access public
- */
- function getDatabase()
- {
- return $this->database_name;
- }
-
- // }}}
- // {{{ function setDSN($dsn)
-
- /**
- * set the DSN
- *
- * @param mixed DSN string or array
- *
- * @return MDB2_OK
- *
- * @access public
- */
- function setDSN($dsn)
- {
- $dsn_default = $GLOBALS['_MDB2_dsninfo_default'];
- $dsn = MDB2::parseDSN($dsn);
- if (array_key_exists('database', $dsn)) {
- $this->database_name = $dsn['database'];
- unset($dsn['database']);
- }
- $this->dsn = array_merge($dsn_default, $dsn);
- return $this->disconnect(false);
- }
-
- // }}}
- // {{{ function getDSN($type = 'string', $hidepw = false)
-
- /**
- * return the DSN as a string
- *
- * @param string format to return ("array", "string")
- * @param string string to hide the password with
- *
- * @return mixed DSN in the chosen type
- *
- * @access public
- */
- function getDSN($type = 'string', $hidepw = false)
- {
- $dsn = array_merge($GLOBALS['_MDB2_dsninfo_default'], $this->dsn);
- $dsn['phptype'] = $this->phptype;
- $dsn['database'] = $this->database_name;
- if ($hidepw) {
- $dsn['password'] = $hidepw;
- }
- switch ($type) {
- // expand to include all possible options
- case 'string':
- $dsn = $dsn['phptype'].
- ($dsn['dbsyntax'] ? ('('.$dsn['dbsyntax'].')') : '').
- '://'.$dsn['username'].':'.
- $dsn['password'].'@'.$dsn['hostspec'].
- ($dsn['port'] ? (':'.$dsn['port']) : '').
- '/'.$dsn['database'];
- break;
- case 'array':
- default:
- break;
- }
- return $dsn;
- }
-
- // }}}
- // {{{ function &standaloneQuery($query, $types = null, $is_manip = false)
-
- /**
- * execute a query as database administrator
- *
- * @param string the SQL query
- * @param mixed array that contains the types of the columns in
- * the result set
- * @param bool if the query is a manipulation query
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function &standaloneQuery($query, $types = null, $is_manip = false)
- {
- $offset = $this->offset;
- $limit = $this->limit;
- $this->offset = $this->limit = 0;
- $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
-
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
-
- $result =& $this->_doQuery($query, $is_manip, $connection, false);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- if ($is_manip) {
- $affected_rows = $this->_affectedRows($connection, $result);
- return $affected_rows;
- }
- $result =& $this->_wrapResult($result, $types, true, false, $limit, $offset);
- return $result;
- }
-
- // }}}
- // {{{ function _modifyQuery($query, $is_manip, $limit, $offset)
-
- /**
- * Changes a query string for various DBMS specific reasons
- *
- * @param string query to modify
- * @param bool if it is a DML query
- * @param int limit the number of rows
- * @param int start reading from given offset
- *
- * @return string modified query
- *
- * @access protected
- */
- function _modifyQuery($query, $is_manip, $limit, $offset)
- {
- return $query;
- }
-
- // }}}
- // {{{ function &_doQuery($query, $is_manip = false, $connection = null, $database_name = null)
-
- /**
- * Execute a query
- * @param string query
- * @param bool if the query is a manipulation query
- * @param resource connection handle
- * @param string database name
- *
- * @return result or error object
- *
- * @access protected
- */
- function &_doQuery($query, $is_manip = false, $connection = null, $database_name = null)
- {
- $this->last_query = $query;
- $result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre'));
- if ($result) {
- if (PEAR::isError($result)) {
- return $result;
- }
- $query = $result;
- }
- $err =& $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- return $err;
- }
-
- // }}}
- // {{{ function _affectedRows($connection, $result = null)
-
- /**
- * Returns the number of rows affected
- *
- * @param resource result handle
- * @param resource connection handle
- *
- * @return mixed MDB2 Error Object or the number of rows affected
- *
- * @access private
- */
- function _affectedRows($connection, $result = null)
- {
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ function &exec($query)
-
- /**
- * Execute a manipulation query to the database and return the number of affected rows
- *
- * @param string the SQL query
- *
- * @return mixed number of affected rows on success, a MDB2 error on failure
- *
- * @access public
- */
- function &exec($query)
- {
- $offset = $this->offset;
- $limit = $this->limit;
- $this->offset = $this->limit = 0;
- $query = $this->_modifyQuery($query, true, $limit, $offset);
-
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
-
- $result =& $this->_doQuery($query, true, $connection, $this->database_name);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- $affectedRows = $this->_affectedRows($connection, $result);
- return $affectedRows;
- }
-
- // }}}
- // {{{ function &query($query, $types = null, $result_class = true, $result_wrap_class = false)
-
- /**
- * Send a query to the database and return any results
- *
- * @param string the SQL query
- * @param mixed array that contains the types of the columns in
- * the result set
- * @param mixed string which specifies which result class to use
- * @param mixed string which specifies which class to wrap results in
- *
- * @return mixed an MDB2_Result handle on success, a MDB2 error on failure
- *
- * @access public
- */
- function &query($query, $types = null, $result_class = true, $result_wrap_class = false)
- {
- $offset = $this->offset;
- $limit = $this->limit;
- $this->offset = $this->limit = 0;
- $query = $this->_modifyQuery($query, false, $limit, $offset);
-
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
-
- $result =& $this->_doQuery($query, false, $connection, $this->database_name);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- $result =& $this->_wrapResult($result, $types, $result_class, $result_wrap_class, $limit, $offset);
- return $result;
- }
-
- // }}}
- // {{{ function &_wrapResult($result, $types = array(), $result_class = true, $result_wrap_class = false, $limit = null, $offset = null)
-
- /**
- * wrap a result set into the correct class
- *
- * @param resource result handle
- * @param mixed array that contains the types of the columns in
- * the result set
- * @param mixed string which specifies which result class to use
- * @param mixed string which specifies which class to wrap results in
- * @param string number of rows to select
- * @param string first row to select
- *
- * @return mixed an MDB2_Result, a MDB2 error on failure
- *
- * @access protected
- */
- function &_wrapResult($result, $types = array(), $result_class = true,
- $result_wrap_class = false, $limit = null, $offset = null)
- {
- if ($types === true) {
- if ($this->supports('result_introspection')) {
- $this->loadModule('Reverse', null, true);
- $tableInfo = $this->reverse->tableInfo($result);
- if (PEAR::isError($tableInfo)) {
- return $tableInfo;
- }
- $types = array();
- foreach ($tableInfo as $field) {
- $types[] = $field['mdb2type'];
- }
- } else {
- $types = null;
- }
- }
-
- if ($result_class === true) {
- $result_class = $this->options['result_buffering']
- ? $this->options['buffered_result_class'] : $this->options['result_class'];
- }
-
- if ($result_class) {
- $class_name = sprintf($result_class, $this->phptype);
- if (!MDB2::classExists($class_name)) {
- $err =& $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'result class does not exist '.$class_name, __FUNCTION__);
- return $err;
- }
- $result =& new $class_name($this, $result, $limit, $offset);
- if (!MDB2::isResultCommon($result)) {
- $err =& $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'result class is not extended from MDB2_Result_Common', __FUNCTION__);
- return $err;
- }
- if (!empty($types)) {
- $err = $result->setResultTypes($types);
- if (PEAR::isError($err)) {
- $result->free();
- return $err;
- }
- }
- }
- if ($result_wrap_class === true) {
- $result_wrap_class = $this->options['result_wrap_class'];
- }
- if ($result_wrap_class) {
- if (!MDB2::classExists($result_wrap_class)) {
- $err =& $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'result wrap class does not exist '.$result_wrap_class, __FUNCTION__);
- return $err;
- }
- $result = new $result_wrap_class($result, $this->fetchmode);
- }
- return $result;
- }
-
- // }}}
- // {{{ function getServerVersion($native = false)
-
- /**
- * return version information about the server
- *
- * @param bool determines if the raw version string should be returned
- *
- * @return mixed array with version information or row string
- *
- * @access public
- */
- function getServerVersion($native = false)
- {
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ function setLimit($limit, $offset = null)
-
- /**
- * set the range of the next query
- *
- * @param string number of rows to select
- * @param string first row to select
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function setLimit($limit, $offset = null)
- {
- if (!$this->supports('limit_queries')) {
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'limit is not supported by this driver', __FUNCTION__);
- }
- $limit = (int)$limit;
- if ($limit < 0) {
- return $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
- 'it was not specified a valid selected range row limit', __FUNCTION__);
- }
- $this->limit = $limit;
- if (!is_null($offset)) {
- $offset = (int)$offset;
- if ($offset < 0) {
- return $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
- 'it was not specified a valid first selected range row', __FUNCTION__);
- }
- $this->offset = $offset;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function subSelect($query, $type = false)
-
- /**
- * simple subselect emulation: leaves the query untouched for all RDBMS
- * that support subselects
- *
- * @param string the SQL query for the subselect that may only
- * return a column
- * @param string determines type of the field
- *
- * @return string the query
- *
- * @access public
- */
- function subSelect($query, $type = false)
- {
- if ($this->supports('sub_selects') === true) {
- return $query;
- }
-
- if (!$this->supports('sub_selects')) {
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- $col = $this->queryCol($query, $type);
- if (PEAR::isError($col)) {
- return $col;
- }
- if (!is_array($col) || count($col) == 0) {
- return 'NULL';
- }
- if ($type) {
- $this->loadModule('Datatype', null, true);
- return $this->datatype->implodeArray($col, $type);
- }
- return implode(', ', $col);
- }
-
- // }}}
- // {{{ function replace($table, $fields)
-
- /**
- * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT
- * query, except that if there is already a row in the table with the same
- * key field values, the REPLACE query just updates its values instead of
- * inserting a new row.
- *
- * The REPLACE type of query does not make part of the SQL standards. Since
- * practically only MySQL and SQLite implement it natively, this type of
- * query isemulated through this method for other DBMS using standard types
- * of queries inside a transaction to assure the atomicity of the operation.
- *
- * @param string name of the table on which the REPLACE query will
- * be executed.
- * @param array associative array that describes the fields and the
- * values that will be inserted or updated in the specified table. The
- * indexes of the array are the names of all the fields of the table.
- * The values of the array are also associative arrays that describe
- * the values and other properties of the table fields.
- *
- * Here follows a list of field properties that need to be specified:
- *
- * value
- * Value to be assigned to the specified field. This value may be
- * of specified in database independent type format as this
- * function can perform the necessary datatype conversions.
- *
- * Default: this property is required unless the Null property is
- * set to 1.
- *
- * type
- * Name of the type of the field. Currently, all types MDB2
- * are supported except for clob and blob.
- *
- * Default: no type conversion
- *
- * null
- * bool property that indicates that the value for this field
- * should be set to null.
- *
- * The default value for fields missing in INSERT queries may be
- * specified the definition of a table. Often, the default value
- * is already null, but since the REPLACE may be emulated using
- * an UPDATE query, make sure that all fields of the table are
- * listed in this function argument array.
- *
- * Default: 0
- *
- * key
- * bool property that indicates that this field should be
- * handled as a primary key or at least as part of the compound
- * unique index of the table that will determine the row that will
- * updated if it exists or inserted a new row otherwise.
- *
- * This function will fail if no key field is specified or if the
- * value of a key field is set to null because fields that are
- * part of unique index they may not be null.
- *
- * Default: 0
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function replace($table, $fields)
- {
- if (!$this->supports('replace')) {
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'replace query is not supported', __FUNCTION__);
- }
- $count = count($fields);
- $condition = $values = array();
- for ($colnum = 0, reset($fields); $colnum < $count; next($fields), $colnum++) {
- $name = key($fields);
- if (isset($fields[$name]['null']) && $fields[$name]['null']) {
- $value = 'NULL';
- } else {
- $type = isset($fields[$name]['type']) ? $fields[$name]['type'] : null;
- $value = $this->quote($fields[$name]['value'], $type);
- }
- $values[$name] = $value;
- if (isset($fields[$name]['key']) && $fields[$name]['key']) {
- if ($value === 'NULL') {
- return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
- 'key value '.$name.' may not be NULL', __FUNCTION__);
- }
- $condition[] = $name . '=' . $value;
- }
- }
- if (empty($condition)) {
- return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
- 'not specified which fields are keys', __FUNCTION__);
- }
-
- $result = null;
- $in_transaction = $this->in_transaction;
- if (!$in_transaction && PEAR::isError($result = $this->beginTransaction())) {
- return $result;
- }
-
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
-
- $condition = ' WHERE '.implode(' AND ', $condition);
- $query = "DELETE FROM $table$condition";
- $result =& $this->_doQuery($query, true, $connection);
- if (!PEAR::isError($result)) {
- $affected_rows = $this->_affectedRows($connection, $result);
- $insert = implode(', ', array_keys($values));
- $values = implode(', ', $values);
- $query = "INSERT INTO $table ($insert) VALUES ($values)";
- $result =& $this->_doQuery($query, true, $connection);
- if (!PEAR::isError($result)) {
- $affected_rows += $this->_affectedRows($connection, $result);;
- }
- }
-
- if (!$in_transaction) {
- if (PEAR::isError($result)) {
- $this->rollback();
- } else {
- $result = $this->commit();
- }
- }
-
- if (PEAR::isError($result)) {
- return $result;
- }
-
- return $affected_rows;
- }
-
- // }}}
- // {{{ function &prepare($query, $types = null, $result_types = null, $lobs = array())
-
- /**
- * Prepares a query for multiple execution with execute().
- * With some database backends, this is emulated.
- * prepare() requires a generic query as string like
- * 'INSERT INTO numbers VALUES(?,?)' or
- * 'INSERT INTO numbers VALUES(:foo,:bar)'.
- * The ? and :name and are placeholders which can be set using
- * bindParam() and the query can be sent off using the execute() method.
- * The allowed format for :name can be set with the 'bindname_format' option.
- *
- * @param string the query to prepare
- * @param mixed array that contains the types of the placeholders
- * @param mixed array that contains the types of the columns in
- * the result set or MDB2_PREPARE_RESULT, if set to
- * MDB2_PREPARE_MANIP the query is handled as a manipulation query
- * @param mixed key (field) value (parameter) pair for all lob placeholders
- *
- * @return mixed resource handle for the prepared query on success,
- * a MDB2 error on failure
- *
- * @access public
- * @see bindParam, execute
- */
- function &prepare($query, $types = null, $result_types = null, $lobs = array())
- {
- $is_manip = ($result_types === MDB2_PREPARE_MANIP);
- $offset = $this->offset;
- $limit = $this->limit;
- $this->offset = $this->limit = 0;
- $result = $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'pre'));
- if ($result) {
- if (PEAR::isError($result)) {
- return $result;
- }
- $query = $result;
- }
- $placeholder_type_guess = $placeholder_type = null;
- $question = '?';
- $colon = ':';
- $positions = array();
- $position = 0;
- $ignores = $this->sql_comments;
- $ignores[] = $this->string_quoting;
- $ignores[] = $this->identifier_quoting;
- while ($position < strlen($query)) {
- $q_position = strpos($query, $question, $position);
- $c_position = strpos($query, $colon, $position);
- if ($q_position && $c_position) {
- $p_position = min($q_position, $c_position);
- } elseif ($q_position) {
- $p_position = $q_position;
- } elseif ($c_position) {
- $p_position = $c_position;
- } else {
- break;
- }
- if (is_null($placeholder_type)) {
- $placeholder_type_guess = $query[$p_position];
- }
-
- $new_pos = $this->_skipDelimitedStrings($query, $position, $p_position);
- if (PEAR::isError($new_pos)) {
- return $new_pos;
- }
- if ($new_pos != $position) {
- $position = $new_pos;
- continue; //evaluate again starting from the new position
- }
-
- if ($query[$position] == $placeholder_type_guess) {
- if (is_null($placeholder_type)) {
- $placeholder_type = $query[$p_position];
- $question = $colon = $placeholder_type;
- if (!empty($types) && is_array($types)) {
- if ($placeholder_type == ':') {
- if (is_int(key($types))) {
- $types_tmp = $types;
- $types = array();
- $count = -1;
- }
- } else {
- $types = array_values($types);
- }
- }
- }
- if ($placeholder_type == ':') {
- $regexp = '/^.{'.($position+1).'}('.$this->options['bindname_format'].').*$/s';
- $parameter = preg_replace($regexp, '\\1', $query);
- if ($parameter === '') {
- $err =& $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
- 'named parameter name must match "bindname_format" option', __FUNCTION__);
- return $err;
- }
- $positions[$p_position] = $parameter;
- $query = substr_replace($query, '?', $position, strlen($parameter)+1);
- // use parameter name in type array
- if (isset($count) && isset($types_tmp[++$count])) {
- $types[$parameter] = $types_tmp[$count];
- }
- } else {
- $positions[$p_position] = count($positions);
- }
- $position = $p_position + 1;
- } else {
- $position = $p_position;
- }
- }
- $class_name = 'MDB2_Statement_'.$this->phptype;
- $statement = null;
- $obj = new $class_name($this, $statement, $positions, $query, $types, $result_types, $is_manip, $limit, $offset);
- $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'post', 'result' => $obj));
- return $obj;
- }
-
- // }}}
- // {{{ function _skipDelimitedStrings($query, $position, $p_position)
-
- /**
- * Utility method, used by prepare() to avoid replacing placeholders within delimited strings.
- * Check if the placeholder is contained within a delimited string.
- * If so, skip it and advance the position, otherwise return the current position,
- * which is valid
- *
- * @param string $query
- * @param integer $position current string cursor position
- * @param integer $p_position placeholder position
- *
- * @return mixed integer $new_position on success
- * MDB2_Error on failure
- *
- * @access protected
- */
- function _skipDelimitedStrings($query, $position, $p_position)
- {
- $ignores = $this->sql_comments;
- $ignores[] = $this->string_quoting;
- $ignores[] = $this->identifier_quoting;
-
- foreach ($ignores as $ignore) {
- if (!empty($ignore['start'])) {
- if (is_int($start_quote = strpos($query, $ignore['start'], $position)) && $start_quote < $p_position) {
- $end_quote = $start_quote;
- do {
- if (!is_int($end_quote = strpos($query, $ignore['end'], $end_quote + 1))) {
- if ($ignore['end'] === "\n") {
- $end_quote = strlen($query) - 1;
- } else {
- $err =& $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
- 'query with an unterminated text string specified', __FUNCTION__);
- return $err;
- }
- }
- } while ($ignore['escape'] && $query[($end_quote - 1)] == $ignore['escape']);
- $position = $end_quote + 1;
- return $position;
- }
- }
- }
- return $position;
- }
-
- // }}}
- // {{{ function quote($value, $type = null, $quote = true)
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string text string value that is intended to be converted.
- * @param string type to which the value should be converted to
- * @param bool quote
- * @param bool escape wildcards
- *
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- *
- * @access public
- */
- function quote($value, $type = null, $quote = true, $escape_wildcards = false)
- {
- $result = $this->loadModule('Datatype', null, true);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- return $this->datatype->quote($value, $type, $quote, $escape_wildcards);
- }
-
- // }}}
- // {{{ function getDeclaration($type, $name, $field)
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare
- * of the given type
- *
- * @param string type to which the value should be converted to
- * @param string name the field to be declared.
- * @param string definition of the field
- *
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- *
- * @access public
- */
- function getDeclaration($type, $name, $field)
- {
- $result = $this->loadModule('Datatype', null, true);
- if (PEAR::isError($result)) {
- return $result;
- }
- return $this->datatype->getDeclaration($type, $name, $field);
- }
-
- // }}}
- // {{{ function compareDefinition($current, $previous)
-
- /**
- * Obtain an array of changes that may need to applied
- *
- * @param array new definition
- * @param array old definition
- *
- * @return array containing all changes that will need to be applied
- *
- * @access public
- */
- function compareDefinition($current, $previous)
- {
- $result = $this->loadModule('Datatype', null, true);
- if (PEAR::isError($result)) {
- return $result;
- }
- return $this->datatype->compareDefinition($current, $previous);
- }
-
- // }}}
- // {{{ function supports($feature)
-
- /**
- * Tell whether a DB implementation or its backend extension
- * supports a given feature.
- *
- * @param string name of the feature (see the MDB2 class doc)
- *
- * @return bool|string if this DB implementation supports a given feature
- * false means no, true means native,
- * 'emulated' means emulated
- *
- * @access public
- */
- function supports($feature)
- {
- if (array_key_exists($feature, $this->supported)) {
- return $this->supported[$feature];
- }
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- "unknown support feature $feature", __FUNCTION__);
- }
-
- // }}}
- // {{{ function getSequenceName($sqn)
-
- /**
- * adds sequence name formatting to a sequence name
- *
- * @param string name of the sequence
- *
- * @return string formatted sequence name
- *
- * @access public
- */
- function getSequenceName($sqn)
- {
- return sprintf($this->options['seqname_format'],
- preg_replace('/[^a-z0-9_\$.]/i', '_', $sqn));
- }
-
- // }}}
- // {{{ function getIndexName($idx)
-
- /**
- * adds index name formatting to a index name
- *
- * @param string name of the index
- *
- * @return string formatted index name
- *
- * @access public
- */
- function getIndexName($idx)
- {
- return sprintf($this->options['idxname_format'],
- preg_replace('/[^a-z0-9_\$]/i', '_', $idx));
- }
-
- // }}}
- // {{{ function nextID($seq_name, $ondemand = true)
-
- /**
- * Returns the next free id of a sequence
- *
- * @param string name of the sequence
- * @param bool when true missing sequences are automatic created
- *
- * @return mixed MDB2 Error Object or id
- *
- * @access public
- */
- function nextID($seq_name, $ondemand = true)
- {
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ function lastInsertID($table = null, $field = null)
-
- /**
- * Returns the autoincrement ID if supported or $id or fetches the current
- * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
- *
- * @param string name of the table into which a new row was inserted
- * @param string name of the field into which a new row was inserted
- *
- * @return mixed MDB2 Error Object or id
- *
- * @access public
- */
- function lastInsertID($table = null, $field = null)
- {
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ function currID($seq_name)
-
- /**
- * Returns the current id of a sequence
- *
- * @param string name of the sequence
- *
- * @return mixed MDB2 Error Object or id
- *
- * @access public
- */
- function currID($seq_name)
- {
- $this->warnings[] = 'database does not support getting current
- sequence value, the sequence value was incremented';
- return $this->nextID($seq_name);
- }
-
- // }}}
- // {{{ function queryOne($query, $type = null, $colnum = 0)
-
- /**
- * Execute the specified query, fetch the value from the first column of
- * the first row of the result set and then frees
- * the result set.
- *
- * @param string the SELECT query statement to be executed.
- * @param string optional argument that specifies the expected
- * datatype of the result set field, so that an eventual conversion
- * may be performed. The default datatype is text, meaning that no
- * conversion is performed
- * @param int the column number to fetch
- *
- * @return mixed MDB2_OK or field value on success, a MDB2 error on failure
- *
- * @access public
- */
- function queryOne($query, $type = null, $colnum = 0)
- {
- $result = $this->query($query, $type);
- if (!MDB2::isResultCommon($result)) {
- return $result;
- }
-
- $one = $result->fetchOne($colnum);
- $result->free();
- return $one;
- }
-
- // }}}
- // {{{ function queryRow($query, $types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT)
-
- /**
- * Execute the specified query, fetch the values from the first
- * row of the result set into an array and then frees
- * the result set.
- *
- * @param string the SELECT query statement to be executed.
- * @param array optional array argument that specifies a list of
- * expected datatypes of the result set columns, so that the eventual
- * conversions may be performed. The default list of datatypes is
- * empty, meaning that no conversion is performed.
- * @param int how the array data should be indexed
- *
- * @return mixed MDB2_OK or data array on success, a MDB2 error on failure
- *
- * @access public
- */
- function queryRow($query, $types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT)
- {
- $result = $this->query($query, $types);
- if (!MDB2::isResultCommon($result)) {
- return $result;
- }
-
- $row = $result->fetchRow($fetchmode);
- $result->free();
- return $row;
- }
-
- // }}}
- // {{{ function queryCol($query, $type = null, $colnum = 0)
-
- /**
- * Execute the specified query, fetch the value from the first column of
- * each row of the result set into an array and then frees the result set.
- *
- * @param string the SELECT query statement to be executed.
- * @param string optional argument that specifies the expected
- * datatype of the result set field, so that an eventual conversion
- * may be performed. The default datatype is text, meaning that no
- * conversion is performed
- * @param int the row number to fetch
- *
- * @return mixed MDB2_OK or data array on success, a MDB2 error on failure
- *
- * @access public
- */
- function queryCol($query, $type = null, $colnum = 0)
- {
- $result = $this->query($query, $type);
- if (!MDB2::isResultCommon($result)) {
- return $result;
- }
-
- $col = $result->fetchCol($colnum);
- $result->free();
- return $col;
- }
-
- // }}}
- // {{{ function queryAll($query, $types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT, $rekey = false, $force_array = false, $group = false)
-
- /**
- * Execute the specified query, fetch all the rows of the result set into
- * a two dimensional array and then frees the result set.
- *
- * @param string the SELECT query statement to be executed.
- * @param array optional array argument that specifies a list of
- * expected datatypes of the result set columns, so that the eventual
- * conversions may be performed. The default list of datatypes is
- * empty, meaning that no conversion is performed.
- * @param int how the array data should be indexed
- * @param bool if set to true, the $all will have the first
- * column as its first dimension
- * @param bool used only when the query returns exactly
- * two columns. If true, the values of the returned array will be
- * one-element arrays instead of scalars.
- * @param bool if true, the values of the returned array is
- * wrapped in another array. If the same key value (in the first
- * column) repeats itself, the values will be appended to this array
- * instead of overwriting the existing values.
- *
- * @return mixed MDB2_OK or data array on success, a MDB2 error on failure
- *
- * @access public
- */
- function queryAll($query, $types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT,
- $rekey = false, $force_array = false, $group = false)
- {
- $result = $this->query($query, $types);
- if (!MDB2::isResultCommon($result)) {
- return $result;
- }
-
- $all = $result->fetchAll($fetchmode, $rekey, $force_array, $group);
- $result->free();
- return $all;
- }
-
- // }}}
-}
-
-// }}}
-// {{{ class MDB2_Result
-
-/**
- * The dummy class that all user space result classes should extend from
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Result
-{
-}
-
-// }}}
-// {{{ class MDB2_Result_Common extends MDB2_Result
-
-/**
- * The common result class for MDB2 result objects
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Result_Common extends MDB2_Result
-{
- // {{{ Variables (Properties)
-
- var $db;
- var $result;
- var $rownum = -1;
- var $types = array();
- var $values = array();
- var $offset;
- var $offset_count = 0;
- var $limit;
- var $column_names;
-
- // }}}
- // {{{ constructor: function __construct(&$db, &$result, $limit = 0, $offset = 0)
-
- /**
- * Constructor
- */
- function __construct(&$db, &$result, $limit = 0, $offset = 0)
- {
- $this->db =& $db;
- $this->result =& $result;
- $this->offset = $offset;
- $this->limit = max(0, $limit - 1);
- }
-
- // }}}
- // {{{ function MDB2_Result_Common(&$db, &$result, $limit = 0, $offset = 0)
-
- /**
- * PHP 4 Constructor
- */
- function MDB2_Result_Common(&$db, &$result, $limit = 0, $offset = 0)
- {
- $this->__construct($db, $result, $limit, $offset);
- }
-
- // }}}
- // {{{ function setResultTypes($types)
-
- /**
- * Define the list of types to be associated with the columns of a given
- * result set.
- *
- * This function may be called before invoking fetchRow(), fetchOne(),
- * fetchCol() and fetchAll() so that the necessary data type
- * conversions are performed on the data to be retrieved by them. If this
- * function is not called, the type of all result set columns is assumed
- * to be text, thus leading to not perform any conversions.
- *
- * @param array variable that lists the
- * data types to be expected in the result set columns. If this array
- * contains less types than the number of columns that are returned
- * in the result set, the remaining columns are assumed to be of the
- * type text. Currently, the types clob and blob are not fully
- * supported.
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function setResultTypes($types)
- {
- $load = $this->db->loadModule('Datatype', null, true);
- if (PEAR::isError($load)) {
- return $load;
- }
- $types = $this->db->datatype->checkResultTypes($types);
- if (PEAR::isError($types)) {
- return $types;
- }
- $this->types = $types;
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function seek($rownum = 0)
-
- /**
- * Seek to a specific row in a result set
- *
- * @param int number of the row where the data can be found
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function seek($rownum = 0)
- {
- $target_rownum = $rownum - 1;
- if ($this->rownum > $target_rownum) {
- return $this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'seeking to previous rows not implemented', __FUNCTION__);
- }
- while ($this->rownum < $target_rownum) {
- $this->fetchRow();
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
-
- /**
- * Fetch and return a row of data
- *
- * @param int how the array data should be indexed
- * @param int number of the row where the data can be found
- *
- * @return int data array on success, a MDB2 error on failure
- *
- * @access public
- */
- function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
- {
- $err =& $this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- return $err;
- }
-
- // }}}
- // {{{ function fetchOne($colnum = 0)
-
- /**
- * fetch single column from the next row from a result set
- *
- * @param int the column number to fetch
- * @param int number of the row where the data can be found
- *
- * @return string data on success, a MDB2 error on failure
- *
- * @access public
- */
- function fetchOne($colnum = 0, $rownum = null)
- {
- $fetchmode = is_numeric($colnum) ? MDB2_FETCHMODE_ORDERED : MDB2_FETCHMODE_ASSOC;
- $row = $this->fetchRow($fetchmode, $rownum);
- if (!is_array($row) || PEAR::isError($row)) {
- return $row;
- }
- if (!array_key_exists($colnum, $row)) {
- return $this->db->raiseError(MDB2_ERROR_TRUNCATED, null, null,
- 'column is not defined in the result set: '.$colnum, __FUNCTION__);
- }
- return $row[$colnum];
- }
-
- // }}}
- // {{{ function fetchCol($colnum = 0)
-
- /**
- * Fetch and return a column from the current row pointer position
- *
- * @param int the column number to fetch
- *
- * @return mixed data array on success, a MDB2 error on failure
- *
- * @access public
- */
- function fetchCol($colnum = 0)
- {
- $column = array();
- $fetchmode = is_numeric($colnum) ? MDB2_FETCHMODE_ORDERED : MDB2_FETCHMODE_ASSOC;
- $row = $this->fetchRow($fetchmode);
- if (is_array($row)) {
- if (!array_key_exists($colnum, $row)) {
- return $this->db->raiseError(MDB2_ERROR_TRUNCATED, null, null,
- 'column is not defined in the result set: '.$colnum, __FUNCTION__);
- }
- do {
- $column[] = $row[$colnum];
- } while (is_array($row = $this->fetchRow($fetchmode)));
- }
- if (PEAR::isError($row)) {
- return $row;
- }
- return $column;
- }
-
- // }}}
- // {{{ function fetchAll($fetchmode = MDB2_FETCHMODE_DEFAULT, $rekey = false, $force_array = false, $group = false)
-
- /**
- * Fetch and return all rows from the current row pointer position
- *
- * @param int $fetchmode the fetch mode to use:
- * + MDB2_FETCHMODE_ORDERED
- * + MDB2_FETCHMODE_ASSOC
- * + MDB2_FETCHMODE_ORDERED | MDB2_FETCHMODE_FLIPPED
- * + MDB2_FETCHMODE_ASSOC | MDB2_FETCHMODE_FLIPPED
- * @param bool if set to true, the $all will have the first
- * column as its first dimension
- * @param bool used only when the query returns exactly
- * two columns. If true, the values of the returned array will be
- * one-element arrays instead of scalars.
- * @param bool if true, the values of the returned array is
- * wrapped in another array. If the same key value (in the first
- * column) repeats itself, the values will be appended to this array
- * instead of overwriting the existing values.
- *
- * @return mixed data array on success, a MDB2 error on failure
- *
- * @access public
- * @see getAssoc()
- */
- function fetchAll($fetchmode = MDB2_FETCHMODE_DEFAULT, $rekey = false,
- $force_array = false, $group = false)
- {
- $all = array();
- $row = $this->fetchRow($fetchmode);
- if (PEAR::isError($row)) {
- return $row;
- } elseif (!$row) {
- return $all;
- }
-
- $shift_array = $rekey ? false : null;
- if (!is_null($shift_array)) {
- if (is_object($row)) {
- $colnum = count(get_object_vars($row));
- } else {
- $colnum = count($row);
- }
- if ($colnum < 2) {
- return $this->db->raiseError(MDB2_ERROR_TRUNCATED, null, null,
- 'rekey feature requires atleast 2 column', __FUNCTION__);
- }
- $shift_array = (!$force_array && $colnum == 2);
- }
-
- if ($rekey) {
- do {
- if (is_object($row)) {
- $arr = get_object_vars($row);
- $key = reset($arr);
- unset($row->{$key});
- } else {
- if ($fetchmode & MDB2_FETCHMODE_ASSOC) {
- $key = reset($row);
- unset($row[key($row)]);
- } else {
- $key = array_shift($row);
- }
- if ($shift_array) {
- $row = array_shift($row);
- }
- }
- if ($group) {
- $all[$key][] = $row;
- } else {
- $all[$key] = $row;
- }
- } while (($row = $this->fetchRow($fetchmode)));
- } elseif ($fetchmode & MDB2_FETCHMODE_FLIPPED) {
- do {
- foreach ($row as $key => $val) {
- $all[$key][] = $val;
- }
- } while (($row = $this->fetchRow($fetchmode)));
- } else {
- do {
- $all[] = $row;
- } while (($row = $this->fetchRow($fetchmode)));
- }
-
- return $all;
- }
-
- // }}}
- // {{{ function rowCount()
- /**
- * Returns the actual row number that was last fetched (count from 0)
- * @return int
- *
- * @access public
- */
- function rowCount()
- {
- return $this->rownum + 1;
- }
-
- // }}}
- // {{{ function numRows()
-
- /**
- * Returns the number of rows in a result object
- *
- * @return mixed MDB2 Error Object or the number of rows
- *
- * @access public
- */
- function numRows()
- {
- return $this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ function nextResult()
-
- /**
- * Move the internal result pointer to the next available result
- *
- * @return true on success, false if there is no more result set or an error object on failure
- *
- * @access public
- */
- function nextResult()
- {
- return $this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ function getColumnNames()
-
- /**
- * Retrieve the names of columns returned by the DBMS in a query result or
- * from the cache.
- *
- * @param bool If set to true the values are the column names,
- * otherwise the names of the columns are the keys.
- * @return mixed Array variable that holds the names of columns or an
- * MDB2 error on failure.
- * Some DBMS may not return any columns when the result set
- * does not contain any rows.
- *
- * @access public
- */
- function getColumnNames($flip = false)
- {
- if (!isset($this->column_names)) {
- $result = $this->_getColumnNames();
- if (PEAR::isError($result)) {
- return $result;
- }
- $this->column_names = $result;
- }
- if ($flip) {
- return array_flip($this->column_names);
- }
- return $this->column_names;
- }
-
- // }}}
- // {{{ function _getColumnNames()
-
- /**
- * Retrieve the names of columns returned by the DBMS in a query result.
- *
- * @return mixed Array variable that holds the names of columns as keys
- * or an MDB2 error on failure.
- * Some DBMS may not return any columns when the result set
- * does not contain any rows.
- *
- * @access private
- */
- function _getColumnNames()
- {
- return $this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ function numCols()
-
- /**
- * Count the number of columns returned by the DBMS in a query result.
- *
- * @return mixed integer value with the number of columns, a MDB2 error
- * on failure
- *
- * @access public
- */
- function numCols()
- {
- return $this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ function getResource()
-
- /**
- * return the resource associated with the result object
- *
- * @return resource
- *
- * @access public
- */
- function getResource()
- {
- return $this->result;
- }
-
- // }}}
- // {{{ function bindColumn($column, &$value, $type = null)
-
- /**
- * Set bind variable to a column.
- *
- * @param int column number or name
- * @param mixed variable reference
- * @param string specifies the type of the field
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function bindColumn($column, &$value, $type = null)
- {
- if (!is_numeric($column)) {
- $column_names = $this->getColumnNames();
- if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- if ($this->db->options['field_case'] == CASE_LOWER) {
- $column = strtolower($column);
- } else {
- $column = strtoupper($column);
- }
- }
- $column = $column_names[$column];
- }
- $this->values[$column] =& $value;
- if (!is_null($type)) {
- $this->types[$column] = $type;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function _assignBindColumns($row)
-
- /**
- * Bind a variable to a value in the result row.
- *
- * @param array row data
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access private
- */
- function _assignBindColumns($row)
- {
- $row = array_values($row);
- foreach ($row as $column => $value) {
- if (array_key_exists($column, $this->values)) {
- $this->values[$column] = $value;
- }
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function free()
-
- /**
- * Free the internal resources associated with result.
- *
- * @return bool true on success, false if result is invalid
- *
- * @access public
- */
- function free()
- {
- $this->result = false;
- return MDB2_OK;
- }
-
- // }}}
-}
-
-// }}}
-// {{{ class MDB2_Row
-
-/**
- * The simple class that accepts row data as an array
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Row
-{
- // {{{ constructor: function __construct(&$row)
-
- /**
- * constructor
- *
- * @param resource row data as array
- */
- function __construct(&$row)
- {
- foreach ($row as $key => $value) {
- $this->$key = &$row[$key];
- }
- }
-
- // }}}
- // {{{ function MDB2_Row(&$row)
-
- /**
- * PHP 4 Constructor
- *
- * @param resource row data as array
- */
- function MDB2_Row(&$row)
- {
- $this->__construct($row);
- }
-
- // }}}
-}
-
-// }}}
-// {{{ class MDB2_Statement_Common
-
-/**
- * The common statement class for MDB2 statement objects
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Statement_Common
-{
- // {{{ Variables (Properties)
-
- var $db;
- var $statement;
- var $query;
- var $result_types;
- var $types;
- var $values = array();
- var $limit;
- var $offset;
- var $is_manip;
-
- // }}}
- // {{{ constructor: function __construct(&$db, &$statement, $positions, $query, $types, $result_types, $is_manip = false, $limit = null, $offset = null)
-
- /**
- * Constructor
- */
- function __construct(&$db, &$statement, $positions, $query, $types, $result_types, $is_manip = false, $limit = null, $offset = null)
- {
- $this->db =& $db;
- $this->statement =& $statement;
- $this->positions = $positions;
- $this->query = $query;
- $this->types = (array)$types;
- $this->result_types = (array)$result_types;
- $this->limit = $limit;
- $this->is_manip = $is_manip;
- $this->offset = $offset;
- }
-
- // }}}
- // {{{ function MDB2_Statement_Common(&$db, &$statement, $positions, $query, $types, $result_types, $is_manip = false, $limit = null, $offset = null)
-
- /**
- * PHP 4 Constructor
- */
- function MDB2_Statement_Common(&$db, &$statement, $positions, $query, $types, $result_types, $is_manip = false, $limit = null, $offset = null)
- {
- $this->__construct($db, $statement, $positions, $query, $types, $result_types, $is_manip, $limit, $offset);
- }
-
- // }}}
- // {{{ function bindValue($parameter, &$value, $type = null)
-
- /**
- * Set the value of a parameter of a prepared query.
- *
- * @param int the order number of the parameter in the query
- * statement. The order number of the first parameter is 1.
- * @param mixed value that is meant to be assigned to specified
- * parameter. The type of the value depends on the $type argument.
- * @param string specifies the type of the field
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function bindValue($parameter, $value, $type = null)
- {
- if (!is_numeric($parameter)) {
- $parameter = preg_replace('/^:(.*)$/', '\\1', $parameter);
- }
- if (!in_array($parameter, $this->positions)) {
- return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
- }
- $this->values[$parameter] = $value;
- if (!is_null($type)) {
- $this->types[$parameter] = $type;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function bindValueArray($values, $types = null)
-
- /**
- * Set the values of multiple a parameter of a prepared query in bulk.
- *
- * @param array specifies all necessary information
- * for bindValue() the array elements must use keys corresponding to
- * the number of the position of the parameter.
- * @param array specifies the types of the fields
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- * @see bindParam()
- */
- function bindValueArray($values, $types = null)
- {
- $types = is_array($types) ? array_values($types) : array_fill(0, count($values), null);
- $parameters = array_keys($values);
- foreach ($parameters as $key => $parameter) {
- $this->db->expectError(MDB2_ERROR_NOT_FOUND);
- $err = $this->bindValue($parameter, $values[$parameter], $types[$key]);
- $this->db->popExpect();
- if (PEAR::isError($err)) {
- if ($err->getCode() == MDB2_ERROR_NOT_FOUND) {
- //ignore (extra value for missing placeholder)
- continue;
- }
- return $err;
- }
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function bindParam($parameter, &$value, $type = null)
-
- /**
- * Bind a variable to a parameter of a prepared query.
- *
- * @param int the order number of the parameter in the query
- * statement. The order number of the first parameter is 1.
- * @param mixed variable that is meant to be bound to specified
- * parameter. The type of the value depends on the $type argument.
- * @param string specifies the type of the field
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function bindParam($parameter, &$value, $type = null)
- {
- if (!is_numeric($parameter)) {
- $parameter = preg_replace('/^:(.*)$/', '\\1', $parameter);
- }
- if (!in_array($parameter, $this->positions)) {
- return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
- }
- $this->values[$parameter] =& $value;
- if (!is_null($type)) {
- $this->types[$parameter] = $type;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function bindParamArray(&$values, $types = null)
-
- /**
- * Bind the variables of multiple a parameter of a prepared query in bulk.
- *
- * @param array specifies all necessary information
- * for bindParam() the array elements must use keys corresponding to
- * the number of the position of the parameter.
- * @param array specifies the types of the fields
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- * @see bindParam()
- */
- function bindParamArray(&$values, $types = null)
- {
- $types = is_array($types) ? array_values($types) : array_fill(0, count($values), null);
- $parameters = array_keys($values);
- foreach ($parameters as $key => $parameter) {
- $err = $this->bindParam($parameter, $values[$parameter], $types[$key]);
- if (PEAR::isError($err)) {
- return $err;
- }
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function &execute($values = null, $result_class = true, $result_wrap_class = false)
-
- /**
- * Execute a prepared query statement.
- *
- * @param array specifies all necessary information
- * for bindParam() the array elements must use keys corresponding to
- * the number of the position of the parameter.
- * @param mixed specifies which result class to use
- * @param mixed specifies which class to wrap results in
- *
- * @return mixed a result handle or MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function &execute($values = null, $result_class = true, $result_wrap_class = false)
- {
- if (is_null($this->positions)) {
- return $this->db->raiseError(MDB2_ERROR, null, null,
- 'Prepared statement has already been freed', __FUNCTION__);
- }
-
- $values = (array)$values;
- if (!empty($values)) {
- $err = $this->bindValueArray($values);
- if (PEAR::isError($err)) {
- return $this->db->raiseError(MDB2_ERROR, null, null,
- 'Binding Values failed with message: ' . $err->getMessage(), __FUNCTION__);
- }
- }
- $result =& $this->_execute($result_class, $result_wrap_class);
- return $result;
- }
-
- // }}}
- // {{{ function &_execute($result_class = true, $result_wrap_class = false)
-
- /**
- * Execute a prepared query statement helper method.
- *
- * @param mixed specifies which result class to use
- * @param mixed specifies which class to wrap results in
- *
- * @return mixed MDB2_Result or integer on success, a MDB2 error on failure
- *
- * @access private
- */
- function &_execute($result_class = true, $result_wrap_class = false)
- {
- $this->last_query = $this->query;
- $query = '';
- $last_position = 0;
- foreach ($this->positions as $current_position => $parameter) {
- if (!array_key_exists($parameter, $this->values)) {
- return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
- }
- $value = $this->values[$parameter];
- $query.= substr($this->query, $last_position, $current_position - $last_position);
- if (!isset($value)) {
- $value_quoted = 'NULL';
- } else {
- $type = !empty($this->types[$parameter]) ? $this->types[$parameter] : null;
- $value_quoted = $this->db->quote($value, $type);
- if (PEAR::isError($value_quoted)) {
- return $value_quoted;
- }
- }
- $query.= $value_quoted;
- $last_position = $current_position + 1;
- }
- $query.= substr($this->query, $last_position);
-
- $this->db->offset = $this->offset;
- $this->db->limit = $this->limit;
- if ($this->is_manip) {
- $result = $this->db->exec($query);
- } else {
- $result =& $this->db->query($query, $this->result_types, $result_class, $result_wrap_class);
- }
- return $result;
- }
-
- // }}}
- // {{{ function free()
-
- /**
- * Release resources allocated for the specified prepared query.
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function free()
- {
- if (is_null($this->positions)) {
- return $this->db->raiseError(MDB2_ERROR, null, null,
- 'Prepared statement has already been freed', __FUNCTION__);
- }
-
- $this->statement = null;
- $this->positions = null;
- $this->query = null;
- $this->types = null;
- $this->result_types = null;
- $this->limit = null;
- $this->is_manip = null;
- $this->offset = null;
- $this->values = null;
-
- return MDB2_OK;
- }
-
- // }}}
-}
-
-// }}}
-// {{{ class MDB2_Module_Common
-
-/**
- * The common modules class for MDB2 module objects
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Module_Common
-{
- // {{{ Variables (Properties)
-
- /**
- * contains the key to the global MDB2 instance array of the associated
- * MDB2 instance
- *
- * @var int
- * @access protected
- */
- var $db_index;
-
- // }}}
- // {{{ constructor: function __construct($db_index)
-
- /**
- * Constructor
- */
- function __construct($db_index)
- {
- $this->db_index = $db_index;
- }
-
- // }}}
- // {{{ function MDB2_Module_Common($db_index)
-
- /**
- * PHP 4 Constructor
- */
- function MDB2_Module_Common($db_index)
- {
- $this->__construct($db_index);
- }
-
- // }}}
- // {{{ function &getDBInstance()
-
- /**
- * Get the instance of MDB2 associated with the module instance
- *
- * @return object MDB2 instance or a MDB2 error on failure
- *
- * @access public
- */
- function &getDBInstance()
- {
- if (isset($GLOBALS['_MDB2_databases'][$this->db_index])) {
- $result =& $GLOBALS['_MDB2_databases'][$this->db_index];
- } else {
- $result =& MDB2::raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'could not find MDB2 instance');
- }
- return $result;
- }
-
- // }}}
-}
-
-// }}}
-// {{{ function MDB2_closeOpenTransactions()
-
-/**
- * Close any open transactions form persistent connections
- *
- * @return void
- *
- * @access public
- */
-
-function MDB2_closeOpenTransactions()
-{
- reset($GLOBALS['_MDB2_databases']);
- while (next($GLOBALS['_MDB2_databases'])) {
- $key = key($GLOBALS['_MDB2_databases']);
- if ($GLOBALS['_MDB2_databases'][$key]->opened_persistent
- && $GLOBALS['_MDB2_databases'][$key]->in_transaction
- ) {
- $GLOBALS['_MDB2_databases'][$key]->rollback();
- }
- }
-}
-
-// }}}
-// {{{ function MDB2_defaultDebugOutput(&$db, $scope, $message, $is_manip = null)
-
-/**
- * default debug output handler
- *
- * @param object reference to an MDB2 database object
- * @param string usually the method name that triggered the debug call:
- * for example 'query', 'prepare', 'execute', 'parameters',
- * 'beginTransaction', 'commit', 'rollback'
- * @param string message that should be appended to the debug variable
- * @param array contains context information about the debug() call
- * common keys are: is_manip, time, result etc.
- *
- * @return void|string optionally return a modified message, this allows
- * rewriting a query before being issued or prepared
- *
- * @access public
- */
-function MDB2_defaultDebugOutput(&$db, $scope, $message, $context = array())
-{
- $db->debug_output.= $scope.'('.$db->db_index.'): ';
- $db->debug_output.= $message.$db->getOption('log_line_break');
- return $message;
-}
-
-// }}}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2006 Manuel Lemos, Tomas V.V.Cox, |
-// | Stig. S. Bakken, Lukas Smith |
-// | All rights reserved. |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
-// | API as well as database abstraction for PHP applications. |
-// | This LICENSE is in the BSD license style. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | |
-// | Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution. |
-// | |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
-// | POSSIBILITY OF SUCH DAMAGE. |
-// +----------------------------------------------------------------------+
-// | Author: Lukas Smith <smith@pooteeweet.org> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Date.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
-//
-
-/**
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-
-/**
- * Several methods to convert the MDB2 native timestamp format (ISO based)
- * to and from data structures that are convenient to worth with in side of php.
- * For more complex date arithmetic please take a look at the Date package in PEAR
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Date
-{
- // {{{ mdbNow()
-
- /**
- * return the current datetime
- *
- * @return string current datetime in the MDB2 format
- * @access public
- */
- function mdbNow()
- {
- return date('Y-m-d H:i:s');
- }
- // }}}
-
- // {{{ mdbToday()
-
- /**
- * return the current date
- *
- * @return string current date in the MDB2 format
- * @access public
- */
- function mdbToday()
- {
- return date('Y-m-d');
- }
- // }}}
-
- // {{{ mdbTime()
-
- /**
- * return the current time
- *
- * @return string current time in the MDB2 format
- * @access public
- */
- function mdbTime()
- {
- return date('H:i:s');
- }
- // }}}
-
- // {{{ date2Mdbstamp()
-
- /**
- * convert a date into a MDB2 timestamp
- *
- * @param int hour of the date
- * @param int minute of the date
- * @param int second of the date
- * @param int month of the date
- * @param int day of the date
- * @param int year of the date
- *
- * @return string a valid MDB2 timestamp
- * @access public
- */
- function date2Mdbstamp($hour = null, $minute = null, $second = null,
- $month = null, $day = null, $year = null)
- {
- return MDB2_Date::unix2Mdbstamp(mktime($hour, $minute, $second, $month, $day, $year, -1));
- }
- // }}}
-
- // {{{ unix2Mdbstamp()
-
- /**
- * convert a unix timestamp into a MDB2 timestamp
- *
- * @param int a valid unix timestamp
- *
- * @return string a valid MDB2 timestamp
- * @access public
- */
- function unix2Mdbstamp($unix_timestamp)
- {
- return date('Y-m-d H:i:s', $unix_timestamp);
- }
- // }}}
-
- // {{{ mdbstamp2Unix()
-
- /**
- * convert a MDB2 timestamp into a unix timestamp
- *
- * @param int a valid MDB2 timestamp
- * @return string unix timestamp with the time stored in the MDB2 format
- *
- * @access public
- */
- function mdbstamp2Unix($mdb_timestamp)
- {
- $arr = MDB2_Date::mdbstamp2Date($mdb_timestamp);
-
- return mktime($arr['hour'], $arr['minute'], $arr['second'], $arr['month'], $arr['day'], $arr['year'], -1);
- }
- // }}}
-
- // {{{ mdbstamp2Date()
-
- /**
- * convert a MDB2 timestamp into an array containing all
- * values necessary to pass to php's date() function
- *
- * @param int a valid MDB2 timestamp
- *
- * @return array with the time split
- * @access public
- */
- function mdbstamp2Date($mdb_timestamp)
- {
- list($arr['year'], $arr['month'], $arr['day'], $arr['hour'], $arr['minute'], $arr['second']) =
- sscanf($mdb_timestamp, "%04u-%02u-%02u %02u:%02u:%02u");
- return $arr;
- }
- // }}}
-}
-
-?>
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2007 Manuel Lemos, Tomas V.V.Cox, |
-// | Stig. S. Bakken, Lukas Smith |
-// | All rights reserved. |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
-// | API as well as database abstraction for PHP applications. |
-// | This LICENSE is in the BSD license style. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | |
-// | Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution. |
-// | |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
-// | POSSIBILITY OF SUCH DAMAGE. |
-// +----------------------------------------------------------------------+
-// | Author: Lukas Smith <smith@pooteeweet.org> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Common.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
-
-require_once 'MDB2/LOB.php';
-
-/**
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-
-/**
- * MDB2_Driver_Common: Base class that is extended by each MDB2 driver
- *
- * To load this module in the MDB2 object:
- * $mdb->loadModule('Datatype');
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Driver_Datatype_Common extends MDB2_Module_Common
-{
- var $valid_default_values = array(
- 'text' => '',
- 'boolean' => true,
- 'integer' => 0,
- 'decimal' => 0.0,
- 'float' => 0.0,
- 'timestamp' => '1970-01-01 00:00:00',
- 'time' => '00:00:00',
- 'date' => '1970-01-01',
- 'clob' => '',
- 'blob' => '',
- );
-
- /**
- * contains all LOB objects created with this MDB2 instance
- * @var array
- * @access protected
- */
- var $lobs = array();
-
- // }}}
- // {{{ getValidTypes()
-
- /**
- * Get the list of valid types
- *
- * This function returns an array of valid types as keys with the values
- * being possible default values for all native datatypes and mapped types
- * for custom datatypes.
- *
- * @return mixed array on success, a MDB2 error on failure
- * @access public
- */
- function getValidTypes()
- {
- $types = $this->valid_default_values;
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- if (!empty($db->options['datatype_map'])) {
- foreach ($db->options['datatype_map'] as $type => $mapped_type) {
- if (array_key_exists($mapped_type, $types)) {
- $types[$type] = $types[$mapped_type];
- } elseif (!empty($db->options['datatype_map_callback'][$type])) {
- $parameter = array('type' => $type, 'mapped_type' => $mapped_type);
- $default = call_user_func_array($db->options['datatype_map_callback'][$type], array(&$db, __FUNCTION__, $parameter));
- $types[$type] = $default;
- }
- }
- }
- return $types;
- }
-
- // }}}
- // {{{ checkResultTypes()
-
- /**
- * Define the list of types to be associated with the columns of a given
- * result set.
- *
- * This function may be called before invoking fetchRow(), fetchOne()
- * fetchCole() and fetchAll() so that the necessary data type
- * conversions are performed on the data to be retrieved by them. If this
- * function is not called, the type of all result set columns is assumed
- * to be text, thus leading to not perform any conversions.
- *
- * @param array $types array variable that lists the
- * data types to be expected in the result set columns. If this array
- * contains less types than the number of columns that are returned
- * in the result set, the remaining columns are assumed to be of the
- * type text. Currently, the types clob and blob are not fully
- * supported.
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function checkResultTypes($types)
- {
- $types = is_array($types) ? $types : array($types);
- foreach ($types as $key => $type) {
- if (!isset($this->valid_default_values[$type])) {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- if (empty($db->options['datatype_map'][$type])) {
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- $type.' for '.$key.' is not a supported column type', __FUNCTION__);
- }
- }
- }
- return $types;
- }
-
- // }}}
- // {{{ _baseConvertResult()
-
- /**
- * General type conversion method
- *
- * @param mixed $value reference to a value to be converted
- * @param string $type specifies which type to convert to
- * @param boolean $rtrim [optional] when TRUE [default], apply rtrim() to text
- * @return object an MDB2 error on failure
- * @access protected
- */
- function _baseConvertResult($value, $type, $rtrim = true)
- {
- switch ($type) {
- case 'text':
- if ($rtrim) {
- $value = rtrim($value);
- }
- return $value;
- case 'integer':
- return intval($value);
- case 'boolean':
- return !empty($value);
- case 'decimal':
- return $value;
- case 'float':
- return doubleval($value);
- case 'date':
- return $value;
- case 'time':
- return $value;
- case 'timestamp':
- return $value;
- case 'clob':
- case 'blob':
- $this->lobs[] = array(
- 'buffer' => null,
- 'position' => 0,
- 'lob_index' => null,
- 'endOfLOB' => false,
- 'resource' => $value,
- 'value' => null,
- 'loaded' => false,
- );
- end($this->lobs);
- $lob_index = key($this->lobs);
- $this->lobs[$lob_index]['lob_index'] = $lob_index;
- return fopen('MDB2LOB://'.$lob_index.'@'.$this->db_index, 'r+');
- }
-
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_INVALID, null, null,
- 'attempt to convert result value to an unknown type :' . $type, __FUNCTION__);
- }
-
- // }}}
- // {{{ convertResult()
-
- /**
- * Convert a value to a RDBMS indipendent MDB2 type
- *
- * @param mixed $value value to be converted
- * @param string $type specifies which type to convert to
- * @param boolean $rtrim [optional] when TRUE [default], apply rtrim() to text
- * @return mixed converted value
- * @access public
- */
- function convertResult($value, $type, $rtrim = true)
- {
- if (is_null($value)) {
- return null;
- }
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- if (!empty($db->options['datatype_map'][$type])) {
- $type = $db->options['datatype_map'][$type];
- if (!empty($db->options['datatype_map_callback'][$type])) {
- $parameter = array('type' => $type, 'value' => $value, 'rtrim' => $rtrim);
- return call_user_func_array($db->options['datatype_map_callback'][$type], array(&$db, __FUNCTION__, $parameter));
- }
- }
- return $this->_baseConvertResult($value, $type, $rtrim);
- }
-
- // }}}
- // {{{ convertResultRow()
-
- /**
- * Convert a result row
- *
- * @param array $types
- * @param array $row specifies the types to convert to
- * @param boolean $rtrim [optional] when TRUE [default], apply rtrim() to text
- * @return mixed MDB2_OK on success, an MDB2 error on failure
- * @access public
- */
- function convertResultRow($types, $row, $rtrim = true)
- {
- $types = $this->_sortResultFieldTypes(array_keys($row), $types);
- foreach ($row as $key => $value) {
- if (empty($types[$key])) {
- continue;
- }
- $value = $this->convertResult($row[$key], $types[$key], $rtrim);
- if (PEAR::isError($value)) {
- return $value;
- }
- $row[$key] = $value;
- }
- return $row;
- }
-
- // }}}
- // {{{ _sortResultFieldTypes()
-
- /**
- * convert a result row
- *
- * @param array $types
- * @param array $row specifies the types to convert to
- * @param bool $rtrim if to rtrim text values or not
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function _sortResultFieldTypes($columns, $types)
- {
- $n_cols = count($columns);
- $n_types = count($types);
- if ($n_cols > $n_types) {
- for ($i= $n_cols - $n_types; $i >= 0; $i--) {
- $types[] = null;
- }
- }
- $sorted_types = array();
- foreach ($columns as $col) {
- $sorted_types[$col] = null;
- }
- foreach ($types as $name => $type) {
- if (array_key_exists($name, $sorted_types)) {
- $sorted_types[$name] = $type;
- unset($types[$name]);
- }
- }
- // if there are left types in the array, fill the null values of the
- // sorted array with them, in order.
- if (count($types)) {
- reset($types);
- foreach (array_keys($sorted_types) as $k) {
- if (is_null($sorted_types[$k])) {
- $sorted_types[$k] = current($types);
- next($types);
- }
- }
- }
- return $sorted_types;
- }
-
- // }}}
- // {{{ getDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare
- * of the given type
- *
- * @param string $type type to which the value should be converted to
- * @param string $name name the field to be declared.
- * @param string $field definition of the field
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access public
- */
- function getDeclaration($type, $name, $field)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if (!empty($db->options['datatype_map'][$type])) {
- $type = $db->options['datatype_map'][$type];
- if (!empty($db->options['datatype_map_callback'][$type])) {
- $parameter = array('type' => $type, 'name' => $name, 'field' => $field);
- return call_user_func_array($db->options['datatype_map_callback'][$type], array(&$db, __FUNCTION__, $parameter));
- }
- $field['type'] = $type;
- }
-
- if (!method_exists($this, "_get{$type}Declaration")) {
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'type not defined: '.$type, __FUNCTION__);
- }
- return $this->{"_get{$type}Declaration"}($name, $field);
- }
-
- // }}}
- // {{{ getTypeDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare an text type
- * field to be used in statements like CREATE TABLE.
- *
- * @param array $field associative array with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * length
- * Integer value that determines the maximum length of the text
- * field. If this argument is missing the field should be
- * declared to have the longest length allowed by the DBMS.
- *
- * default
- * Text value to be used as default for this field.
- *
- * notnull
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access public
- */
- function getTypeDeclaration($field)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- switch ($field['type']) {
- case 'text':
- $length = !empty($field['length']) ? $field['length'] : $db->options['default_text_field_length'];
- $fixed = !empty($field['fixed']) ? $field['fixed'] : false;
- return $fixed ? ($length ? 'CHAR('.$length.')' : 'CHAR('.$db->options['default_text_field_length'].')')
- : ($length ? 'VARCHAR('.$length.')' : 'TEXT');
- case 'clob':
- return 'TEXT';
- case 'blob':
- return 'TEXT';
- case 'integer':
- return 'INT';
- case 'boolean':
- return 'INT';
- case 'date':
- return 'CHAR ('.strlen('YYYY-MM-DD').')';
- case 'time':
- return 'CHAR ('.strlen('HH:MM:SS').')';
- case 'timestamp':
- return 'CHAR ('.strlen('YYYY-MM-DD HH:MM:SS').')';
- case 'float':
- return 'TEXT';
- case 'decimal':
- return 'TEXT';
- }
- return '';
- }
-
- // }}}
- // {{{ _getDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare a generic type
- * field to be used in statements like CREATE TABLE.
- *
- * @param string $name name the field to be declared.
- * @param array $field associative array with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * length
- * Integer value that determines the maximum length of the text
- * field. If this argument is missing the field should be
- * declared to have the longest length allowed by the DBMS.
- *
- * default
- * Text value to be used as default for this field.
- *
- * notnull
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- * charset
- * Text value with the default CHARACTER SET for this field.
- * collation
- * Text value with the default COLLATION for this field.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field, or a MDB2_Error on failure
- * @access protected
- */
- function _getDeclaration($name, $field)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $name = $db->quoteIdentifier($name, true);
- $declaration_options = $db->datatype->_getDeclarationOptions($field);
- if (PEAR::isError($declaration_options)) {
- return $declaration_options;
- }
- return $name.' '.$this->getTypeDeclaration($field).$declaration_options;
- }
-
- // }}}
- // {{{ _getDeclarationOptions()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare a generic type
- * field to be used in statement like CREATE TABLE, without the field name
- * and type values (ie. just the character set, default value, if the
- * field is permitted to be NULL or not, and the collation options).
- *
- * @param array $field associative array with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * default
- * Text value to be used as default for this field.
- * notnull
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- * charset
- * Text value with the default CHARACTER SET for this field.
- * collation
- * Text value with the default COLLATION for this field.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field's options.
- * @access protected
- */
- function _getDeclarationOptions($field)
- {
- $charset = empty($field['charset']) ? '' :
- ' '.$this->_getCharsetFieldDeclaration($field['charset']);
-
- $default = '';
- if (array_key_exists('default', $field)) {
- if ($field['default'] === '') {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- if (empty($field['notnull'])) {
- $field['default'] = null;
- } else {
- $valid_default_values = $this->getValidTypes();
- $field['default'] = $valid_default_values[$field['type']];
- }
- if ($field['default'] === ''
- && ($db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL)
- ) {
- $field['default'] = ' ';
- }
- }
- $default = ' DEFAULT '.$this->quote($field['default'], $field['type']);
- } elseif (empty($field['notnull'])) {
- $default = ' DEFAULT NULL';
- }
-
- $notnull = empty($field['notnull']) ? '' : ' NOT NULL';
-
- $collation = empty($field['collation']) ? '' :
- ' '.$this->_getCollationFieldDeclaration($field['collation']);
- return $charset.$default.$notnull.$collation;
- }
-
- // }}}
- // {{{ _getCharsetFieldDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to set the CHARACTER SET
- * of a field declaration to be used in statements like CREATE TABLE.
- *
- * @param string $charset name of the charset
- * @return string DBMS specific SQL code portion needed to set the CHARACTER SET
- * of a field declaration.
- */
- function _getCharsetFieldDeclaration($charset)
- {
- return '';
- }
-
- // }}}
- // {{{ _getCollationFieldDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to set the COLLATION
- * of a field declaration to be used in statements like CREATE TABLE.
- *
- * @param string $collation name of the collation
- * @return string DBMS specific SQL code portion needed to set the COLLATION
- * of a field declaration.
- */
- function _getCollationFieldDeclaration($collation)
- {
- return '';
- }
-
- // }}}
- // {{{ _getIntegerDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare an integer type
- * field to be used in statements like CREATE TABLE.
- *
- * @param string $name name the field to be declared.
- * @param array $field associative array with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * unsigned
- * Boolean flag that indicates whether the field should be
- * declared as unsigned integer if possible.
- *
- * default
- * Integer value to be used as default for this field.
- *
- * notnull
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access protected
- */
- function _getIntegerDeclaration($name, $field)
- {
- if (!empty($field['unsigned'])) {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $db->warnings[] = "unsigned integer field \"$name\" is being declared as signed integer";
- }
- return $this->_getDeclaration($name, $field);
- }
-
- // }}}
- // {{{ _getTextDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare an text type
- * field to be used in statements like CREATE TABLE.
- *
- * @param string $name name the field to be declared.
- * @param array $field associative array with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * length
- * Integer value that determines the maximum length of the text
- * field. If this argument is missing the field should be
- * declared to have the longest length allowed by the DBMS.
- *
- * default
- * Text value to be used as default for this field.
- *
- * notnull
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access protected
- */
- function _getTextDeclaration($name, $field)
- {
- return $this->_getDeclaration($name, $field);
- }
-
- // }}}
- // {{{ _getCLOBDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare an character
- * large object type field to be used in statements like CREATE TABLE.
- *
- * @param string $name name the field to be declared.
- * @param array $field associative array with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * length
- * Integer value that determines the maximum length of the large
- * object field. If this argument is missing the field should be
- * declared to have the longest length allowed by the DBMS.
- *
- * notnull
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access public
- */
- function _getCLOBDeclaration($name, $field)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $notnull = empty($field['notnull']) ? '' : ' NOT NULL';
- $name = $db->quoteIdentifier($name, true);
- return $name.' '.$this->getTypeDeclaration($field).$notnull;
- }
-
- // }}}
- // {{{ _getBLOBDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare an binary large
- * object type field to be used in statements like CREATE TABLE.
- *
- * @param string $name name the field to be declared.
- * @param array $field associative array with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * length
- * Integer value that determines the maximum length of the large
- * object field. If this argument is missing the field should be
- * declared to have the longest length allowed by the DBMS.
- *
- * notnull
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access protected
- */
- function _getBLOBDeclaration($name, $field)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $notnull = empty($field['notnull']) ? '' : ' NOT NULL';
- $name = $db->quoteIdentifier($name, true);
- return $name.' '.$this->getTypeDeclaration($field).$notnull;
- }
-
- // }}}
- // {{{ _getBooleanDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare a boolean type
- * field to be used in statements like CREATE TABLE.
- *
- * @param string $name name the field to be declared.
- * @param array $field associative array with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * default
- * Boolean value to be used as default for this field.
- *
- * notnullL
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access protected
- */
- function _getBooleanDeclaration($name, $field)
- {
- return $this->_getDeclaration($name, $field);
- }
-
- // }}}
- // {{{ _getDateDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare a date type
- * field to be used in statements like CREATE TABLE.
- *
- * @param string $name name the field to be declared.
- * @param array $field associative array with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * default
- * Date value to be used as default for this field.
- *
- * notnull
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access protected
- */
- function _getDateDeclaration($name, $field)
- {
- return $this->_getDeclaration($name, $field);
- }
-
- // }}}
- // {{{ _getTimestampDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare a timestamp
- * field to be used in statements like CREATE TABLE.
- *
- * @param string $name name the field to be declared.
- * @param array $field associative array with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * default
- * Timestamp value to be used as default for this field.
- *
- * notnull
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access protected
- */
- function _getTimestampDeclaration($name, $field)
- {
- return $this->_getDeclaration($name, $field);
- }
-
- // }}}
- // {{{ _getTimeDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare a time
- * field to be used in statements like CREATE TABLE.
- *
- * @param string $name name the field to be declared.
- * @param array $field associative array with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * default
- * Time value to be used as default for this field.
- *
- * notnull
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access protected
- */
- function _getTimeDeclaration($name, $field)
- {
- return $this->_getDeclaration($name, $field);
- }
-
- // }}}
- // {{{ _getFloatDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare a float type
- * field to be used in statements like CREATE TABLE.
- *
- * @param string $name name the field to be declared.
- * @param array $field associative array with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * default
- * Float value to be used as default for this field.
- *
- * notnull
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access protected
- */
- function _getFloatDeclaration($name, $field)
- {
- return $this->_getDeclaration($name, $field);
- }
-
- // }}}
- // {{{ _getDecimalDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare a decimal type
- * field to be used in statements like CREATE TABLE.
- *
- * @param string $name name the field to be declared.
- * @param array $field associative array with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * default
- * Decimal value to be used as default for this field.
- *
- * notnull
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access protected
- */
- function _getDecimalDeclaration($name, $field)
- {
- return $this->_getDeclaration($name, $field);
- }
-
- // }}}
- // {{{ compareDefinition()
-
- /**
- * Obtain an array of changes that may need to applied
- *
- * @param array $current new definition
- * @param array $previous old definition
- * @return array containing all changes that will need to be applied
- * @access public
- */
- function compareDefinition($current, $previous)
- {
- $type = !empty($current['type']) ? $current['type'] : null;
-
- if (!method_exists($this, "_compare{$type}Definition")) {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- if (!empty($db->options['datatype_map_callback'][$type])) {
- $parameter = array('current' => $current, 'previous' => $previous);
- $change = call_user_func_array($db->options['datatype_map_callback'][$type], array(&$db, __FUNCTION__, $parameter));
- return $change;
- }
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'type "'.$current['type'].'" is not yet supported', __FUNCTION__);
- }
-
- if (empty($previous['type']) || $previous['type'] != $type) {
- return $current;
- }
-
- $change = $this->{"_compare{$type}Definition"}($current, $previous);
-
- if ($previous['type'] != $type) {
- $change['type'] = true;
- }
-
- $previous_notnull = !empty($previous['notnull']) ? $previous['notnull'] : false;
- $notnull = !empty($current['notnull']) ? $current['notnull'] : false;
- if ($previous_notnull != $notnull) {
- $change['notnull'] = true;
- }
-
- $previous_default = array_key_exists('default', $previous) ? $previous['default'] :
- ($previous_notnull ? '' : null);
- $default = array_key_exists('default', $current) ? $current['default'] :
- ($notnull ? '' : null);
- if ($previous_default !== $default) {
- $change['default'] = true;
- }
-
- return $change;
- }
-
- // }}}
- // {{{ _compareIntegerDefinition()
-
- /**
- * Obtain an array of changes that may need to applied to an integer field
- *
- * @param array $current new definition
- * @param array $previous old definition
- * @return array containing all changes that will need to be applied
- * @access protected
- */
- function _compareIntegerDefinition($current, $previous)
- {
- $change = array();
- $previous_unsigned = !empty($previous['unsigned']) ? $previous['unsigned'] : false;
- $unsigned = !empty($current['unsigned']) ? $current['unsigned'] : false;
- if ($previous_unsigned != $unsigned) {
- $change['unsigned'] = true;
- }
- $previous_autoincrement = !empty($previous['autoincrement']) ? $previous['autoincrement'] : false;
- $autoincrement = !empty($current['autoincrement']) ? $current['autoincrement'] : false;
- if ($previous_autoincrement != $autoincrement) {
- $change['autoincrement'] = true;
- }
- return $change;
- }
-
- // }}}
- // {{{ _compareTextDefinition()
-
- /**
- * Obtain an array of changes that may need to applied to an text field
- *
- * @param array $current new definition
- * @param array $previous old definition
- * @return array containing all changes that will need to be applied
- * @access protected
- */
- function _compareTextDefinition($current, $previous)
- {
- $change = array();
- $previous_length = !empty($previous['length']) ? $previous['length'] : 0;
- $length = !empty($current['length']) ? $current['length'] : 0;
- if ($previous_length != $length) {
- $change['length'] = true;
- }
- $previous_fixed = !empty($previous['fixed']) ? $previous['fixed'] : 0;
- $fixed = !empty($current['fixed']) ? $current['fixed'] : 0;
- if ($previous_fixed != $fixed) {
- $change['fixed'] = true;
- }
- return $change;
- }
-
- // }}}
- // {{{ _compareCLOBDefinition()
-
- /**
- * Obtain an array of changes that may need to applied to an CLOB field
- *
- * @param array $current new definition
- * @param array $previous old definition
- * @return array containing all changes that will need to be applied
- * @access protected
- */
- function _compareCLOBDefinition($current, $previous)
- {
- return $this->_compareTextDefinition($current, $previous);
- }
-
- // }}}
- // {{{ _compareBLOBDefinition()
-
- /**
- * Obtain an array of changes that may need to applied to an BLOB field
- *
- * @param array $current new definition
- * @param array $previous old definition
- * @return array containing all changes that will need to be applied
- * @access protected
- */
- function _compareBLOBDefinition($current, $previous)
- {
- return $this->_compareTextDefinition($current, $previous);
- }
-
- // }}}
- // {{{ _compareDateDefinition()
-
- /**
- * Obtain an array of changes that may need to applied to an date field
- *
- * @param array $current new definition
- * @param array $previous old definition
- * @return array containing all changes that will need to be applied
- * @access protected
- */
- function _compareDateDefinition($current, $previous)
- {
- return array();
- }
-
- // }}}
- // {{{ _compareTimeDefinition()
-
- /**
- * Obtain an array of changes that may need to applied to an time field
- *
- * @param array $current new definition
- * @param array $previous old definition
- * @return array containing all changes that will need to be applied
- * @access protected
- */
- function _compareTimeDefinition($current, $previous)
- {
- return array();
- }
-
- // }}}
- // {{{ _compareTimestampDefinition()
-
- /**
- * Obtain an array of changes that may need to applied to an timestamp field
- *
- * @param array $current new definition
- * @param array $previous old definition
- * @return array containing all changes that will need to be applied
- * @access protected
- */
- function _compareTimestampDefinition($current, $previous)
- {
- return array();
- }
-
- // }}}
- // {{{ _compareBooleanDefinition()
-
- /**
- * Obtain an array of changes that may need to applied to an boolean field
- *
- * @param array $current new definition
- * @param array $previous old definition
- * @return array containing all changes that will need to be applied
- * @access protected
- */
- function _compareBooleanDefinition($current, $previous)
- {
- return array();
- }
-
- // }}}
- // {{{ _compareFloatDefinition()
-
- /**
- * Obtain an array of changes that may need to applied to an float field
- *
- * @param array $current new definition
- * @param array $previous old definition
- * @return array containing all changes that will need to be applied
- * @access protected
- */
- function _compareFloatDefinition($current, $previous)
- {
- return array();
- }
-
- // }}}
- // {{{ _compareDecimalDefinition()
-
- /**
- * Obtain an array of changes that may need to applied to an decimal field
- *
- * @param array $current new definition
- * @param array $previous old definition
- * @return array containing all changes that will need to be applied
- * @access protected
- */
- function _compareDecimalDefinition($current, $previous)
- {
- return array();
- }
-
- // }}}
- // {{{ quote()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @param string $type type to which the value should be converted to
- * @param bool $quote determines if the value should be quoted and escaped
- * @param bool $escape_wildcards if to escape escape wildcards
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- * @access public
- */
- function quote($value, $type = null, $quote = true, $escape_wildcards = false)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if (is_null($value)
- || ($value === '' && $db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL)
- ) {
- if (!$quote) {
- return null;
- }
- return 'NULL';
- }
-
- if (is_null($type)) {
- switch (gettype($value)) {
- case 'integer':
- $type = 'integer';
- break;
- case 'double':
- // todo: default to decimal as float is quite unusual
- // $type = 'float';
- $type = 'decimal';
- break;
- case 'boolean':
- $type = 'boolean';
- break;
- case 'array':
- $value = serialize($value);
- case 'object':
- $type = 'text';
- break;
- default:
- if (preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/', $value)) {
- $type = 'timestamp';
- } elseif (preg_match('/^\d{2}:\d{2}$/', $value)) {
- $type = 'time';
- } elseif (preg_match('/^\d{4}-\d{2}-\d{2}$/', $value)) {
- $type = 'date';
- } else {
- $type = 'text';
- }
- break;
- }
- } elseif (!empty($db->options['datatype_map'][$type])) {
- $type = $db->options['datatype_map'][$type];
- if (!empty($db->options['datatype_map_callback'][$type])) {
- $parameter = array('type' => $type, 'value' => $value, 'quote' => $quote, 'escape_wildcards' => $escape_wildcards);
- return call_user_func_array($db->options['datatype_map_callback'][$type], array(&$db, __FUNCTION__, $parameter));
- }
- }
-
- if (!method_exists($this, "_quote{$type}")) {
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'type not defined: '.$type, __FUNCTION__);
- }
- $value = $this->{"_quote{$type}"}($value, $quote, $escape_wildcards);
- if ($quote && $escape_wildcards && $db->string_quoting['escape_pattern']
- && $db->string_quoting['escape'] !== $db->string_quoting['escape_pattern']
- ) {
- $value.= $this->patternEscapeString();
- }
- return $value;
- }
-
- // }}}
- // {{{ _quoteInteger()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @param bool $quote determines if the value should be quoted and escaped
- * @param bool $escape_wildcards if to escape escape wildcards
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- * @access protected
- */
- function _quoteInteger($value, $quote, $escape_wildcards)
- {
- return (int)$value;
- }
-
- // }}}
- // {{{ _quoteText()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @param bool $quote determines if the value should be quoted and escaped
- * @param bool $escape_wildcards if to escape escape wildcards
- * @return string text string that already contains any DBMS specific
- * escaped character sequences.
- * @access protected
- */
- function _quoteText($value, $quote, $escape_wildcards)
- {
- if (!$quote) {
- return $value;
- }
-
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $value = $db->escape($value, $escape_wildcards);
- if (PEAR::isError($value)) {
- return $value;
- }
- return "'".$value."'";
- }
-
- // }}}
- // {{{ _readFile()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- * @access protected
- */
- function _readFile($value)
- {
- $close = false;
- if (preg_match('/^(\w+:\/\/)(.*)$/', $value, $match)) {
- $close = true;
- if ($match[1] == 'file://') {
- $value = $match[2];
- }
- $value = @fopen($value, 'r');
- }
-
- if (is_resource($value)) {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $fp = $value;
- $value = '';
- while (!@feof($fp)) {
- $value.= @fread($fp, $db->options['lob_buffer_length']);
- }
- if ($close) {
- @fclose($fp);
- }
- }
-
- return $value;
- }
-
- // }}}
- // {{{ _quoteLOB()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @param bool $quote determines if the value should be quoted and escaped
- * @param bool $escape_wildcards if to escape escape wildcards
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- * @access protected
- */
- function _quoteLOB($value, $quote, $escape_wildcards)
- {
- $value = $this->_readFile($value);
- if (PEAR::isError($value)) {
- return $value;
- }
- return $this->_quoteText($value, $quote, $escape_wildcards);
- }
-
- // }}}
- // {{{ _quoteCLOB()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @param bool $quote determines if the value should be quoted and escaped
- * @param bool $escape_wildcards if to escape escape wildcards
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- * @access protected
- */
- function _quoteCLOB($value, $quote, $escape_wildcards)
- {
- return $this->_quoteLOB($value, $quote, $escape_wildcards);
- }
-
- // }}}
- // {{{ _quoteBLOB()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @param bool $quote determines if the value should be quoted and escaped
- * @param bool $escape_wildcards if to escape escape wildcards
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- * @access protected
- */
- function _quoteBLOB($value, $quote, $escape_wildcards)
- {
- return $this->_quoteLOB($value, $quote, $escape_wildcards);
- }
-
- // }}}
- // {{{ _quoteBoolean()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @param bool $quote determines if the value should be quoted and escaped
- * @param bool $escape_wildcards if to escape escape wildcards
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- * @access protected
- */
- function _quoteBoolean($value, $quote, $escape_wildcards)
- {
- return ($value ? 1 : 0);
- }
-
- // }}}
- // {{{ _quoteDate()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @param bool $quote determines if the value should be quoted and escaped
- * @param bool $escape_wildcards if to escape escape wildcards
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- * @access protected
- */
- function _quoteDate($value, $quote, $escape_wildcards)
- {
- if ($value === 'CURRENT_DATE') {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- if (isset($db->function) && is_a($db->function, 'MDB2_Driver_Function_Common')) {
- return $db->function->now('date');
- }
- return 'CURRENT_DATE';
- }
- return $this->_quoteText($value, $quote, $escape_wildcards);
- }
-
- // }}}
- // {{{ _quoteTimestamp()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @param bool $quote determines if the value should be quoted and escaped
- * @param bool $escape_wildcards if to escape escape wildcards
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- * @access protected
- */
- function _quoteTimestamp($value, $quote, $escape_wildcards)
- {
- if ($value === 'CURRENT_TIMESTAMP') {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- if (isset($db->function) && is_a($db->function, 'MDB2_Driver_Function_Common')) {
- return $db->function->now('timestamp');
- }
- return 'CURRENT_TIMESTAMP';
- }
- return $this->_quoteText($value, $quote, $escape_wildcards);
- }
-
- // }}}
- // {{{ _quoteTime()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @param bool $quote determines if the value should be quoted and escaped
- * @param bool $escape_wildcards if to escape escape wildcards
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- * @access protected
- */
- function _quoteTime($value, $quote, $escape_wildcards)
- {
- if ($value === 'CURRENT_TIME') {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- if (isset($db->function) && is_a($db->function, 'MDB2_Driver_Function_Common')) {
- return $db->function->now('time');
- }
- return 'CURRENT_TIME';
- }
- return $this->_quoteText($value, $quote, $escape_wildcards);
- }
-
- // }}}
- // {{{ _quoteFloat()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @param bool $quote determines if the value should be quoted and escaped
- * @param bool $escape_wildcards if to escape escape wildcards
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- * @access protected
- */
- function _quoteFloat($value, $quote, $escape_wildcards)
- {
- if (preg_match('/^(.*)e([-+])(\d+)$/i', $value, $matches)) {
- $decimal = $this->_quoteDecimal($matches[1], $quote, $escape_wildcards);
- $sign = $matches[2];
- $exponent = str_pad($matches[3], 2, '0', STR_PAD_LEFT);
- $value = $decimal.'E'.$sign.$exponent;
- } else {
- $value = $this->_quoteDecimal($value, $quote, $escape_wildcards);
- }
- return $value;
- }
-
- // }}}
- // {{{ _quoteDecimal()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @param bool $quote determines if the value should be quoted and escaped
- * @param bool $escape_wildcards if to escape escape wildcards
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- * @access protected
- */
- function _quoteDecimal($value, $quote, $escape_wildcards)
- {
- $value = (string)$value;
- $value = preg_replace('/[^\d\.,\-+eE]/', '', $value);
- if (preg_match('/[^.0-9]/', $value)) {
- if (strpos($value, ',')) {
- // 1000,00
- if (!strpos($value, '.')) {
- // convert the last "," to a "."
- $value = strrev(str_replace(',', '.', strrev($value)));
- // 1.000,00
- } elseif (strpos($value, '.') && strpos($value, '.') < strpos($value, ',')) {
- $value = str_replace('.', '', $value);
- // convert the last "," to a "."
- $value = strrev(str_replace(',', '.', strrev($value)));
- // 1,000.00
- } else {
- $value = str_replace(',', '', $value);
- }
- }
- }
- return $value;
- }
-
- // }}}
- // {{{ writeLOBToFile()
-
- /**
- * retrieve LOB from the database
- *
- * @param resource $lob stream handle
- * @param string $file name of the file into which the LOb should be fetched
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access protected
- */
- function writeLOBToFile($lob, $file)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if (preg_match('/^(\w+:\/\/)(.*)$/', $file, $match)) {
- if ($match[1] == 'file://') {
- $file = $match[2];
- }
- }
-
- $fp = @fopen($file, 'wb');
- while (!@feof($lob)) {
- $result = @fread($lob, $db->options['lob_buffer_length']);
- $read = strlen($result);
- if (@fwrite($fp, $result, $read) != $read) {
- @fclose($fp);
- return $db->raiseError(MDB2_ERROR, null, null,
- 'could not write to the output file', __FUNCTION__);
- }
- }
- @fclose($fp);
- return MDB2_OK;
- }
-
- // }}}
- // {{{ _retrieveLOB()
-
- /**
- * retrieve LOB from the database
- *
- * @param array $lob array
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access protected
- */
- function _retrieveLOB(&$lob)
- {
- if (is_null($lob['value'])) {
- $lob['value'] = $lob['resource'];
- }
- $lob['loaded'] = true;
- return MDB2_OK;
- }
-
- // }}}
- // {{{ readLOB()
-
- /**
- * Read data from large object input stream.
- *
- * @param resource $lob stream handle
- * @param string $data reference to a variable that will hold data
- * to be read from the large object input stream
- * @param integer $length value that indicates the largest ammount ofdata
- * to be read from the large object input stream.
- * @return mixed the effective number of bytes read from the large object
- * input stream on sucess or an MDB2 error object.
- * @access public
- * @see endOfLOB()
- */
- function _readLOB($lob, $length)
- {
- return substr($lob['value'], $lob['position'], $length);
- }
-
- // }}}
- // {{{ _endOfLOB()
-
- /**
- * Determine whether it was reached the end of the large object and
- * therefore there is no more data to be read for the its input stream.
- *
- * @param array $lob array
- * @return mixed true or false on success, a MDB2 error on failure
- * @access protected
- */
- function _endOfLOB($lob)
- {
- return $lob['endOfLOB'];
- }
-
- // }}}
- // {{{ destroyLOB()
-
- /**
- * Free any resources allocated during the lifetime of the large object
- * handler object.
- *
- * @param resource $lob stream handle
- * @access public
- */
- function destroyLOB($lob)
- {
- $lob_data = stream_get_meta_data($lob);
- $lob_index = $lob_data['wrapper_data']->lob_index;
- fclose($lob);
- if (isset($this->lobs[$lob_index])) {
- $this->_destroyLOB($this->lobs[$lob_index]);
- unset($this->lobs[$lob_index]);
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ _destroyLOB()
-
- /**
- * Free any resources allocated during the lifetime of the large object
- * handler object.
- *
- * @param array $lob array
- * @access private
- */
- function _destroyLOB(&$lob)
- {
- return MDB2_OK;
- }
-
- // }}}
- // {{{ implodeArray()
-
- /**
- * apply a type to all values of an array and return as a comma seperated string
- * useful for generating IN statements
- *
- * @access public
- *
- * @param array $array data array
- * @param string $type determines type of the field
- *
- * @return string comma seperated values
- */
- function implodeArray($array, $type = false)
- {
- if (!is_array($array) || empty($array)) {
- return 'NULL';
- }
- if ($type) {
- foreach ($array as $value) {
- $return[] = $this->quote($value, $type);
- }
- } else {
- $return = $array;
- }
- return implode(', ', $return);
- }
-
- // }}}
- // {{{ matchPattern()
-
- /**
- * build a pattern matching string
- *
- * @access public
- *
- * @param array $pattern even keys are strings, odd are patterns (% and _)
- * @param string $operator optional pattern operator (LIKE, ILIKE and maybe others in the future)
- * @param string $field optional field name that is being matched against
- * (might be required when emulating ILIKE)
- *
- * @return string SQL pattern
- */
- function matchPattern($pattern, $operator = null, $field = null)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $match = '';
- if (!is_null($operator)) {
- $operator = strtoupper($operator);
- switch ($operator) {
- // case insensitive
- case 'ILIKE':
- if (is_null($field)) {
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'case insensitive LIKE matching requires passing the field name', __FUNCTION__);
- }
- $db->loadModule('Function', null, true);
- $match = $db->function->lower($field).' LIKE ';
- break;
- // case sensitive
- case 'LIKE':
- $match = is_null($field) ? 'LIKE ' : $field.' LIKE ';
- break;
- default:
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'not a supported operator type:'. $operator, __FUNCTION__);
- }
- }
- $match.= "'";
- foreach ($pattern as $key => $value) {
- if ($key % 2) {
- $match.= $value;
- } else {
- if ($operator === 'ILIKE') {
- $value = strtolower($value);
- }
- $escaped = $db->escape($value);
- if (PEAR::isError($escaped)) {
- return $escaped;
- }
- $match.= $db->escapePattern($escaped);
- }
- }
- $match.= "'";
- $match.= $this->patternEscapeString();
- return $match;
- }
-
- // }}}
- // {{{ patternEscapeString()
-
- /**
- * build string to define pattern escape character
- *
- * @access public
- *
- * @return string define pattern escape character
- */
- function patternEscapeString()
- {
- return '';
- }
-
- // }}}
- // {{{ mapNativeDatatype()
-
- /**
- * Maps a native array description of a field to a MDB2 datatype and length
- *
- * @param array $field native field description
- * @return array containing the various possible types, length, sign, fixed
- * @access public
- */
- function mapNativeDatatype($field)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- // If the user has specified an option to map the native field
- // type to a custom MDB2 datatype...
- $db_type = strtok($field['type'], '(), ');
- if (!empty($db->options['nativetype_map_callback'][$db_type])) {
- return call_user_func_array($db->options['nativetype_map_callback'][$db_type], array($db, $field));
- }
-
- // Otherwise perform the built-in (i.e. normal) MDB2 native type to
- // MDB2 datatype conversion
- return $this->_mapNativeDatatype($field);
- }
-
- // }}}
- // {{{ _mapNativeDatatype()
-
- /**
- * Maps a native array description of a field to a MDB2 datatype and length
- *
- * @param array $field native field description
- * @return array containing the various possible types, length, sign, fixed
- * @access public
- */
- function _mapNativeDatatype($field)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ mapPrepareDatatype()
-
- /**
- * Maps an mdb2 datatype to mysqli prepare type
- *
- * @param string $type
- * @return string
- * @access public
- */
- function mapPrepareDatatype($type)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if (!empty($db->options['datatype_map'][$type])) {
- $type = $db->options['datatype_map'][$type];
- if (!empty($db->options['datatype_map_callback'][$type])) {
- $parameter = array('type' => $type);
- return call_user_func_array($db->options['datatype_map_callback'][$type], array(&$db, __FUNCTION__, $parameter));
- }
- }
-
- return $type;
- }
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2007 Manuel Lemos, Tomas V.V.Cox, |
-// | Stig. S. Bakken, Lukas Smith |
-// | All rights reserved. |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
-// | API as well as database abstraction for PHP applications. |
-// | This LICENSE is in the BSD license style. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | |
-// | Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution. |
-// | |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
-// | POSSIBILITY OF SUCH DAMAGE. |
-// +----------------------------------------------------------------------+
-// | Author: Paul Cooper <pgc@ucecom.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: pgsql.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
-
-require_once 'MDB2/Driver/Datatype/Common.php';
-
-/**
- * MDB2 PostGreSQL driver
- *
- * @package MDB2
- * @category Database
- * @author Paul Cooper <pgc@ucecom.com>
- */
-class MDB2_Driver_Datatype_pgsql extends MDB2_Driver_Datatype_Common
-{
- // {{{ _baseConvertResult()
-
- /**
- * General type conversion method
- *
- * @param mixed $value refernce to a value to be converted
- * @param string $type specifies which type to convert to
- * @param boolean $rtrim [optional] when TRUE [default], apply rtrim() to text
- * @return object a MDB2 error on failure
- * @access protected
- */
- function _baseConvertResult($value, $type, $rtrim = true)
- {
- if (is_null($value)) {
- return null;
- }
- switch ($type) {
- case 'boolean':
- return $value == 't';
- case 'float':
- return doubleval($value);
- case 'date':
- return $value;
- case 'time':
- return substr($value, 0, strlen('HH:MM:SS'));
- case 'timestamp':
- return substr($value, 0, strlen('YYYY-MM-DD HH:MM:SS'));
- case 'blob':
- $value = pg_unescape_bytea($value);
- return parent::_baseConvertResult($value, $type, $rtrim);
- }
- return parent::_baseConvertResult($value, $type, $rtrim);
- }
-
- // }}}
- // {{{ getTypeDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare an text type
- * field to be used in statements like CREATE TABLE.
- *
- * @param array $field associative array with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * length
- * Integer value that determines the maximum length of the text
- * field. If this argument is missing the field should be
- * declared to have the longest length allowed by the DBMS.
- *
- * default
- * Text value to be used as default for this field.
- *
- * notnull
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access public
- */
- function getTypeDeclaration($field)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- switch ($field['type']) {
- case 'text':
- $length = !empty($field['length'])
- ? $field['length'] : $db->options['default_text_field_length'];
- $fixed = !empty($field['fixed']) ? $field['fixed'] : false;
- return $fixed ? ($length ? 'CHAR('.$length.')' : 'CHAR('.$db->options['default_text_field_length'].')')
- : ($length ? 'VARCHAR('.$length.')' : 'TEXT');
- case 'clob':
- return 'TEXT';
- case 'blob':
- return 'BYTEA';
- case 'integer':
- if (!empty($field['autoincrement'])) {
- if (!empty($field['length'])) {
- $length = $field['length'];
- if ($length > 4) {
- return 'BIGSERIAL PRIMARY KEY';
- }
- }
- return 'SERIAL PRIMARY KEY';
- }
- if (!empty($field['length'])) {
- $length = $field['length'];
- if ($length <= 2) {
- return 'SMALLINT';
- } elseif ($length == 3 || $length == 4) {
- return 'INT';
- } elseif ($length > 4) {
- return 'BIGINT';
- }
- }
- return 'INT';
- case 'boolean':
- return 'BOOLEAN';
- case 'date':
- return 'DATE';
- case 'time':
- return 'TIME without time zone';
- case 'timestamp':
- return 'TIMESTAMP without time zone';
- case 'float':
- return 'FLOAT8';
- case 'decimal':
- $length = !empty($field['length']) ? $field['length'] : 18;
- $scale = !empty($field['scale']) ? $field['scale'] : $db->options['decimal_places'];
- return 'NUMERIC('.$length.','.$scale.')';
- }
- }
-
- // }}}
- // {{{ _getIntegerDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare an integer type
- * field to be used in statements like CREATE TABLE.
- *
- * @param string $name name the field to be declared.
- * @param array $field associative array with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * unsigned
- * Boolean flag that indicates whether the field should be
- * declared as unsigned integer if possible.
- *
- * default
- * Integer value to be used as default for this field.
- *
- * notnull
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access protected
- */
- function _getIntegerDeclaration($name, $field)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if (!empty($field['unsigned'])) {
- $db->warnings[] = "unsigned integer field \"$name\" is being declared as signed integer";
- }
- if (!empty($field['autoincrement'])) {
- $name = $db->quoteIdentifier($name, true);
- return $name.' '.$this->getTypeDeclaration($field);
- }
- $default = '';
- if (array_key_exists('default', $field)) {
- if ($field['default'] === '') {
- $field['default'] = empty($field['notnull']) ? null : 0;
- }
- $default = ' DEFAULT '.$this->quote($field['default'], 'integer');
- } elseif (empty($field['notnull'])) {
- $default = ' DEFAULT NULL';
- }
-
- $notnull = empty($field['notnull']) ? '' : ' NOT NULL';
- $name = $db->quoteIdentifier($name, true);
- return $name.' '.$this->getTypeDeclaration($field).$default.$notnull;
- }
-
- // }}}
- // {{{ _quoteCLOB()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @param bool $quote determines if the value should be quoted and escaped
- * @param bool $escape_wildcards if to escape escape wildcards
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- * @access protected
- */
- function _quoteCLOB($value, $quote, $escape_wildcards)
- {
- return $this->_quoteText($value, $quote, $escape_wildcards);
- }
-
- // }}}
- // {{{ _quoteBLOB()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @param bool $quote determines if the value should be quoted and escaped
- * @param bool $escape_wildcards if to escape escape wildcards
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- * @access protected
- */
- function _quoteBLOB($value, $quote, $escape_wildcards)
- {
- if (!$quote) {
- return $value;
- }
- if (version_compare(PHP_VERSION, '5.2.0RC6', '>=')) {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- $connection = $db->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- $value = @pg_escape_bytea($connection, $value);
- } else {
- $value = @pg_escape_bytea($value);
- }
- return "'".$value."'";
- }
-
- // }}}
- // {{{ _quoteBoolean()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @param bool $quote determines if the value should be quoted and escaped
- * @param bool $escape_wildcards if to escape escape wildcards
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- * @access protected
- */
- function _quoteBoolean($value, $quote, $escape_wildcards)
- {
- $value = $value ? 't' : 'f';
- if (!$quote) {
- return $value;
- }
- return "'".$value."'";
- }
-
- // }}}
- // {{{ matchPattern()
-
- /**
- * build a pattern matching string
- *
- * @access public
- *
- * @param array $pattern even keys are strings, odd are patterns (% and _)
- * @param string $operator optional pattern operator (LIKE, ILIKE and maybe others in the future)
- * @param string $field optional field name that is being matched against
- * (might be required when emulating ILIKE)
- *
- * @return string SQL pattern
- */
- function matchPattern($pattern, $operator = null, $field = null)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $match = '';
- if (!is_null($operator)) {
- $field = is_null($field) ? '' : $field.' ';
- $operator = strtoupper($operator);
- switch ($operator) {
- // case insensitive
- case 'ILIKE':
- $match = $field.'ILIKE ';
- break;
- // case sensitive
- case 'LIKE':
- $match = $field.'LIKE ';
- break;
- default:
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'not a supported operator type:'. $operator, __FUNCTION__);
- }
- }
- $match.= "'";
- foreach ($pattern as $key => $value) {
- if ($key % 2) {
- $match.= $value;
- } else {
- $match.= $db->escapePattern($db->escape($value));
- }
- }
- $match.= "'";
- $match.= $this->patternEscapeString();
- return $match;
- }
-
- // }}}
- // {{{ patternEscapeString()
-
- /**
- * build string to define escape pattern string
- *
- * @access public
- *
- *
- * @return string define escape pattern
- */
- function patternEscapeString()
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- return ' ESCAPE '.$this->quote($db->string_quoting['escape_pattern']);
- }
-
- // }}}
- // {{{ _mapNativeDatatype()
-
- /**
- * Maps a native array description of a field to a MDB2 datatype and length
- *
- * @param array $field native field description
- * @return array containing the various possible types, length, sign, fixed
- * @access public
- */
- function _mapNativeDatatype($field)
- {
- $db_type = strtolower($field['type']);
- $length = $field['length'];
- $type = array();
- $unsigned = $fixed = null;
- switch ($db_type) {
- case 'smallint':
- case 'int2':
- $type[] = 'integer';
- $unsigned = false;
- $length = 2;
- if ($length == '2') {
- $type[] = 'boolean';
- if (preg_match('/^(is|has)/', $field['name'])) {
- $type = array_reverse($type);
- }
- }
- break;
- case 'int':
- case 'int4':
- case 'integer':
- case 'serial':
- case 'serial4':
- $type[] = 'integer';
- $unsigned = false;
- $length = 4;
- break;
- case 'bigint':
- case 'int8':
- case 'bigserial':
- case 'serial8':
- $type[] = 'integer';
- $unsigned = false;
- $length = 8;
- break;
- case 'bool':
- case 'boolean':
- $type[] = 'boolean';
- $length = null;
- break;
- case 'text':
- case 'varchar':
- $fixed = false;
- case 'unknown':
- case 'char':
- case 'bpchar':
- $type[] = 'text';
- if ($length == '1') {
- $type[] = 'boolean';
- if (preg_match('/^(is|has)/', $field['name'])) {
- $type = array_reverse($type);
- }
- } elseif (strstr($db_type, 'text')) {
- $type[] = 'clob';
- $type = array_reverse($type);
- }
- if ($fixed !== false) {
- $fixed = true;
- }
- break;
- case 'date':
- $type[] = 'date';
- $length = null;
- break;
- case 'datetime':
- case 'timestamp':
- $type[] = 'timestamp';
- $length = null;
- break;
- case 'time':
- $type[] = 'time';
- $length = null;
- break;
- case 'float':
- case 'float8':
- case 'double':
- case 'real':
- $type[] = 'float';
- break;
- case 'decimal':
- case 'money':
- case 'numeric':
- $type[] = 'decimal';
- if (isset($field['scale'])) {
- $length = $length.','.$field['scale'];
- }
- break;
- case 'tinyblob':
- case 'mediumblob':
- case 'longblob':
- case 'blob':
- case 'bytea':
- $type[] = 'blob';
- $length = null;
- break;
- case 'oid':
- $type[] = 'blob';
- $type[] = 'clob';
- $length = null;
- break;
- case 'year':
- $type[] = 'integer';
- $type[] = 'date';
- $length = null;
- break;
- default:
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'unknown database attribute type: '.$db_type, __FUNCTION__);
- }
-
- if ((int)$length <= 0) {
- $length = null;
- }
-
- return array($type, $length, $unsigned, $fixed);
- }
-
- // }}}
- // {{{ mapPrepareDatatype()
-
- /**
- * Maps an mdb2 datatype to native prepare type
- *
- * @param string $type
- * @return string
- * @access public
- */
- function mapPrepareDatatype($type)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if (!empty($db->options['datatype_map'][$type])) {
- $type = $db->options['datatype_map'][$type];
- if (!empty($db->options['datatype_map_callback'][$type])) {
- $parameter = array('type' => $type);
- return call_user_func_array($db->options['datatype_map_callback'][$type], array(&$db, __FUNCTION__, $parameter));
- }
- }
-
- switch ($type) {
- case 'integer':
- return 'int';
- case 'boolean':
- return 'bool';
- case 'decimal':
- case 'float':
- return 'numeric';
- case 'clob':
- return 'text';
- case 'blob':
- return 'bytea';
- default:
- break;
- }
- return $type;
- }
- // }}}
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2006 Manuel Lemos, Tomas V.V.Cox, |
-// | Stig. S. Bakken, Lukas Smith |
-// | All rights reserved. |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
-// | API as well as database abstraction for PHP applications. |
-// | This LICENSE is in the BSD license style. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | |
-// | Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution. |
-// | |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
-// | POSSIBILITY OF SUCH DAMAGE. |
-// +----------------------------------------------------------------------+
-// | Author: Lukas Smith <smith@pooteeweet.org> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Common.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
-//
-
-/**
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-
-/**
- * Base class for the function modules that is extended by each MDB2 driver
- *
- * To load this module in the MDB2 object:
- * $mdb->loadModule('Function');
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Driver_Function_Common extends MDB2_Module_Common
-{
- // {{{ executeStoredProc()
-
- /**
- * Execute a stored procedure and return any results
- *
- * @param string $name string that identifies the function to execute
- * @param mixed $params array that contains the paramaters to pass the stored proc
- * @param mixed $types array that contains the types of the columns in
- * the result set
- * @param mixed $result_class string which specifies which result class to use
- * @param mixed $result_wrap_class string which specifies which class to wrap results in
- * @return mixed a result handle or MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function &executeStoredProc($name, $params = null, $types = null, $result_class = true, $result_wrap_class = false)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $error =& $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- return $error;
- }
-
- // }}}
- // {{{ functionTable()
-
- /**
- * return string for internal table used when calling only a function
- *
- * @return string for internal table used when calling only a function
- * @access public
- */
- function functionTable()
- {
- return '';
- }
-
- // }}}
- // {{{ now()
-
- /**
- * Return string to call a variable with the current timestamp inside an SQL statement
- * There are three special variables for current date and time:
- * - CURRENT_TIMESTAMP (date and time, TIMESTAMP type)
- * - CURRENT_DATE (date, DATE type)
- * - CURRENT_TIME (time, TIME type)
- *
- * @return string to call a variable with the current timestamp
- * @access public
- */
- function now($type = 'timestamp')
- {
- switch ($type) {
- case 'time':
- return 'CURRENT_TIME';
- case 'date':
- return 'CURRENT_DATE';
- case 'timestamp':
- default:
- return 'CURRENT_TIMESTAMP';
- }
- }
-
- // }}}
- // {{{ substring()
-
- /**
- * return string to call a function to get a substring inside an SQL statement
- *
- * @return string to call a function to get a substring
- * @access public
- */
- function substring($value, $position = 1, $length = null)
- {
- if (!is_null($length)) {
- return "SUBSTRING($value FROM $position FOR $length)";
- }
- return "SUBSTRING($value FROM $position)";
- }
-
- // }}}
- // {{{ concat()
-
- /**
- * Returns string to concatenate two or more string parameters
- *
- * @param string $value1
- * @param string $value2
- * @param string $values...
- * @return string to concatenate two strings
- * @access public
- */
- function concat($value1, $value2)
- {
- $args = func_get_args();
- return "(".implode(' || ', $args).")";
- }
-
- // }}}
- // {{{ random()
-
- /**
- * return string to call a function to get random value inside an SQL statement
- *
- * @return return string to generate float between 0 and 1
- * @access public
- */
- function random()
- {
- return 'RAND()';
- }
-
- // }}}
- // {{{ lower()
-
- /**
- * return string to call a function to lower the case of an expression
- *
- * @param string $expression
- * @return return string to lower case of an expression
- * @access public
- */
- function lower($expression)
- {
- return "LOWER($expression)";
- }
-
- // }}}
- // {{{ upper()
-
- /**
- * return string to call a function to upper the case of an expression
- *
- * @param string $expression
- * @return return string to upper case of an expression
- * @access public
- */
- function upper($expression)
- {
- return "UPPER($expression)";
- }
-
- // }}}
- // {{{ length()
-
- /**
- * return string to call a function to get the length of a string expression
- *
- * @param string $expression
- * @return return string to get the string expression length
- * @access public
- */
- function length($expression)
- {
- return "LENGTH($expression)";
- }
-
- // }}}
- // {{{ guid()
-
- /**
- * Returns global unique identifier
- *
- * @return string to get global unique identifier
- * @access public
- */
- function guid()
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $error =& $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- return $error;
- }
-
- // }}}
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2006 Manuel Lemos, Tomas V.V.Cox, |
-// | Stig. S. Bakken, Lukas Smith |
-// | All rights reserved. |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
-// | API as well as database abstraction for PHP applications. |
-// | This LICENSE is in the BSD license style. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | |
-// | Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution. |
-// | |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
-// | POSSIBILITY OF SUCH DAMAGE. |
-// +----------------------------------------------------------------------+
-// | Author: Paul Cooper <pgc@ucecom.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: pgsql.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
-
-require_once 'MDB2/Driver/Function/Common.php';
-
-/**
- * MDB2 MySQL driver for the function modules
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Driver_Function_pgsql extends MDB2_Driver_Function_Common
-{
- // {{{ executeStoredProc()
-
- /**
- * Execute a stored procedure and return any results
- *
- * @param string $name string that identifies the function to execute
- * @param mixed $params array that contains the paramaters to pass the stored proc
- * @param mixed $types array that contains the types of the columns in
- * the result set
- * @param mixed $result_class string which specifies which result class to use
- * @param mixed $result_wrap_class string which specifies which class to wrap results in
- * @return mixed a result handle or MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function &executeStoredProc($name, $params = null, $types = null, $result_class = true, $result_wrap_class = false)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = 'SELECT * FROM '.$name;
- $query .= $params ? '('.implode(', ', $params).')' : '()';
- return $db->query($query, $types, $result_class, $result_wrap_class);
- }
- // }}}
- // {{{ random()
-
- /**
- * return string to call a function to get random value inside an SQL statement
- *
- * @return return string to generate float between 0 and 1
- * @access public
- */
- function random()
- {
- return 'RANDOM()';
- }
-
- // }}}
-}
-?>
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2007 Manuel Lemos, Tomas V.V.Cox, |
-// | Stig. S. Bakken, Lukas Smith |
-// | All rights reserved. |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
-// | API as well as database abstraction for PHP applications. |
-// | This LICENSE is in the BSD license style. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | |
-// | Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution. |
-// | |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
-// | POSSIBILITY OF SUCH DAMAGE. |
-// +----------------------------------------------------------------------+
-// | Author: Lukas Smith <smith@pooteeweet.org> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Common.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
-//
-
-/**
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-
-/**
- * Base class for the management modules that is extended by each MDB2 driver
- *
- * To load this module in the MDB2 object:
- * $mdb->loadModule('Manager');
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Driver_Manager_Common extends MDB2_Module_Common
-{
- // {{{ splitTableSchema()
-
- /**
- * Split the "[owner|schema].table" notation into an array
- * @access private
- */
- function splitTableSchema($table)
- {
- $ret = array();
- if (strpos($table, '.') !== false) {
- return explode('.', $table);
- }
- return array(null, $table);
- }
-
- // }}}
- // {{{ getFieldDeclarationList()
-
- /**
- * Get declaration of a number of field in bulk
- *
- * @param array $fields a multidimensional associative array.
- * The first dimension determines the field name, while the second
- * dimension is keyed with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * default
- * Boolean value to be used as default for this field.
- *
- * notnull
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- *
- * @return mixed string on success, a MDB2 error on failure
- * @access public
- */
- function getFieldDeclarationList($fields)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if (!is_array($fields) || empty($fields)) {
- return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'missing any fields', __FUNCTION__);
- }
- foreach ($fields as $field_name => $field) {
- $query = $db->getDeclaration($field['type'], $field_name, $field);
- if (PEAR::isError($query)) {
- return $query;
- }
- $query_fields[] = $query;
- }
- return implode(', ', $query_fields);
- }
-
- // }}}
- // {{{ _fixSequenceName()
-
- /**
- * Removes any formatting in an sequence name using the 'seqname_format' option
- *
- * @param string $sqn string that containts name of a potential sequence
- * @param bool $check if only formatted sequences should be returned
- * @return string name of the sequence with possible formatting removed
- * @access protected
- */
- function _fixSequenceName($sqn, $check = false)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $seq_pattern = '/^'.preg_replace('/%s/', '([a-z0-9_]+)', $db->options['seqname_format']).'$/i';
- $seq_name = preg_replace($seq_pattern, '\\1', $sqn);
- if ($seq_name && !strcasecmp($sqn, $db->getSequenceName($seq_name))) {
- return $seq_name;
- }
- if ($check) {
- return false;
- }
- return $sqn;
- }
-
- // }}}
- // {{{ _fixIndexName()
-
- /**
- * Removes any formatting in an index name using the 'idxname_format' option
- *
- * @param string $idx string that containts name of anl index
- * @return string name of the index with eventual formatting removed
- * @access protected
- */
- function _fixIndexName($idx)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $idx_pattern = '/^'.preg_replace('/%s/', '([a-z0-9_]+)', $db->options['idxname_format']).'$/i';
- $idx_name = preg_replace($idx_pattern, '\\1', $idx);
- if ($idx_name && !strcasecmp($idx, $db->getIndexName($idx_name))) {
- return $idx_name;
- }
- return $idx;
- }
-
- // }}}
- // {{{ createDatabase()
-
- /**
- * create a new database
- *
- * @param string $name name of the database that should be created
- * @param array $options array with charset, collation info
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function createDatabase($database, $options = array())
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ dropDatabase()
-
- /**
- * drop an existing database
- *
- * @param string $name name of the database that should be dropped
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function dropDatabase($database)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ _getCreateTableQuery()
-
- /**
- * Create a basic SQL query for a new table creation
- *
- * @param string $name Name of the database that should be created
- * @param array $fields Associative array that contains the definition of each field of the new table
- * @param array $options An associative array of table options
- *
- * @return mixed string (the SQL query) on success, a MDB2 error on failure
- * @see createTable()
- */
- function _getCreateTableQuery($name, $fields, $options = array())
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if (!$name) {
- return $db->raiseError(MDB2_ERROR_CANNOT_CREATE, null, null,
- 'no valid table name specified', __FUNCTION__);
- }
- if (empty($fields)) {
- return $db->raiseError(MDB2_ERROR_CANNOT_CREATE, null, null,
- 'no fields specified for table "'.$name.'"', __FUNCTION__);
- }
- $query_fields = $this->getFieldDeclarationList($fields);
- if (PEAR::isError($query_fields)) {
- return $query_fields;
- }
- if (!empty($options['primary'])) {
- $query_fields.= ', PRIMARY KEY ('.implode(', ', array_keys($options['primary'])).')';
- }
-
- $name = $db->quoteIdentifier($name, true);
- $result = 'CREATE ';
- if (!empty($options['temporary'])) {
- $result .= $this->_getTemporaryTableQuery();
- }
- $result .= " TABLE $name ($query_fields)";
- return $result;
- }
-
- // }}}
- // {{{ _getTemporaryTableQuery()
-
- /**
- * A method to return the required SQL string that fits between CREATE ... TABLE
- * to create the table as a temporary table.
- *
- * Should be overridden in driver classes to return the correct string for the
- * specific database type.
- *
- * The default is to return the string "TEMPORARY" - this will result in a
- * SQL error for any database that does not support temporary tables, or that
- * requires a different SQL command from "CREATE TEMPORARY TABLE".
- *
- * @return string The string required to be placed between "CREATE" and "TABLE"
- * to generate a temporary table, if possible.
- */
- function _getTemporaryTableQuery()
- {
- return 'TEMPORARY';
- }
-
- // }}}
- // {{{ createTable()
-
- /**
- * create a new table
- *
- * @param string $name Name of the database that should be created
- * @param array $fields Associative array that contains the definition of each field of the new table
- * The indexes of the array entries are the names of the fields of the table an
- * the array entry values are associative arrays like those that are meant to be
- * passed with the field definitions to get[Type]Declaration() functions.
- * array(
- * 'id' => array(
- * 'type' => 'integer',
- * 'unsigned' => 1
- * 'notnull' => 1
- * 'default' => 0
- * ),
- * 'name' => array(
- * 'type' => 'text',
- * 'length' => 12
- * ),
- * 'password' => array(
- * 'type' => 'text',
- * 'length' => 12
- * )
- * );
- * @param array $options An associative array of table options:
- * array(
- * 'comment' => 'Foo',
- * 'temporary' => true|false,
- * );
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function createTable($name, $fields, $options = array())
- {
- $query = $this->_getCreateTableQuery($name, $fields, $options);
- if (PEAR::isError($query)) {
- return $query;
- }
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- $result = $db->exec($query);
- if (PEAR::isError($result)) {
- return $result;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ dropTable()
-
- /**
- * drop an existing table
- *
- * @param string $name name of the table that should be dropped
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function dropTable($name)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $name = $db->quoteIdentifier($name, true);
- return $db->exec("DROP TABLE $name");
- }
-
- // }}}
- // {{{ alterTable()
-
- /**
- * alter an existing table
- *
- * @param string $name name of the table that is intended to be changed.
- * @param array $changes associative array that contains the details of each type
- * of change that is intended to be performed. The types of
- * changes that are currently supported are defined as follows:
- *
- * name
- *
- * New name for the table.
- *
- * add
- *
- * Associative array with the names of fields to be added as
- * indexes of the array. The value of each entry of the array
- * should be set to another associative array with the properties
- * of the fields to be added. The properties of the fields should
- * be the same as defined by the MDB2 parser.
- *
- *
- * remove
- *
- * Associative array with the names of fields to be removed as indexes
- * of the array. Currently the values assigned to each entry are ignored.
- * An empty array should be used for future compatibility.
- *
- * rename
- *
- * Associative array with the names of fields to be renamed as indexes
- * of the array. The value of each entry of the array should be set to
- * another associative array with the entry named name with the new
- * field name and the entry named Declaration that is expected to contain
- * the portion of the field declaration already in DBMS specific SQL code
- * as it is used in the CREATE TABLE statement.
- *
- * change
- *
- * Associative array with the names of the fields to be changed as indexes
- * of the array. Keep in mind that if it is intended to change either the
- * name of a field and any other properties, the change array entries
- * should have the new names of the fields as array indexes.
- *
- * The value of each entry of the array should be set to another associative
- * array with the properties of the fields to that are meant to be changed as
- * array entries. These entries should be assigned to the new values of the
- * respective properties. The properties of the fields should be the same
- * as defined by the MDB2 parser.
- *
- * Example
- * array(
- * 'name' => 'userlist',
- * 'add' => array(
- * 'quota' => array(
- * 'type' => 'integer',
- * 'unsigned' => 1
- * )
- * ),
- * 'remove' => array(
- * 'file_limit' => array(),
- * 'time_limit' => array()
- * ),
- * 'change' => array(
- * 'name' => array(
- * 'length' => '20',
- * 'definition' => array(
- * 'type' => 'text',
- * 'length' => 20,
- * ),
- * )
- * ),
- * 'rename' => array(
- * 'sex' => array(
- * 'name' => 'gender',
- * 'definition' => array(
- * 'type' => 'text',
- * 'length' => 1,
- * 'default' => 'M',
- * ),
- * )
- * )
- * )
- *
- * @param boolean $check indicates whether the function should just check if the DBMS driver
- * can perform the requested table alterations if the value is true or
- * actually perform them otherwise.
- * @access public
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- */
- function alterTable($name, $changes, $check)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ listDatabases()
-
- /**
- * list all databases
- *
- * @return mixed array of database names on success, a MDB2 error on failure
- * @access public
- */
- function listDatabases()
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implementedd', __FUNCTION__);
- }
-
- // }}}
- // {{{ listUsers()
-
- /**
- * list all users
- *
- * @return mixed array of user names on success, a MDB2 error on failure
- * @access public
- */
- function listUsers()
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ listViews()
-
- /**
- * list all views in the current database
- *
- * @param string database, the current is default
- * NB: not all the drivers can get the view names from
- * a database other than the current one
- * @return mixed array of view names on success, a MDB2 error on failure
- * @access public
- */
- function listViews($database = null)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ listTableViews()
-
- /**
- * list the views in the database that reference a given table
- *
- * @param string table for which all referenced views should be found
- * @return mixed array of view names on success, a MDB2 error on failure
- * @access public
- */
- function listTableViews($table)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ listTableTriggers()
-
- /**
- * list all triggers in the database that reference a given table
- *
- * @param string table for which all referenced triggers should be found
- * @return mixed array of trigger names on success, a MDB2 error on failure
- * @access public
- */
- function listTableTriggers($table = null)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ listFunctions()
-
- /**
- * list all functions in the current database
- *
- * @return mixed array of function names on success, a MDB2 error on failure
- * @access public
- */
- function listFunctions()
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ listTables()
-
- /**
- * list all tables in the current database
- *
- * @param string database, the current is default.
- * NB: not all the drivers can get the table names from
- * a database other than the current one
- * @return mixed array of table names on success, a MDB2 error on failure
- * @access public
- */
- function listTables($database = null)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ listTableFields()
-
- /**
- * list all fields in a table in the current database
- *
- * @param string $table name of table that should be used in method
- * @return mixed array of field names on success, a MDB2 error on failure
- * @access public
- */
- function listTableFields($table)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ createIndex()
-
- /**
- * Get the stucture of a field into an array
- *
- * @param string $table name of the table on which the index is to be created
- * @param string $name name of the index to be created
- * @param array $definition associative array that defines properties of the index to be created.
- * Currently, only one property named FIELDS is supported. This property
- * is also an associative with the names of the index fields as array
- * indexes. Each entry of this array is set to another type of associative
- * array that specifies properties of the index that are specific to
- * each field.
- *
- * Currently, only the sorting property is supported. It should be used
- * to define the sorting direction of the index. It may be set to either
- * ascending or descending.
- *
- * Not all DBMS support index sorting direction configuration. The DBMS
- * drivers of those that do not support it ignore this property. Use the
- * function supports() to determine whether the DBMS driver can manage indexes.
- *
- * Example
- * array(
- * 'fields' => array(
- * 'user_name' => array(
- * 'sorting' => 'ascending'
- * ),
- * 'last_login' => array()
- * )
- * )
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function createIndex($table, $name, $definition)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $table = $db->quoteIdentifier($table, true);
- $name = $db->quoteIdentifier($db->getIndexName($name), true);
- $query = "CREATE INDEX $name ON $table";
- $fields = array();
- foreach (array_keys($definition['fields']) as $field) {
- $fields[] = $db->quoteIdentifier($field, true);
- }
- $query .= ' ('. implode(', ', $fields) . ')';
- return $db->exec($query);
- }
-
- // }}}
- // {{{ dropIndex()
-
- /**
- * drop existing index
- *
- * @param string $table name of table that should be used in method
- * @param string $name name of the index to be dropped
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function dropIndex($table, $name)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $name = $db->quoteIdentifier($db->getIndexName($name), true);
- return $db->exec("DROP INDEX $name");
- }
-
- // }}}
- // {{{ listTableIndexes()
-
- /**
- * list all indexes in a table
- *
- * @param string $table name of table that should be used in method
- * @return mixed array of index names on success, a MDB2 error on failure
- * @access public
- */
- function listTableIndexes($table)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ _getAdvancedFKOptions()
-
- /**
- * Return the FOREIGN KEY query section dealing with non-standard options
- * as MATCH, INITIALLY DEFERRED, ON UPDATE, ...
- *
- * @param array $definition
- * @return string
- * @access protected
- */
- function _getAdvancedFKOptions($definition)
- {
- return '';
- }
-
- // }}}
- // {{{ createConstraint()
-
- /**
- * create a constraint on a table
- *
- * @param string $table name of the table on which the constraint is to be created
- * @param string $name name of the constraint to be created
- * @param array $definition associative array that defines properties of the constraint to be created.
- * The full structure of the array looks like this:
- * <pre>
- * array (
- * [primary] => 0
- * [unique] => 0
- * [foreign] => 1
- * [check] => 0
- * [fields] => array (
- * [field1name] => array() // one entry per each field covered
- * [field2name] => array() // by the index
- * [field3name] => array(
- * [sorting] => ascending
- * [position] => 3
- * )
- * )
- * [references] => array(
- * [table] => name
- * [fields] => array(
- * [field1name] => array( //one entry per each referenced field
- * [position] => 1
- * )
- * )
- * )
- * [deferrable] => 0
- * [initiallydeferred] => 0
- * [onupdate] => CASCADE|RESTRICT|SET NULL|SET DEFAULT|NO ACTION
- * [ondelete] => CASCADE|RESTRICT|SET NULL|SET DEFAULT|NO ACTION
- * [match] => SIMPLE|PARTIAL|FULL
- * );
- * </pre>
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function createConstraint($table, $name, $definition)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- $table = $db->quoteIdentifier($table, true);
- $name = $db->quoteIdentifier($db->getIndexName($name), true);
- $query = "ALTER TABLE $table ADD CONSTRAINT $name";
- if (!empty($definition['primary'])) {
- $query.= ' PRIMARY KEY';
- } elseif (!empty($definition['unique'])) {
- $query.= ' UNIQUE';
- } elseif (!empty($definition['foreign'])) {
- $query.= ' FOREIGN KEY';
- }
- $fields = array();
- foreach (array_keys($definition['fields']) as $field) {
- $fields[] = $db->quoteIdentifier($field, true);
- }
- $query .= ' ('. implode(', ', $fields) . ')';
- if (!empty($definition['foreign'])) {
- $query.= ' REFERENCES ' . $db->quoteIdentifier($definition['references']['table'], true);
- $referenced_fields = array();
- foreach (array_keys($definition['references']['fields']) as $field) {
- $referenced_fields[] = $db->quoteIdentifier($field, true);
- }
- $query .= ' ('. implode(', ', $referenced_fields) . ')';
- $query .= $this->_getAdvancedFKOptions($definition);
- }
- return $db->exec($query);
- }
-
- // }}}
- // {{{ dropConstraint()
-
- /**
- * drop existing constraint
- *
- * @param string $table name of table that should be used in method
- * @param string $name name of the constraint to be dropped
- * @param string $primary hint if the constraint is primary
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function dropConstraint($table, $name, $primary = false)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $table = $db->quoteIdentifier($table, true);
- $name = $db->quoteIdentifier($db->getIndexName($name), true);
- return $db->exec("ALTER TABLE $table DROP CONSTRAINT $name");
- }
-
- // }}}
- // {{{ listTableConstraints()
-
- /**
- * list all constraints in a table
- *
- * @param string $table name of table that should be used in method
- * @return mixed array of constraint names on success, a MDB2 error on failure
- * @access public
- */
- function listTableConstraints($table)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ createSequence()
-
- /**
- * create sequence
- *
- * @param string $seq_name name of the sequence to be created
- * @param string $start start value of the sequence; default is 1
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function createSequence($seq_name, $start = 1)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ dropSequence()
-
- /**
- * drop existing sequence
- *
- * @param string $seq_name name of the sequence to be dropped
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function dropSequence($name)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ listSequences()
-
- /**
- * list all sequences in the current database
- *
- * @param string database, the current is default
- * NB: not all the drivers can get the sequence names from
- * a database other than the current one
- * @return mixed array of sequence names on success, a MDB2 error on failure
- * @access public
- */
- function listSequences($database = null)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2007 Manuel Lemos, Tomas V.V.Cox, |
-// | Stig. S. Bakken, Lukas Smith |
-// | All rights reserved. |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
-// | API as well as database abstraction for PHP applications. |
-// | This LICENSE is in the BSD license style. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | |
-// | Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution. |
-// | |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
-// | POSSIBILITY OF SUCH DAMAGE. |
-// +----------------------------------------------------------------------+
-// | Author: Paul Cooper <pgc@ucecom.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: pgsql.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
-
-require_once 'MDB2/Driver/Manager/Common.php';
-
-/**
- * MDB2 MySQL driver for the management modules
- *
- * @package MDB2
- * @category Database
- * @author Paul Cooper <pgc@ucecom.com>
- */
-class MDB2_Driver_Manager_pgsql extends MDB2_Driver_Manager_Common
-{
- // {{{ createDatabase()
-
- /**
- * create a new database
- *
- * @param string $name name of the database that should be created
- * @param array $options array with charset info
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function createDatabase($name, $options = array())
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $name = $db->quoteIdentifier($name, true);
- $query = 'CREATE DATABASE ' . $name;
- if (!empty($options['charset'])) {
- $query .= ' WITH ENCODING ' . $db->quote($options['charset'], 'text');
- }
- return $db->standaloneQuery($query, null, true);
- }
-
- // }}}
- // {{{ dropDatabase()
-
- /**
- * drop an existing database
- *
- * @param string $name name of the database that should be dropped
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function dropDatabase($name)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $name = $db->quoteIdentifier($name, true);
- return $db->standaloneQuery("DROP DATABASE $name", null, true);
- }
-
- // }}}
- // {{{ _getAdvancedFKOptions()
-
- /**
- * Return the FOREIGN KEY query section dealing with non-standard options
- * as MATCH, INITIALLY DEFERRED, ON UPDATE, ...
- *
- * @param array $definition
- * @return string
- * @access protected
- */
- function _getAdvancedFKOptions($definition)
- {
- $query = '';
- if (!empty($definition['match'])) {
- $query .= ' MATCH '.$definition['match'];
- }
- if (!empty($definition['onupdate'])) {
- $query .= ' ON UPDATE '.$definition['onupdate'];
- }
- if (!empty($definition['ondelete'])) {
- $query .= ' ON DELETE '.$definition['ondelete'];
- }
- if (!empty($definition['deferrable'])) {
- $query .= ' DEFERRABLE';
- } else {
- $query .= ' NOT DEFERRABLE';
- }
- if (!empty($definition['initiallydeferred'])) {
- $query .= ' INITIALLY DEFERRED';
- } else {
- $query .= ' INITIALLY IMMEDIATE';
- }
- return $query;
- }
-
- // }}}
- // {{{ alterTable()
-
- /**
- * alter an existing table
- *
- * @param string $name name of the table that is intended to be changed.
- * @param array $changes associative array that contains the details of each type
- * of change that is intended to be performed. The types of
- * changes that are currently supported are defined as follows:
- *
- * name
- *
- * New name for the table.
- *
- * add
- *
- * Associative array with the names of fields to be added as
- * indexes of the array. The value of each entry of the array
- * should be set to another associative array with the properties
- * of the fields to be added. The properties of the fields should
- * be the same as defined by the MDB2 parser.
- *
- *
- * remove
- *
- * Associative array with the names of fields to be removed as indexes
- * of the array. Currently the values assigned to each entry are ignored.
- * An empty array should be used for future compatibility.
- *
- * rename
- *
- * Associative array with the names of fields to be renamed as indexes
- * of the array. The value of each entry of the array should be set to
- * another associative array with the entry named name with the new
- * field name and the entry named Declaration that is expected to contain
- * the portion of the field declaration already in DBMS specific SQL code
- * as it is used in the CREATE TABLE statement.
- *
- * change
- *
- * Associative array with the names of the fields to be changed as indexes
- * of the array. Keep in mind that if it is intended to change either the
- * name of a field and any other properties, the change array entries
- * should have the new names of the fields as array indexes.
- *
- * The value of each entry of the array should be set to another associative
- * array with the properties of the fields to that are meant to be changed as
- * array entries. These entries should be assigned to the new values of the
- * respective properties. The properties of the fields should be the same
- * as defined by the MDB2 parser.
- *
- * Example
- * array(
- * 'name' => 'userlist',
- * 'add' => array(
- * 'quota' => array(
- * 'type' => 'integer',
- * 'unsigned' => 1
- * )
- * ),
- * 'remove' => array(
- * 'file_limit' => array(),
- * 'time_limit' => array()
- * ),
- * 'change' => array(
- * 'name' => array(
- * 'length' => '20',
- * 'definition' => array(
- * 'type' => 'text',
- * 'length' => 20,
- * ),
- * )
- * ),
- * 'rename' => array(
- * 'sex' => array(
- * 'name' => 'gender',
- * 'definition' => array(
- * 'type' => 'text',
- * 'length' => 1,
- * 'default' => 'M',
- * ),
- * )
- * )
- * )
- *
- * @param boolean $check indicates whether the function should just check if the DBMS driver
- * can perform the requested table alterations if the value is true or
- * actually perform them otherwise.
- * @access public
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- */
- function alterTable($name, $changes, $check)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- foreach ($changes as $change_name => $change) {
- switch ($change_name) {
- case 'add':
- case 'remove':
- case 'change':
- case 'name':
- case 'rename':
- break;
- default:
- return $db->raiseError(MDB2_ERROR_CANNOT_ALTER, null, null,
- 'change type "'.$change_name.'\" not yet supported', __FUNCTION__);
- }
- }
-
- if ($check) {
- return MDB2_OK;
- }
-
- if (!empty($changes['add']) && is_array($changes['add'])) {
- foreach ($changes['add'] as $field_name => $field) {
- $query = 'ADD ' . $db->getDeclaration($field['type'], $field_name, $field);
- $result = $db->exec("ALTER TABLE $name $query");
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- }
-
- if (!empty($changes['remove']) && is_array($changes['remove'])) {
- foreach ($changes['remove'] as $field_name => $field) {
- $field_name = $db->quoteIdentifier($field_name, true);
- $query = 'DROP ' . $field_name;
- $result = $db->exec("ALTER TABLE $name $query");
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- }
-
- if (!empty($changes['change']) && is_array($changes['change'])) {
- foreach ($changes['change'] as $field_name => $field) {
- $field_name = $db->quoteIdentifier($field_name, true);
- if (!empty($field['definition']['type'])) {
- $server_info = $db->getServerVersion();
- if (PEAR::isError($server_info)) {
- return $server_info;
- }
- if (is_array($server_info) && $server_info['major'] < 8) {
- return $db->raiseError(MDB2_ERROR_CANNOT_ALTER, null, null,
- 'changing column type for "'.$change_name.'\" requires PostgreSQL 8.0 or above', __FUNCTION__);
- }
- $db->loadModule('Datatype', null, true);
- $query = "ALTER $field_name TYPE ".$db->datatype->getTypeDeclaration($field['definition']);
- $result = $db->exec("ALTER TABLE $name $query");
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- if (array_key_exists('default', $field['definition'])) {
- $query = "ALTER $field_name SET DEFAULT ".$db->quote($field['definition']['default'], $field['definition']['type']);
- $result = $db->exec("ALTER TABLE $name $query");
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- if (!empty($field['definition']['notnull'])) {
- $query = "ALTER $field_name ".($field['definition']['notnull'] ? 'SET' : 'DROP').' NOT NULL';
- $result = $db->exec("ALTER TABLE $name $query");
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- }
- }
-
- if (!empty($changes['rename']) && is_array($changes['rename'])) {
- foreach ($changes['rename'] as $field_name => $field) {
- $field_name = $db->quoteIdentifier($field_name, true);
- $result = $db->exec("ALTER TABLE $name RENAME COLUMN $field_name TO ".$db->quoteIdentifier($field['name'], true));
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- }
-
- $name = $db->quoteIdentifier($name, true);
- if (!empty($changes['name'])) {
- $change_name = $db->quoteIdentifier($changes['name'], true);
- $result = $db->exec("ALTER TABLE $name RENAME TO ".$change_name);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
-
- return MDB2_OK;
- }
-
- // }}}
- // {{{ listDatabases()
-
- /**
- * list all databases
- *
- * @return mixed array of database names on success, a MDB2 error on failure
- * @access public
- */
- function listDatabases()
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = 'SELECT datname FROM pg_database';
- $result2 = $db->standaloneQuery($query, array('text'), false);
- if (!MDB2::isResultCommon($result2)) {
- return $result2;
- }
-
- $result = $result2->fetchCol();
- $result2->free();
- if (PEAR::isError($result)) {
- return $result;
- }
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
- }
- return $result;
- }
-
- // }}}
- // {{{ listUsers()
-
- /**
- * list all users
- *
- * @return mixed array of user names on success, a MDB2 error on failure
- * @access public
- */
- function listUsers()
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = 'SELECT usename FROM pg_user';
- $result2 = $db->standaloneQuery($query, array('text'), false);
- if (!MDB2::isResultCommon($result2)) {
- return $result2;
- }
-
- $result = $result2->fetchCol();
- $result2->free();
- return $result;
- }
-
- // }}}
- // {{{ listViews()
-
- /**
- * list all views in the current database
- *
- * @return mixed array of view names on success, a MDB2 error on failure
- * @access public
- */
- function listViews()
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = "SELECT viewname
- FROM pg_views
- WHERE schemaname NOT IN ('pg_catalog', 'information_schema')
- AND viewname !~ '^pg_'";
- $result = $db->queryCol($query);
- if (PEAR::isError($result)) {
- return $result;
- }
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
- }
- return $result;
- }
-
- // }}}
- // {{{ listTableViews()
-
- /**
- * list the views in the database that reference a given table
- *
- * @param string table for which all referenced views should be found
- * @return mixed array of view names on success, a MDB2 error on failure
- * @access public
- */
- function listTableViews($table)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = 'SELECT viewname FROM pg_views NATURAL JOIN pg_tables';
- $query.= ' WHERE tablename ='.$db->quote($table, 'text');
- $result = $db->queryCol($query);
- if (PEAR::isError($result)) {
- return $result;
- }
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
- }
- return $result;
- }
-
- // }}}
- // {{{ listFunctions()
-
- /**
- * list all functions in the current database
- *
- * @return mixed array of function names on success, a MDB2 error on failure
- * @access public
- */
- function listFunctions()
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = "
- SELECT
- proname
- FROM
- pg_proc pr,
- pg_type tp
- WHERE
- tp.oid = pr.prorettype
- AND pr.proisagg = FALSE
- AND tp.typname <> 'trigger'
- AND pr.pronamespace IN
- (SELECT oid FROM pg_namespace WHERE nspname NOT LIKE 'pg_%' AND nspname != 'information_schema')";
- $result = $db->queryCol($query);
- if (PEAR::isError($result)) {
- return $result;
- }
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
- }
- return $result;
- }
-
- // }}}
- // {{{ listTableTriggers()
-
- /**
- * list all triggers in the database that reference a given table
- *
- * @param string table for which all referenced triggers should be found
- * @return mixed array of trigger names on success, a MDB2 error on failure
- * @access public
- */
- function listTableTriggers($table = null)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = 'SELECT trg.tgname AS trigger_name
- FROM pg_trigger trg,
- pg_class tbl
- WHERE trg.tgrelid = tbl.oid';
- if (!is_null($table)) {
- $table = $db->quote(strtoupper($table), 'text');
- $query .= " AND tbl.relname = $table";
- }
- $result = $db->queryCol($query);
- if (PEAR::isError($result)) {
- return $result;
- }
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
- }
- return $result;
- }
-
- // }}}
- // {{{ listTables()
-
- /**
- * list all tables in the current database
- *
- * @return mixed array of table names on success, a MDB2 error on failure
- * @access public
- */
- function listTables()
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- // gratuitously stolen from PEAR DB _getSpecialQuery in pgsql.php
- $query = 'SELECT c.relname AS "Name"'
- . ' FROM pg_class c, pg_user u'
- . ' WHERE c.relowner = u.usesysid'
- . " AND c.relkind = 'r'"
- . ' AND NOT EXISTS'
- . ' (SELECT 1 FROM pg_views'
- . ' WHERE viewname = c.relname)'
- . " AND c.relname !~ '^(pg_|sql_)'"
- . ' UNION'
- . ' SELECT c.relname AS "Name"'
- . ' FROM pg_class c'
- . " WHERE c.relkind = 'r'"
- . ' AND NOT EXISTS'
- . ' (SELECT 1 FROM pg_views'
- . ' WHERE viewname = c.relname)'
- . ' AND NOT EXISTS'
- . ' (SELECT 1 FROM pg_user'
- . ' WHERE usesysid = c.relowner)'
- . " AND c.relname !~ '^pg_'";
- $result = $db->queryCol($query);
- if (PEAR::isError($result)) {
- return $result;
- }
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
- }
- return $result;
- }
-
- // }}}
- // {{{ listTableFields()
-
- /**
- * list all fields in a table in the current database
- *
- * @param string $table name of table that should be used in method
- * @return mixed array of field names on success, a MDB2 error on failure
- * @access public
- */
- function listTableFields($table)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $table = $db->quoteIdentifier($table, true);
- $db->setLimit(1);
- $result2 = $db->query("SELECT * FROM $table");
- if (PEAR::isError($result2)) {
- return $result2;
- }
- $result = $result2->getColumnNames();
- $result2->free();
- if (PEAR::isError($result)) {
- return $result;
- }
- return array_flip($result);
- }
-
- // }}}
- // {{{ listTableIndexes()
-
- /**
- * list all indexes in a table
- *
- * @param string $table name of table that should be used in method
- * @return mixed array of index names on success, a MDB2 error on failure
- * @access public
- */
- function listTableIndexes($table)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $table = $db->quote($table, 'text');
- $subquery = "SELECT indexrelid FROM pg_index, pg_class";
- $subquery.= " WHERE pg_class.relname=$table AND pg_class.oid=pg_index.indrelid AND indisunique != 't' AND indisprimary != 't'";
- $query = "SELECT relname FROM pg_class WHERE oid IN ($subquery)";
- $indexes = $db->queryCol($query, 'text');
- if (PEAR::isError($indexes)) {
- return $indexes;
- }
-
- $result = array();
- foreach ($indexes as $index) {
- $index = $this->_fixIndexName($index);
- if (!empty($index)) {
- $result[$index] = true;
- }
- }
-
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_change_key_case($result, $db->options['field_case']);
- }
- return array_keys($result);
- }
-
- // }}}
- // {{{ listTableConstraints()
-
- /**
- * list all constraints in a table
- *
- * @param string $table name of table that should be used in method
- * @return mixed array of constraint names on success, a MDB2 error on failure
- * @access public
- */
- function listTableConstraints($table)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $table = $db->quote($table, 'text');
- $subquery = "SELECT indexrelid FROM pg_index, pg_class";
- $subquery.= " WHERE pg_class.relname=$table AND pg_class.oid=pg_index.indrelid AND (indisunique = 't' OR indisprimary = 't')";
- $query = "SELECT relname FROM pg_class WHERE oid IN ($subquery)";
- $constraints = $db->queryCol($query);
- if (PEAR::isError($constraints)) {
- return $constraints;
- }
-
- $result = array();
- foreach ($constraints as $constraint) {
- $constraint = $this->_fixIndexName($constraint);
- if (!empty($constraint)) {
- $result[$constraint] = true;
- }
- }
-
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE
- && $db->options['field_case'] == CASE_LOWER
- ) {
- $result = array_change_key_case($result, $db->options['field_case']);
- }
- return array_keys($result);
- }
-
- // }}}
- // {{{ createSequence()
-
- /**
- * create sequence
- *
- * @param string $seq_name name of the sequence to be created
- * @param string $start start value of the sequence; default is 1
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function createSequence($seq_name, $start = 1)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $sequence_name = $db->quoteIdentifier($db->getSequenceName($seq_name), true);
- return $db->exec("CREATE SEQUENCE $sequence_name INCREMENT 1".
- ($start < 1 ? " MINVALUE $start" : '')." START $start");
- }
-
- // }}}
- // {{{ dropSequence()
-
- /**
- * drop existing sequence
- *
- * @param string $seq_name name of the sequence to be dropped
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function dropSequence($seq_name)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $sequence_name = $db->quoteIdentifier($db->getSequenceName($seq_name), true);
- return $db->exec("DROP SEQUENCE $sequence_name");
- }
-
- // }}}
- // {{{ listSequences()
-
- /**
- * list all sequences in the current database
- *
- * @return mixed array of sequence names on success, a MDB2 error on failure
- * @access public
- */
- function listSequences()
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = "SELECT relname FROM pg_class WHERE relkind = 'S' AND relnamespace IN";
- $query.= "(SELECT oid FROM pg_namespace WHERE nspname NOT LIKE 'pg_%' AND nspname != 'information_schema')";
- $table_names = $db->queryCol($query);
- if (PEAR::isError($table_names)) {
- return $table_names;
- }
- $result = array();
- foreach ($table_names as $table_name) {
- $result[] = $this->_fixSequenceName($table_name);
- }
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
- }
- return $result;
- }
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2006 Manuel Lemos, Tomas V.V.Cox, |
-// | Stig. S. Bakken, Lukas Smith |
-// | All rights reserved. |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
-// | API as well as database abstraction for PHP applications. |
-// | This LICENSE is in the BSD license style. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | |
-// | Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution. |
-// | |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
-// | POSSIBILITY OF SUCH DAMAGE. |
-// +----------------------------------------------------------------------+
-// | Author: Lukas Smith <smith@pooteeweet.org> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Common.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
-//
-
-/**
- * Base class for the natuve modules that is extended by each MDB2 driver
- *
- * To load this module in the MDB2 object:
- * $mdb->loadModule('Native');
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Driver_Native_Common extends MDB2_Module_Common
-{
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2006 Manuel Lemos, Tomas V.V.Cox, |
-// | Stig. S. Bakken, Lukas Smith |
-// | All rights reserved. |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
-// | API as well as database abstraction for PHP applications. |
-// | This LICENSE is in the BSD license style. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | |
-// | Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution. |
-// | |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
-// | POSSIBILITY OF SUCH DAMAGE. |
-// +----------------------------------------------------------------------+
-// | Author: Paul Cooper <pgc@ucecom.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: pgsql.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
-
-require_once 'MDB2/Driver/Native/Common.php';
-
-/**
- * MDB2 PostGreSQL driver for the native module
- *
- * @package MDB2
- * @category Database
- * @author Paul Cooper <pgc@ucecom.com>
- */
-class MDB2_Driver_Native_pgsql extends MDB2_Driver_Native_Common
-{
- // }}}
- // {{{ deleteOID()
-
- /**
- * delete an OID
- *
- * @param integer $OID
- * @return mixed MDB2_OK on success or MDB2 Error Object on failure
- * @access public
- */
- function deleteOID($OID)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $connection = $db->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
-
- if (!@pg_lo_unlink($connection, $OID)) {
- return $db->raiseError(null, null, null,
- 'Unable to unlink OID: '.$OID, __FUNCTION__);
- }
- return MDB2_OK;
- }
-
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2007 Manuel Lemos, Tomas V.V.Cox, |
-// | Stig. S. Bakken, Lukas Smith |
-// | All rights reserved. |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
-// | API as well as database abstraction for PHP applications. |
-// | This LICENSE is in the BSD license style. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | |
-// | Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution. |
-// | |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
-// | POSSIBILITY OF SUCH DAMAGE. |
-// +----------------------------------------------------------------------+
-// | Author: Lukas Smith <smith@pooteeweet.org> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Common.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
-//
-
-/**
- * @package MDB2
- * @category Database
- */
-
-/**
- * These are constants for the tableInfo-function
- * they are bitwised or'ed. so if there are more constants to be defined
- * in the future, adjust MDB2_TABLEINFO_FULL accordingly
- */
-
-define('MDB2_TABLEINFO_ORDER', 1);
-define('MDB2_TABLEINFO_ORDERTABLE', 2);
-define('MDB2_TABLEINFO_FULL', 3);
-
-/**
- * Base class for the schema reverse engineering module that is extended by each MDB2 driver
- *
- * To load this module in the MDB2 object:
- * $mdb->loadModule('Reverse');
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Driver_Reverse_Common extends MDB2_Module_Common
-{
- // {{{ splitTableSchema()
-
- /**
- * Split the "[owner|schema].table" notation into an array
- * @access private
- */
- function splitTableSchema($table)
- {
- $ret = array();
- if (strpos($table, '.') !== false) {
- return explode('.', $table);
- }
- return array(null, $table);
- }
-
- // }}}
- // {{{ getTableFieldDefinition()
-
- /**
- * Get the structure of a field into an array
- *
- * @param string $table name of table that should be used in method
- * @param string $field name of field that should be used in method
- * @return mixed data array on success, a MDB2 error on failure.
- * The returned array contains an array for each field definition,
- * with all or some of these indices, depending on the field data type:
- * [notnull] [nativetype] [length] [fixed] [default] [type] [mdb2type]
- * @access public
- */
- function getTableFieldDefinition($table, $field)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ getTableIndexDefinition()
-
- /**
- * Get the structure of an index into an array
- *
- * @param string $table name of table that should be used in method
- * @param string $index name of index that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * The returned array has this structure:
- * </pre>
- * array (
- * [fields] => array (
- * [field1name] => array() // one entry per each field covered
- * [field2name] => array() // by the index
- * [field3name] => array(
- * [sorting] => ascending
- * )
- * )
- * );
- * </pre>
- * @access public
- */
- function getTableIndexDefinition($table, $index)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ getTableConstraintDefinition()
-
- /**
- * Get the structure of an constraints into an array
- *
- * @param string $table name of table that should be used in method
- * @param string $index name of index that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * The returned array has this structure:
- * <pre>
- * array (
- * [primary] => 0
- * [unique] => 0
- * [foreign] => 1
- * [check] => 0
- * [fields] => array (
- * [field1name] => array() // one entry per each field covered
- * [field2name] => array() // by the index
- * [field3name] => array(
- * [sorting] => ascending
- * [position] => 3
- * )
- * )
- * [references] => array(
- * [table] => name
- * [fields] => array(
- * [field1name] => array( //one entry per each referenced field
- * [position] => 1
- * )
- * )
- * )
- * [deferrable] => 0
- * [initiallydeferred] => 0
- * [onupdate] => CASCADE|RESTRICT|SET NULL|SET DEFAULT|NO ACTION
- * [ondelete] => CASCADE|RESTRICT|SET NULL|SET DEFAULT|NO ACTION
- * [match] => SIMPLE|PARTIAL|FULL
- * );
- * </pre>
- * @access public
- */
- function getTableConstraintDefinition($table, $index)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ getSequenceDefinition()
-
- /**
- * Get the structure of a sequence into an array
- *
- * @param string $sequence name of sequence that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * The returned array has this structure:
- * <pre>
- * array (
- * [start] => n
- * );
- * </pre>
- * @access public
- */
- function getSequenceDefinition($sequence)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $start = $db->currId($sequence);
- if (PEAR::isError($start)) {
- return $start;
- }
- if ($db->supports('current_id')) {
- $start++;
- } else {
- $db->warnings[] = 'database does not support getting current
- sequence value, the sequence value was incremented';
- }
- $definition = array();
- if ($start != 1) {
- $definition = array('start' => $start);
- }
- return $definition;
- }
-
- // }}}
- // {{{ getTriggerDefinition()
-
- /**
- * Get the structure of a trigger into an array
- *
- * EXPERIMENTAL
- *
- * WARNING: this function is experimental and may change the returned value
- * at any time until labelled as non-experimental
- *
- * @param string $trigger name of trigger that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * The returned array has this structure:
- * <pre>
- * array (
- * [trigger_name] => 'trigger name',
- * [table_name] => 'table name',
- * [trigger_body] => 'trigger body definition',
- * [trigger_type] => 'BEFORE' | 'AFTER',
- * [trigger_event] => 'INSERT' | 'UPDATE' | 'DELETE'
- * //or comma separated list of multiple events, when supported
- * [trigger_enabled] => true|false
- * [trigger_comment] => 'trigger comment',
- * );
- * </pre>
- * The oci8 driver also returns a [when_clause] index.
- * @access public
- */
- function getTriggerDefinition($trigger)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ tableInfo()
-
- /**
- * Returns information about a table or a result set
- *
- * The format of the resulting array depends on which <var>$mode</var>
- * you select. The sample output below is based on this query:
- * <pre>
- * SELECT tblFoo.fldID, tblFoo.fldPhone, tblBar.fldId
- * FROM tblFoo
- * JOIN tblBar ON tblFoo.fldId = tblBar.fldId
- * </pre>
- *
- * <ul>
- * <li>
- *
- * <kbd>null</kbd> (default)
- * <pre>
- * [0] => Array (
- * [table] => tblFoo
- * [name] => fldId
- * [type] => int
- * [len] => 11
- * [flags] => primary_key not_null
- * )
- * [1] => Array (
- * [table] => tblFoo
- * [name] => fldPhone
- * [type] => string
- * [len] => 20
- * [flags] =>
- * )
- * [2] => Array (
- * [table] => tblBar
- * [name] => fldId
- * [type] => int
- * [len] => 11
- * [flags] => primary_key not_null
- * )
- * </pre>
- *
- * </li><li>
- *
- * <kbd>MDB2_TABLEINFO_ORDER</kbd>
- *
- * <p>In addition to the information found in the default output,
- * a notation of the number of columns is provided by the
- * <samp>num_fields</samp> element while the <samp>order</samp>
- * element provides an array with the column names as the keys and
- * their location index number (corresponding to the keys in the
- * the default output) as the values.</p>
- *
- * <p>If a result set has identical field names, the last one is
- * used.</p>
- *
- * <pre>
- * [num_fields] => 3
- * [order] => Array (
- * [fldId] => 2
- * [fldTrans] => 1
- * )
- * </pre>
- *
- * </li><li>
- *
- * <kbd>MDB2_TABLEINFO_ORDERTABLE</kbd>
- *
- * <p>Similar to <kbd>MDB2_TABLEINFO_ORDER</kbd> but adds more
- * dimensions to the array in which the table names are keys and
- * the field names are sub-keys. This is helpful for queries that
- * join tables which have identical field names.</p>
- *
- * <pre>
- * [num_fields] => 3
- * [ordertable] => Array (
- * [tblFoo] => Array (
- * [fldId] => 0
- * [fldPhone] => 1
- * )
- * [tblBar] => Array (
- * [fldId] => 2
- * )
- * )
- * </pre>
- *
- * </li>
- * </ul>
- *
- * The <samp>flags</samp> element contains a space separated list
- * of extra information about the field. This data is inconsistent
- * between DBMS's due to the way each DBMS works.
- * + <samp>primary_key</samp>
- * + <samp>unique_key</samp>
- * + <samp>multiple_key</samp>
- * + <samp>not_null</samp>
- *
- * Most DBMS's only provide the <samp>table</samp> and <samp>flags</samp>
- * elements if <var>$result</var> is a table name. The following DBMS's
- * provide full information from queries:
- * + fbsql
- * + mysql
- *
- * If the 'portability' option has <samp>MDB2_PORTABILITY_FIX_CASE</samp>
- * turned on, the names of tables and fields will be lower or upper cased.
- *
- * @param object|string $result MDB2_result object from a query or a
- * string containing the name of a table.
- * While this also accepts a query result
- * resource identifier, this behavior is
- * deprecated.
- * @param int $mode either unused or one of the tableInfo modes:
- * <kbd>MDB2_TABLEINFO_ORDERTABLE</kbd>,
- * <kbd>MDB2_TABLEINFO_ORDER</kbd> or
- * <kbd>MDB2_TABLEINFO_FULL</kbd> (which does both).
- * These are bitwise, so the first two can be
- * combined using <kbd>|</kbd>.
- *
- * @return array an associative array with the information requested.
- * A MDB2_Error object on failure.
- *
- * @see MDB2_Driver_Common::setOption()
- */
- function tableInfo($result, $mode = null)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if (!is_string($result)) {
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- $db->loadModule('Manager', null, true);
- $fields = $db->manager->listTableFields($result);
- if (PEAR::isError($fields)) {
- return $fields;
- }
-
- $flags = array();
-
- $idxname_format = $db->getOption('idxname_format');
- $db->setOption('idxname_format', '%s');
-
- $indexes = $db->manager->listTableIndexes($result);
- if (PEAR::isError($indexes)) {
- $db->setOption('idxname_format', $idxname_format);
- return $indexes;
- }
-
- foreach ($indexes as $index) {
- $definition = $this->getTableIndexDefinition($result, $index);
- if (PEAR::isError($definition)) {
- $db->setOption('idxname_format', $idxname_format);
- return $definition;
- }
- if (count($definition['fields']) > 1) {
- foreach ($definition['fields'] as $field => $sort) {
- $flags[$field] = 'multiple_key';
- }
- }
- }
-
- $constraints = $db->manager->listTableConstraints($result);
- if (PEAR::isError($constraints)) {
- return $constraints;
- }
-
- foreach ($constraints as $constraint) {
- $definition = $this->getTableConstraintDefinition($result, $constraint);
- if (PEAR::isError($definition)) {
- $db->setOption('idxname_format', $idxname_format);
- return $definition;
- }
- $flag = !empty($definition['primary'])
- ? 'primary_key' : (!empty($definition['unique'])
- ? 'unique_key' : false);
- if ($flag) {
- foreach ($definition['fields'] as $field => $sort) {
- if (empty($flags[$field]) || $flags[$field] != 'primary_key') {
- $flags[$field] = $flag;
- }
- }
- }
- }
-
- if ($mode) {
- $res['num_fields'] = count($fields);
- }
-
- foreach ($fields as $i => $field) {
- $definition = $this->getTableFieldDefinition($result, $field);
- if (PEAR::isError($definition)) {
- $db->setOption('idxname_format', $idxname_format);
- return $definition;
- }
- $res[$i] = $definition[0];
- $res[$i]['name'] = $field;
- $res[$i]['table'] = $result;
- $res[$i]['type'] = preg_replace('/^([a-z]+).*$/i', '\\1', trim($definition[0]['nativetype']));
- // 'primary_key', 'unique_key', 'multiple_key'
- $res[$i]['flags'] = empty($flags[$field]) ? '' : $flags[$field];
- // not_null', 'unsigned', 'auto_increment', 'default_[rawencodedvalue]'
- if (!empty($res[$i]['notnull'])) {
- $res[$i]['flags'].= ' not_null';
- }
- if (!empty($res[$i]['unsigned'])) {
- $res[$i]['flags'].= ' unsigned';
- }
- if (!empty($res[$i]['auto_increment'])) {
- $res[$i]['flags'].= ' autoincrement';
- }
- if (!empty($res[$i]['default'])) {
- $res[$i]['flags'].= ' default_'.rawurlencode($res[$i]['default']);
- }
-
- if ($mode & MDB2_TABLEINFO_ORDER) {
- $res['order'][$res[$i]['name']] = $i;
- }
- if ($mode & MDB2_TABLEINFO_ORDERTABLE) {
- $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
- }
- }
-
- $db->setOption('idxname_format', $idxname_format);
- return $res;
- }
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2007 Manuel Lemos, Tomas V.V.Cox, |
-// | Stig. S. Bakken, Lukas Smith |
-// | All rights reserved. |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
-// | API as well as database abstraction for PHP applications. |
-// | This LICENSE is in the BSD license style. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | |
-// | Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution. |
-// | |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
-// | POSSIBILITY OF SUCH DAMAGE. |
-// +----------------------------------------------------------------------+
-// | Authors: Paul Cooper <pgc@ucecom.com> |
-// | Lorenzo Alberton <l.alberton@quipo.it> |
-// +----------------------------------------------------------------------+
-//
-// $Id: pgsql.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
-
-require_once 'MDB2/Driver/Reverse/Common.php';
-
-/**
- * MDB2 PostGreSQL driver for the schema reverse engineering module
- *
- * @package MDB2
- * @category Database
- * @author Paul Cooper <pgc@ucecom.com>
- * @author Lorenzo Alberton <l.alberton@quipo.it>
- */
-class MDB2_Driver_Reverse_pgsql extends MDB2_Driver_Reverse_Common
-{
- // {{{ getTableFieldDefinition()
-
- /**
- * Get the structure of a field into an array
- *
- * @param string $table_name name of table that should be used in method
- * @param string $field_name name of field that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * @access public
- */
- function getTableFieldDefinition($table_name, $field_name)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $result = $db->loadModule('Datatype', null, true);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- list($schema, $table) = $this->splitTableSchema($table_name);
-
- $query = "SELECT a.attname AS name,
- t.typname AS type,
- CASE a.attlen
- WHEN -1 THEN
- CASE t.typname
- WHEN 'numeric' THEN (a.atttypmod / 65536)
- WHEN 'decimal' THEN (a.atttypmod / 65536)
- WHEN 'money' THEN (a.atttypmod / 65536)
- ELSE CASE a.atttypmod
- WHEN -1 THEN NULL
- ELSE a.atttypmod - 4
- END
- END
- ELSE a.attlen
- END AS length,
- CASE t.typname
- WHEN 'numeric' THEN (a.atttypmod % 65536) - 4
- WHEN 'decimal' THEN (a.atttypmod % 65536) - 4
- WHEN 'money' THEN (a.atttypmod % 65536) - 4
- ELSE 0
- END AS scale,
- a.attnotnull,
- a.atttypmod,
- a.atthasdef,
- (SELECT substring(pg_get_expr(d.adbin, d.adrelid) for 128)
- FROM pg_attrdef d
- WHERE d.adrelid = a.attrelid
- AND d.adnum = a.attnum
- AND a.atthasdef
- ) as default
- FROM pg_attribute a,
- pg_class c,
- pg_type t
- WHERE c.relname = ".$db->quote($table, 'text')."
- AND a.atttypid = t.oid
- AND c.oid = a.attrelid
- AND NOT a.attisdropped
- AND a.attnum > 0
- AND a.attname = ".$db->quote($field_name, 'text')."
- ORDER BY a.attnum";
- $column = $db->queryRow($query, null, MDB2_FETCHMODE_ASSOC);
- if (PEAR::isError($column)) {
- return $column;
- }
-
- if (empty($column)) {
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'it was not specified an existing table column', __FUNCTION__);
- }
-
- $column = array_change_key_case($column, CASE_LOWER);
- $mapped_datatype = $db->datatype->mapNativeDatatype($column);
- if (PEAR::isError($mapped_datatype)) {
- return $mapped_datatype;
- }
- list($types, $length, $unsigned, $fixed) = $mapped_datatype;
- $notnull = false;
- if (!empty($column['attnotnull']) && $column['attnotnull'] == 't') {
- $notnull = true;
- }
- $default = null;
- if ($column['atthasdef'] === 't'
- && !preg_match("/nextval\('([^']+)'/", $column['default'])
- ) {
- $pattern = '/(\'.*\')::[\w ]+$/i';
- $default = $column['default'];#substr($column['adsrc'], 1, -1);
- if (is_null($default) && $notnull) {
- $default = '';
- } elseif (!empty($default) && preg_match($pattern, $default)) {
- //remove data type cast
- $default = preg_replace ($pattern, '\\1', $default);
- }
- }
- $autoincrement = false;
- if (preg_match("/nextval\('([^']+)'/", $column['default'], $nextvals)) {
- $autoincrement = true;
- }
- $definition[0] = array('notnull' => $notnull, 'nativetype' => $column['type']);
- if (!is_null($length)) {
- $definition[0]['length'] = $length;
- }
- if (!is_null($unsigned)) {
- $definition[0]['unsigned'] = $unsigned;
- }
- if (!is_null($fixed)) {
- $definition[0]['fixed'] = $fixed;
- }
- if ($default !== false) {
- $definition[0]['default'] = $default;
- }
- if ($autoincrement !== false) {
- $definition[0]['autoincrement'] = $autoincrement;
- }
- foreach ($types as $key => $type) {
- $definition[$key] = $definition[0];
- if ($type == 'clob' || $type == 'blob') {
- unset($definition[$key]['default']);
- }
- $definition[$key]['type'] = $type;
- $definition[$key]['mdb2type'] = $type;
- }
- return $definition;
- }
-
- // }}}
- // {{{ getTableIndexDefinition()
-
- /**
- * Get the structure of an index into an array
- *
- * @param string $table_name name of table that should be used in method
- * @param string $index_name name of index that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * @access public
- */
- function getTableIndexDefinition($table_name, $index_name)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- list($schema, $table) = $this->splitTableSchema($table_name);
-
- $query = 'SELECT relname, indkey FROM pg_index, pg_class';
- $query.= ' WHERE pg_class.oid = pg_index.indexrelid';
- $query.= " AND indisunique != 't' AND indisprimary != 't'";
- $query.= ' AND pg_class.relname = %s';
- $index_name_mdb2 = $db->getIndexName($index_name);
- $row = $db->queryRow(sprintf($query, $db->quote($index_name_mdb2, 'text')), null, MDB2_FETCHMODE_ASSOC);
- if (PEAR::isError($row) || empty($row)) {
- // fallback to the given $index_name, without transformation
- $row = $db->queryRow(sprintf($query, $db->quote($index_name, 'text')), null, MDB2_FETCHMODE_ASSOC);
- }
- if (PEAR::isError($row)) {
- return $row;
- }
-
- if (empty($row)) {
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'it was not specified an existing table index', __FUNCTION__);
- }
-
- $row = array_change_key_case($row, CASE_LOWER);
-
- $db->loadModule('Manager', null, true);
- $columns = $db->manager->listTableFields($table_name);
-
- $definition = array();
-
- $index_column_numbers = explode(' ', $row['indkey']);
-
- $colpos = 1;
- foreach ($index_column_numbers as $number) {
- $definition['fields'][$columns[($number - 1)]] = array(
- 'position' => $colpos++,
- 'sorting' => 'ascending',
- );
- }
- return $definition;
- }
-
- // }}}
- // {{{ getTableConstraintDefinition()
-
- /**
- * Get the structure of a constraint into an array
- *
- * @param string $table_name name of table that should be used in method
- * @param string $constraint_name name of constraint that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * @access public
- */
- function getTableConstraintDefinition($table_name, $constraint_name)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- list($schema, $table) = $this->splitTableSchema($table_name);
-
- $query = "SELECT c.oid,
- c.conname AS constraint_name,
- CASE WHEN c.contype = 'c' THEN 1 ELSE 0 END AS \"check\",
- CASE WHEN c.contype = 'f' THEN 1 ELSE 0 END AS \"foreign\",
- CASE WHEN c.contype = 'p' THEN 1 ELSE 0 END AS \"primary\",
- CASE WHEN c.contype = 'u' THEN 1 ELSE 0 END AS \"unique\",
- CASE WHEN c.condeferrable = 'f' THEN 0 ELSE 1 END AS deferrable,
- CASE WHEN c.condeferred = 'f' THEN 0 ELSE 1 END AS initiallydeferred,
- --array_to_string(c.conkey, ' ') AS constraint_key,
- t.relname AS table_name,
- t2.relname AS references_table,
- CASE confupdtype
- WHEN 'a' THEN 'NO ACTION'
- WHEN 'r' THEN 'RESTRICT'
- WHEN 'c' THEN 'CASCADE'
- WHEN 'n' THEN 'SET NULL'
- WHEN 'd' THEN 'SET DEFAULT'
- END AS onupdate,
- CASE confdeltype
- WHEN 'a' THEN 'NO ACTION'
- WHEN 'r' THEN 'RESTRICT'
- WHEN 'c' THEN 'CASCADE'
- WHEN 'n' THEN 'SET NULL'
- WHEN 'd' THEN 'SET DEFAULT'
- END AS ondelete,
- CASE confmatchtype
- WHEN 'u' THEN 'UNSPECIFIED'
- WHEN 'f' THEN 'FULL'
- WHEN 'p' THEN 'PARTIAL'
- END AS match,
- --array_to_string(c.confkey, ' ') AS fk_constraint_key,
- consrc
- FROM pg_constraint c
- LEFT JOIN pg_class t ON c.conrelid = t.oid
- LEFT JOIN pg_class t2 ON c.confrelid = t2.oid
- WHERE c.conname = %s
- AND t.relname = " . $db->quote($table, 'text');
- $constraint_name_mdb2 = $db->getIndexName($constraint_name);
- $row = $db->queryRow(sprintf($query, $db->quote($constraint_name_mdb2, 'text')), null, MDB2_FETCHMODE_ASSOC);
- if (PEAR::isError($row) || empty($row)) {
- // fallback to the given $index_name, without transformation
- $constraint_name_mdb2 = $constraint_name;
- $row = $db->queryRow(sprintf($query, $db->quote($constraint_name_mdb2, 'text')), null, MDB2_FETCHMODE_ASSOC);
- }
- if (PEAR::isError($row)) {
- return $row;
- }
-
- if (empty($row)) {
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- $constraint_name . ' is not an existing table constraint', __FUNCTION__);
- }
-
- $row = array_change_key_case($row, CASE_LOWER);
-
- $definition = array(
- 'primary' => (boolean)$row['primary'],
- 'unique' => (boolean)$row['unique'],
- 'foreign' => (boolean)$row['foreign'],
- 'check' => (boolean)$row['check'],
- 'fields' => array(),
- 'references' => array(
- 'table' => $row['references_table'],
- 'fields' => array(),
- ),
- 'deferrable' => (boolean)$row['deferrable'],
- 'initiallydeferred' => (boolean)$row['initiallydeferred'],
- 'onupdate' => $row['onupdate'],
- 'ondelete' => $row['ondelete'],
- 'match' => $row['match'],
- );
-
- $query = 'SELECT a.attname
- FROM pg_constraint c
- LEFT JOIN pg_class t ON c.conrelid = t.oid
- LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(c.conkey)
- WHERE c.conname = %s
- AND t.relname = ' . $db->quote($table, 'text');
- $constraint_name_mdb2 = $db->getIndexName($constraint_name);
- $fields = $db->queryCol(sprintf($query, $db->quote($constraint_name_mdb2, 'text')), null);
- if (PEAR::isError($fields)) {
- return $fields;
- }
- $colpos = 1;
- foreach ($fields as $field) {
- $definition['fields'][$field] = array(
- 'position' => $colpos++,
- 'sorting' => 'ascending',
- );
- }
-
- if ($definition['foreign']) {
- $query = 'SELECT a.attname
- FROM pg_constraint c
- LEFT JOIN pg_class t ON c.confrelid = t.oid
- LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(c.conkey)
- WHERE c.conname = %s
- AND t.relname = ' . $db->quote($definition['references']['table'], 'text');
- $constraint_name_mdb2 = $db->getIndexName($constraint_name);
- $foreign_fields = $db->queryCol(sprintf($query, $db->quote($constraint_name_mdb2, 'text')), null);
- if (PEAR::isError($foreign_fields)) {
- return $foreign_fields;
- }
- $colpos = 1;
- foreach ($foreign_fields as $foreign_field) {
- $definition['references']['fields'][$foreign_field] = array(
- 'position' => $colpos++,
- );
- }
- }
-
- if ($definition['check']) {
- $check_def = $db->queryOne("SELECT pg_get_constraintdef(" . $row['oid'] . ", 't')");
- // ...
- }
- return $definition;
- }
-
- // }}}
- // {{{ getTriggerDefinition()
-
- /**
- * Get the structure of a trigger into an array
- *
- * EXPERIMENTAL
- *
- * WARNING: this function is experimental and may change the returned value
- * at any time until labelled as non-experimental
- *
- * @param string $trigger name of trigger that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * @access public
- *
- * @TODO: add support for plsql functions and functions with args
- */
- function getTriggerDefinition($trigger)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = "SELECT trg.tgname AS trigger_name,
- tbl.relname AS table_name,
- CASE
- WHEN p.proname IS NOT NULL THEN 'EXECUTE PROCEDURE ' || p.proname || '();'
- ELSE ''
- END AS trigger_body,
- CASE trg.tgtype & cast(2 as int2)
- WHEN 0 THEN 'AFTER'
- ELSE 'BEFORE'
- END AS trigger_type,
- CASE trg.tgtype & cast(28 as int2)
- WHEN 16 THEN 'UPDATE'
- WHEN 8 THEN 'DELETE'
- WHEN 4 THEN 'INSERT'
- WHEN 20 THEN 'INSERT, UPDATE'
- WHEN 28 THEN 'INSERT, UPDATE, DELETE'
- WHEN 24 THEN 'UPDATE, DELETE'
- WHEN 12 THEN 'INSERT, DELETE'
- END AS trigger_event,
- trg.tgenabled AS trigger_enabled,
- obj_description(trg.oid, 'pg_trigger') AS trigger_comment
- FROM pg_trigger trg,
- pg_class tbl,
- pg_proc p
- WHERE trg.tgrelid = tbl.oid
- AND trg.tgfoid = p.oid
- AND trg.tgname = ". $db->quote($trigger, 'text');
- $types = array(
- 'trigger_name' => 'text',
- 'table_name' => 'text',
- 'trigger_body' => 'text',
- 'trigger_type' => 'text',
- 'trigger_event' => 'text',
- 'trigger_comment' => 'text',
- 'trigger_enabled' => 'boolean',
- );
- return $db->queryRow($query, $types, MDB2_FETCHMODE_ASSOC);
- }
-
- // }}}
- // {{{ tableInfo()
-
- /**
- * Returns information about a table or a result set
- *
- * NOTE: only supports 'table' and 'flags' if <var>$result</var>
- * is a table name.
- *
- * @param object|string $result MDB2_result object from a query or a
- * string containing the name of a table.
- * While this also accepts a query result
- * resource identifier, this behavior is
- * deprecated.
- * @param int $mode a valid tableInfo mode
- *
- * @return array an associative array with the information requested.
- * A MDB2_Error object on failure.
- *
- * @see MDB2_Driver_Common::tableInfo()
- */
- function tableInfo($result, $mode = null)
- {
- if (is_string($result)) {
- return parent::tableInfo($result, $mode);
- }
-
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $resource = MDB2::isResultCommon($result) ? $result->getResource() : $result;
- if (!is_resource($resource)) {
- return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'Could not generate result resource', __FUNCTION__);
- }
-
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- if ($db->options['field_case'] == CASE_LOWER) {
- $case_func = 'strtolower';
- } else {
- $case_func = 'strtoupper';
- }
- } else {
- $case_func = 'strval';
- }
-
- $count = @pg_num_fields($resource);
- $res = array();
-
- if ($mode) {
- $res['num_fields'] = $count;
- }
-
- $db->loadModule('Datatype', null, true);
- for ($i = 0; $i < $count; $i++) {
- $res[$i] = array(
- 'table' => function_exists('pg_field_table') ? @pg_field_table($resource, $i) : '',
- 'name' => $case_func(@pg_field_name($resource, $i)),
- 'type' => @pg_field_type($resource, $i),
- 'length' => @pg_field_size($resource, $i),
- 'flags' => '',
- );
- $mdb2type_info = $db->datatype->mapNativeDatatype($res[$i]);
- if (PEAR::isError($mdb2type_info)) {
- return $mdb2type_info;
- }
- $res[$i]['mdb2type'] = $mdb2type_info[0][0];
- if ($mode & MDB2_TABLEINFO_ORDER) {
- $res['order'][$res[$i]['name']] = $i;
- }
- if ($mode & MDB2_TABLEINFO_ORDERTABLE) {
- $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
- }
- }
-
- return $res;
- }
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// vim: set et ts=4 sw=4 fdm=marker:
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2006 Manuel Lemos, Tomas V.V.Cox, |
-// | Stig. S. Bakken, Lukas Smith |
-// | All rights reserved. |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
-// | API as well as database abstraction for PHP applications. |
-// | This LICENSE is in the BSD license style. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | |
-// | Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution. |
-// | |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
-// | POSSIBILITY OF SUCH DAMAGE. |
-// +----------------------------------------------------------------------+
-// | Author: Paul Cooper <pgc@ucecom.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: pgsql.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
-
-/**
- * MDB2 PostGreSQL driver
- *
- * @package MDB2
- * @category Database
- * @author Paul Cooper <pgc@ucecom.com>
- */
-class MDB2_Driver_pgsql extends MDB2_Driver_Common
-{
- // {{{ properties
- var $string_quoting = array('start' => "'", 'end' => "'", 'escape' => "'", 'escape_pattern' => '\\');
-
- var $identifier_quoting = array('start' => '"', 'end' => '"', 'escape' => '"');
- // }}}
- // {{{ constructor
-
- /**
- * Constructor
- */
- function __construct()
- {
- parent::__construct();
-
- $this->phptype = 'pgsql';
- $this->dbsyntax = 'pgsql';
-
- $this->supported['sequences'] = true;
- $this->supported['indexes'] = true;
- $this->supported['affected_rows'] = true;
- $this->supported['summary_functions'] = true;
- $this->supported['order_by_text'] = true;
- $this->supported['transactions'] = true;
- $this->supported['savepoints'] = true;
- $this->supported['current_id'] = true;
- $this->supported['limit_queries'] = true;
- $this->supported['LOBs'] = true;
- $this->supported['replace'] = 'emulated';
- $this->supported['sub_selects'] = true;
- $this->supported['auto_increment'] = 'emulated';
- $this->supported['primary_key'] = true;
- $this->supported['result_introspection'] = true;
- $this->supported['prepared_statements'] = true;
- $this->supported['identifier_quoting'] = true;
- $this->supported['pattern_escaping'] = true;
- $this->supported['new_link'] = true;
-
- $this->options['multi_query'] = false;
- $this->options['disable_smart_seqname'] = false;
- }
-
- // }}}
- // {{{ errorInfo()
-
- /**
- * This method is used to collect information about an error
- *
- * @param integer $error
- * @return array
- * @access public
- */
- function errorInfo($error = null)
- {
- // Fall back to MDB2_ERROR if there was no mapping.
- $error_code = MDB2_ERROR;
-
- $native_msg = '';
- if (is_resource($error)) {
- $native_msg = @pg_result_error($error);
- } elseif ($this->connection) {
- $native_msg = @pg_last_error($this->connection);
- if (!$native_msg && @pg_connection_status($this->connection) === PGSQL_CONNECTION_BAD) {
- $native_msg = 'Database connection has been lost.';
- $error_code = MDB2_ERROR_CONNECT_FAILED;
- }
- }
-
- static $error_regexps;
- if (empty($error_regexps)) {
- $error_regexps = array(
- '/column .* (of relation .*)?does not exist/i'
- => MDB2_ERROR_NOSUCHFIELD,
- '/(relation|sequence|table).*does not exist|class .* not found/i'
- => MDB2_ERROR_NOSUCHTABLE,
- '/index .* does not exist/'
- => MDB2_ERROR_NOT_FOUND,
- '/relation .* already exists/i'
- => MDB2_ERROR_ALREADY_EXISTS,
- '/(divide|division) by zero$/i'
- => MDB2_ERROR_DIVZERO,
- '/pg_atoi: error in .*: can\'t parse /i'
- => MDB2_ERROR_INVALID_NUMBER,
- '/invalid input syntax for( type)? (integer|numeric)/i'
- => MDB2_ERROR_INVALID_NUMBER,
- '/value .* is out of range for type \w*int/i'
- => MDB2_ERROR_INVALID_NUMBER,
- '/integer out of range/i'
- => MDB2_ERROR_INVALID_NUMBER,
- '/value too long for type character/i'
- => MDB2_ERROR_INVALID,
- '/attribute .* not found|relation .* does not have attribute/i'
- => MDB2_ERROR_NOSUCHFIELD,
- '/column .* specified in USING clause does not exist in (left|right) table/i'
- => MDB2_ERROR_NOSUCHFIELD,
- '/parser: parse error at or near/i'
- => MDB2_ERROR_SYNTAX,
- '/syntax error at/'
- => MDB2_ERROR_SYNTAX,
- '/column reference .* is ambiguous/i'
- => MDB2_ERROR_SYNTAX,
- '/permission denied/'
- => MDB2_ERROR_ACCESS_VIOLATION,
- '/violates not-null constraint/'
- => MDB2_ERROR_CONSTRAINT_NOT_NULL,
- '/violates [\w ]+ constraint/'
- => MDB2_ERROR_CONSTRAINT,
- '/referential integrity violation/'
- => MDB2_ERROR_CONSTRAINT,
- '/more expressions than target columns/i'
- => MDB2_ERROR_VALUE_COUNT_ON_ROW,
- );
- }
- if (is_numeric($error) && $error < 0) {
- $error_code = $error;
- } else {
- foreach ($error_regexps as $regexp => $code) {
- if (preg_match($regexp, $native_msg)) {
- $error_code = $code;
- break;
- }
- }
- }
- return array($error_code, null, $native_msg);
- }
-
- // }}}
- // {{{ escape()
-
- /**
- * Quotes a string so it can be safely used in a query. It will quote
- * the text so it can safely be used within a query.
- *
- * @param string the input string to quote
- * @param bool escape wildcards
- *
- * @return string quoted string
- *
- * @access public
- */
- function escape($text, $escape_wildcards = false)
- {
- if ($escape_wildcards) {
- $text = $this->escapePattern($text);
- }
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- if (version_compare(PHP_VERSION, '5.2.0RC5', '>=')) {
- $text = @pg_escape_string($connection, $text);
- } else {
- $text = @pg_escape_string($text);
- }
- return $text;
- }
-
- // }}}
- // {{{ beginTransaction()
-
- /**
- * Start a transaction or set a savepoint.
- *
- * @param string name of a savepoint to set
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function beginTransaction($savepoint = null)
- {
- $this->debug('Starting transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
- if (!is_null($savepoint)) {
- if (!$this->in_transaction) {
- return $this->raiseError(MDB2_ERROR_INVALID, null, null,
- 'savepoint cannot be released when changes are auto committed', __FUNCTION__);
- }
- $query = 'SAVEPOINT '.$savepoint;
- return $this->_doQuery($query, true);
- } elseif ($this->in_transaction) {
- return MDB2_OK; //nothing to do
- }
- if (!$this->destructor_registered && $this->opened_persistent) {
- $this->destructor_registered = true;
- register_shutdown_function('MDB2_closeOpenTransactions');
- }
- $result =& $this->_doQuery('BEGIN', true);
- if (PEAR::isError($result)) {
- return $result;
- }
- $this->in_transaction = true;
- return MDB2_OK;
- }
-
- // }}}
- // {{{ commit()
-
- /**
- * Commit the database changes done during a transaction that is in
- * progress or release a savepoint. This function may only be called when
- * auto-committing is disabled, otherwise it will fail. Therefore, a new
- * transaction is implicitly started after committing the pending changes.
- *
- * @param string name of a savepoint to release
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function commit($savepoint = null)
- {
- $this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
- if (!$this->in_transaction) {
- return $this->raiseError(MDB2_ERROR_INVALID, null, null,
- 'commit/release savepoint cannot be done changes are auto committed', __FUNCTION__);
- }
- if (!is_null($savepoint)) {
- $query = 'RELEASE SAVEPOINT '.$savepoint;
- return $this->_doQuery($query, true);
- }
-
- $result =& $this->_doQuery('COMMIT', true);
- if (PEAR::isError($result)) {
- return $result;
- }
- $this->in_transaction = false;
- return MDB2_OK;
- }
-
- // }}}
- // {{{ rollback()
-
- /**
- * Cancel any database changes done during a transaction or since a specific
- * savepoint that is in progress. This function may only be called when
- * auto-committing is disabled, otherwise it will fail. Therefore, a new
- * transaction is implicitly started after canceling the pending changes.
- *
- * @param string name of a savepoint to rollback to
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function rollback($savepoint = null)
- {
- $this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
- if (!$this->in_transaction) {
- return $this->raiseError(MDB2_ERROR_INVALID, null, null,
- 'rollback cannot be done changes are auto committed', __FUNCTION__);
- }
- if (!is_null($savepoint)) {
- $query = 'ROLLBACK TO SAVEPOINT '.$savepoint;
- return $this->_doQuery($query, true);
- }
-
- $query = 'ROLLBACK';
- $result =& $this->_doQuery($query, true);
- if (PEAR::isError($result)) {
- return $result;
- }
- $this->in_transaction = false;
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function setTransactionIsolation()
-
- /**
- * Set the transacton isolation level.
- *
- * @param string standard isolation level
- * READ UNCOMMITTED (allows dirty reads)
- * READ COMMITTED (prevents dirty reads)
- * REPEATABLE READ (prevents nonrepeatable reads)
- * SERIALIZABLE (prevents phantom reads)
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- * @since 2.1.1
- */
- function setTransactionIsolation($isolation)
- {
- $this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true));
- switch ($isolation) {
- case 'READ UNCOMMITTED':
- case 'READ COMMITTED':
- case 'REPEATABLE READ':
- case 'SERIALIZABLE':
- break;
- default:
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'isolation level is not supported: '.$isolation, __FUNCTION__);
- }
-
- $query = "SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL $isolation";
- return $this->_doQuery($query, true);
- }
-
- // }}}
- // {{{ _doConnect()
-
- /**
- * Does the grunt work of connecting to the database
- *
- * @return mixed connection resource on success, MDB2 Error Object on failure
- * @access protected
- **/
- function _doConnect($database_name, $persistent = false)
- {
- if ($database_name == '') {
- $database_name = 'template1';
- }
-
- $protocol = $this->dsn['protocol'] ? $this->dsn['protocol'] : 'tcp';
-
- $params = array('');
- if ($protocol == 'tcp') {
- if ($this->dsn['hostspec']) {
- $params[0].= 'host=' . $this->dsn['hostspec'];
- }
- if ($this->dsn['port']) {
- $params[0].= ' port=' . $this->dsn['port'];
- }
- } elseif ($protocol == 'unix') {
- // Allow for pg socket in non-standard locations.
- if ($this->dsn['socket']) {
- $params[0].= 'host=' . $this->dsn['socket'];
- }
- if ($this->dsn['port']) {
- $params[0].= ' port=' . $this->dsn['port'];
- }
- }
- if ($database_name) {
- $params[0].= ' dbname=\'' . addslashes($database_name) . '\'';
- }
- if ($this->dsn['username']) {
- $params[0].= ' user=\'' . addslashes($this->dsn['username']) . '\'';
- }
- if ($this->dsn['password']) {
- $params[0].= ' password=\'' . addslashes($this->dsn['password']) . '\'';
- }
- if (!empty($this->dsn['options'])) {
- $params[0].= ' options=' . $this->dsn['options'];
- }
- if (!empty($this->dsn['tty'])) {
- $params[0].= ' tty=' . $this->dsn['tty'];
- }
- if (!empty($this->dsn['connect_timeout'])) {
- $params[0].= ' connect_timeout=' . $this->dsn['connect_timeout'];
- }
- if (!empty($this->dsn['sslmode'])) {
- $params[0].= ' sslmode=' . $this->dsn['sslmode'];
- }
- if (!empty($this->dsn['service'])) {
- $params[0].= ' service=' . $this->dsn['service'];
- }
-
- if (!empty($this->dsn['new_link'])
- && ($this->dsn['new_link'] == 'true' || $this->dsn['new_link'] === true))
- {
- if (version_compare(phpversion(), '4.3.0', '>=')) {
- $params[] = PGSQL_CONNECT_FORCE_NEW;
- }
- }
-
- $connect_function = $persistent ? 'pg_pconnect' : 'pg_connect';
-
- $connection = @call_user_func_array($connect_function, $params);
- if (!$connection) {
- return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
- 'unable to establish a connection', __FUNCTION__);
- }
-
- if (empty($this->dsn['disable_iso_date'])) {
- if (!@pg_query($connection, "SET SESSION DATESTYLE = 'ISO'")) {
- return $this->raiseError(null, null, null,
- 'Unable to set date style to iso', __FUNCTION__);
- }
- }
-
- if (!empty($this->dsn['charset'])) {
- $result = $this->setCharset($this->dsn['charset'], $connection);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
-
- return $connection;
- }
-
- // }}}
- // {{{ connect()
-
- /**
- * Connect to the database
- *
- * @return true on success, MDB2 Error Object on failure
- * @access public
- **/
- function connect()
- {
- if (is_resource($this->connection)) {
- //if (count(array_diff($this->connected_dsn, $this->dsn)) == 0
- if (MDB2::areEquals($this->connected_dsn, $this->dsn)
- && $this->connected_database_name == $this->database_name
- && ($this->opened_persistent == $this->options['persistent'])
- ) {
- return MDB2_OK;
- }
- $this->disconnect(false);
- }
-
- if (!PEAR::loadExtension($this->phptype)) {
- return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'extension '.$this->phptype.' is not compiled into PHP', __FUNCTION__);
- }
-
- if ($this->database_name) {
- $connection = $this->_doConnect($this->database_name, $this->options['persistent']);
- if (PEAR::isError($connection)) {
- return $connection;
- }
- $this->connection = $connection;
- $this->connected_dsn = $this->dsn;
- $this->connected_database_name = $this->database_name;
- $this->opened_persistent = $this->options['persistent'];
- $this->dbsyntax = $this->dsn['dbsyntax'] ? $this->dsn['dbsyntax'] : $this->phptype;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ setCharset()
-
- /**
- * Set the charset on the current connection
- *
- * @param string charset
- * @param resource connection handle
- *
- * @return true on success, MDB2 Error Object on failure
- */
- function setCharset($charset, $connection = null)
- {
- if (is_null($connection)) {
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- }
-
- $result = @pg_set_client_encoding($connection, $charset);
- if ($result == -1) {
- return $this->raiseError(null, null, null,
- 'Unable to set client charset: '.$charset, __FUNCTION__);
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ disconnect()
-
- /**
- * Log out and disconnect from the database.
- *
- * @param boolean $force if the disconnect should be forced even if the
- * connection is opened persistently
- * @return mixed true on success, false if not connected and error
- * object on error
- * @access public
- */
- function disconnect($force = true)
- {
- if (is_resource($this->connection)) {
- if ($this->in_transaction) {
- $dsn = $this->dsn;
- $database_name = $this->database_name;
- $persistent = $this->options['persistent'];
- $this->dsn = $this->connected_dsn;
- $this->database_name = $this->connected_database_name;
- $this->options['persistent'] = $this->opened_persistent;
- $this->rollback();
- $this->dsn = $dsn;
- $this->database_name = $database_name;
- $this->options['persistent'] = $persistent;
- }
-
- if (!$this->opened_persistent || $force) {
- @pg_close($this->connection);
- }
- }
- return parent::disconnect($force);
- }
-
- // }}}
- // {{{ standaloneQuery()
-
- /**
- * execute a query as DBA
- *
- * @param string $query the SQL query
- * @param mixed $types array that contains the types of the columns in
- * the result set
- * @param boolean $is_manip if the query is a manipulation query
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function &standaloneQuery($query, $types = null, $is_manip = false)
- {
- $connection = $this->_doConnect('template1', false);
- if (PEAR::isError($connection)) {
- $err =& $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
- 'Cannot connect to template1', __FUNCTION__);
- return $err;
- }
-
- $offset = $this->offset;
- $limit = $this->limit;
- $this->offset = $this->limit = 0;
- $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
-
- $result =& $this->_doQuery($query, $is_manip, $connection, false);
- @pg_close($connection);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- if ($is_manip) {
- $affected_rows = $this->_affectedRows($connection, $result);
- return $affected_rows;
- }
- $result =& $this->_wrapResult($result, $types, true, false, $limit, $offset);
- return $result;
- }
-
- // }}}
- // {{{ _doQuery()
-
- /**
- * Execute a query
- * @param string $query query
- * @param boolean $is_manip if the query is a manipulation query
- * @param resource $connection
- * @param string $database_name
- * @return result or error object
- * @access protected
- */
- function &_doQuery($query, $is_manip = false, $connection = null, $database_name = null)
- {
- $this->last_query = $query;
- $result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre'));
- if ($result) {
- if (PEAR::isError($result)) {
- return $result;
- }
- $query = $result;
- }
- if ($this->options['disable_query']) {
- $result = $is_manip ? 0 : null;
- return $result;
- }
-
- if (is_null($connection)) {
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- }
-
- $function = $this->options['multi_query'] ? 'pg_send_query' : 'pg_query';
- $result = @$function($connection, $query);
- if (!$result) {
- $err =& $this->raiseError(null, null, null,
- 'Could not execute statement', __FUNCTION__);
- return $err;
- } elseif ($this->options['multi_query']) {
- if (!($result = @pg_get_result($connection))) {
- $err =& $this->raiseError(null, null, null,
- 'Could not get the first result from a multi query', __FUNCTION__);
- return $err;
- }
- }
-
- $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'post', 'result' => $result));
- return $result;
- }
-
- // }}}
- // {{{ _affectedRows()
-
- /**
- * Returns the number of rows affected
- *
- * @param resource $result
- * @param resource $connection
- * @return mixed MDB2 Error Object or the number of rows affected
- * @access private
- */
- function _affectedRows($connection, $result = null)
- {
- if (is_null($connection)) {
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- }
- return @pg_affected_rows($result);
- }
-
- // }}}
- // {{{ _modifyQuery()
-
- /**
- * Changes a query string for various DBMS specific reasons
- *
- * @param string $query query to modify
- * @param boolean $is_manip if it is a DML query
- * @param integer $limit limit the number of rows
- * @param integer $offset start reading from given offset
- * @return string modified query
- * @access protected
- */
- function _modifyQuery($query, $is_manip, $limit, $offset)
- {
- if ($limit > 0
- && !preg_match('/LIMIT\s*\d(?:\s*(?:,|OFFSET)\s*\d+)?(?:[^\)]*)?$/i', $query)
- ) {
- $query = rtrim($query);
- if (substr($query, -1) == ';') {
- $query = substr($query, 0, -1);
- }
- if ($is_manip) {
- $query = $this->_modifyManipQuery($query, $limit);
- } else {
- $query.= " LIMIT $limit OFFSET $offset";
- }
- }
- return $query;
- }
-
- // }}}
- // {{{ _modifyManipQuery()
-
- /**
- * Changes a manip query string for various DBMS specific reasons
- *
- * @param string $query query to modify
- * @param integer $limit limit the number of rows
- * @return string modified query
- * @access protected
- */
- function _modifyManipQuery($query, $limit)
- {
- $pos = strpos(strtolower($query), 'where');
- $where = $pos ? substr($query, $pos) : '';
-
- $manip_clause = '(\bDELETE\b\s+(?:\*\s+)?\bFROM\b|\bUPDATE\b)';
- $from_clause = '([\w\.]+)';
- $where_clause = '(?:(.*)\bWHERE\b\s+(.*))|(.*)';
- $pattern = '/^'. $manip_clause . '\s+' . $from_clause .'(?:\s)*(?:'. $where_clause .')?$/i';
- $matches = preg_match($pattern, $query, $match);
- if ($matches) {
- $manip = $match[1];
- $from = $match[2];
- $what = (count($matches) == 6) ? $match[5] : $match[3];
- return $manip.' '.$from.' '.$what.' WHERE ctid=(SELECT ctid FROM '.$from.' '.$where.' LIMIT '.$limit.')';
- }
- //return error?
- return $query;
- }
-
- // }}}
- // {{{ getServerVersion()
-
- /**
- * return version information about the server
- *
- * @param bool $native determines if the raw version string should be returned
- * @return mixed array/string with version information or MDB2 error object
- * @access public
- */
- function getServerVersion($native = false)
- {
- $query = 'SHOW SERVER_VERSION';
- if ($this->connected_server_info) {
- $server_info = $this->connected_server_info;
- } else {
- $server_info = $this->queryOne($query, 'text');
- if (PEAR::isError($server_info)) {
- return $server_info;
- }
- }
- // cache server_info
- $this->connected_server_info = $server_info;
- if (!$native && !PEAR::isError($server_info)) {
- $tmp = explode('.', $server_info, 3);
- if (empty($tmp[2])
- && isset($tmp[1])
- && preg_match('/(\d+)(.*)/', $tmp[1], $tmp2)
- ) {
- $server_info = array(
- 'major' => $tmp[0],
- 'minor' => $tmp2[1],
- 'patch' => null,
- 'extra' => $tmp2[2],
- 'native' => $server_info,
- );
- } else {
- $server_info = array(
- 'major' => isset($tmp[0]) ? $tmp[0] : null,
- 'minor' => isset($tmp[1]) ? $tmp[1] : null,
- 'patch' => isset($tmp[2]) ? $tmp[2] : null,
- 'extra' => null,
- 'native' => $server_info,
- );
- }
- }
- return $server_info;
- }
-
- // }}}
- // {{{ prepare()
-
- /**
- * Prepares a query for multiple execution with execute().
- * With some database backends, this is emulated.
- * prepare() requires a generic query as string like
- * 'INSERT INTO numbers VALUES(?,?)' or
- * 'INSERT INTO numbers VALUES(:foo,:bar)'.
- * The ? and :name and are placeholders which can be set using
- * bindParam() and the query can be sent off using the execute() method.
- * The allowed format for :name can be set with the 'bindname_format' option.
- *
- * @param string $query the query to prepare
- * @param mixed $types array that contains the types of the placeholders
- * @param mixed $result_types array that contains the types of the columns in
- * the result set or MDB2_PREPARE_RESULT, if set to
- * MDB2_PREPARE_MANIP the query is handled as a manipulation query
- * @param mixed $lobs key (field) value (parameter) pair for all lob placeholders
- * @return mixed resource handle for the prepared query on success, a MDB2
- * error on failure
- * @access public
- * @see bindParam, execute
- */
- function &prepare($query, $types = null, $result_types = null, $lobs = array())
- {
- if ($this->options['emulate_prepared']) {
- $obj =& parent::prepare($query, $types, $result_types, $lobs);
- return $obj;
- }
- $is_manip = ($result_types === MDB2_PREPARE_MANIP);
- $offset = $this->offset;
- $limit = $this->limit;
- $this->offset = $this->limit = 0;
- $result = $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'pre'));
- if ($result) {
- if (PEAR::isError($result)) {
- return $result;
- }
- $query = $result;
- }
- $pgtypes = function_exists('pg_prepare') ? false : array();
- if ($pgtypes !== false && !empty($types)) {
- $this->loadModule('Datatype', null, true);
- }
- $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
- $placeholder_type_guess = $placeholder_type = null;
- $question = '?';
- $colon = ':';
- $positions = array();
- $position = $parameter = 0;
- while ($position < strlen($query)) {
- $q_position = strpos($query, $question, $position);
- $c_position = strpos($query, $colon, $position);
- //skip "::type" cast ("select id::varchar(20) from sometable where name=?")
- $doublecolon_position = strpos($query, '::', $position);
- if ($doublecolon_position !== false && $doublecolon_position == $c_position) {
- $c_position = strpos($query, $colon, $position+2);
- }
- if ($q_position && $c_position) {
- $p_position = min($q_position, $c_position);
- } elseif ($q_position) {
- $p_position = $q_position;
- } elseif ($c_position) {
- $p_position = $c_position;
- } else {
- break;
- }
- if (is_null($placeholder_type)) {
- $placeholder_type_guess = $query[$p_position];
- }
-
- $new_pos = $this->_skipDelimitedStrings($query, $position, $p_position);
- if (PEAR::isError($new_pos)) {
- return $new_pos;
- }
- if ($new_pos != $position) {
- $position = $new_pos;
- continue; //evaluate again starting from the new position
- }
-
- if ($query[$position] == $placeholder_type_guess) {
- if (is_null($placeholder_type)) {
- $placeholder_type = $query[$p_position];
- $question = $colon = $placeholder_type;
- if (!empty($types) && is_array($types)) {
- if ($placeholder_type == ':') {
- } else {
- $types = array_values($types);
- }
- }
- }
- if ($placeholder_type_guess == '?') {
- $length = 1;
- $name = $parameter;
- } else {
- $regexp = '/^.{'.($position+1).'}('.$this->options['bindname_format'].').*$/s';
- $param = preg_replace($regexp, '\\1', $query);
- if ($param === '') {
- $err =& $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
- 'named parameter name must match "bindname_format" option', __FUNCTION__);
- return $err;
- }
- $length = strlen($param) + 1;
- $name = $param;
- }
- if ($pgtypes !== false) {
- if (is_array($types) && array_key_exists($name, $types)) {
- $pgtypes[] = $this->datatype->mapPrepareDatatype($types[$name]);
- } elseif (is_array($types) && array_key_exists($parameter, $types)) {
- $pgtypes[] = $this->datatype->mapPrepareDatatype($types[$parameter]);
- } else {
- $pgtypes[] = 'text';
- }
- }
- if (($key_parameter = array_search($name, $positions))) {
- $next_parameter = 1;
- foreach ($positions as $key => $value) {
- if ($key_parameter == $key) {
- break;
- }
- ++$next_parameter;
- }
- } else {
- ++$parameter;
- $next_parameter = $parameter;
- $positions[] = $name;
- }
- $query = substr_replace($query, '$'.$parameter, $position, $length);
- $position = $p_position + strlen($parameter);
- } else {
- $position = $p_position;
- }
- }
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- static $prep_statement_counter = 1;
- $statement_name = sprintf($this->options['statement_format'], $this->phptype, sha1(microtime() + mt_rand())) . $prep_statement_counter++;
- $statement_name = strtolower($statement_name);
- if ($pgtypes === false) {
- $result = @pg_prepare($connection, $statement_name, $query);
- if (!$result) {
- $err =& $this->raiseError(null, null, null,
- 'Unable to create prepared statement handle', __FUNCTION__);
- return $err;
- }
- } else {
- $types_string = '';
- if ($pgtypes) {
- $types_string = ' ('.implode(', ', $pgtypes).') ';
- }
- $query = 'PREPARE '.$statement_name.$types_string.' AS '.$query;
- $statement =& $this->_doQuery($query, true, $connection);
- if (PEAR::isError($statement)) {
- return $statement;
- }
- }
-
- $class_name = 'MDB2_Statement_'.$this->phptype;
- $obj = new $class_name($this, $statement_name, $positions, $query, $types, $result_types, $is_manip, $limit, $offset);
- $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'post', 'result' => $obj));
- return $obj;
- }
-
- // }}}
- // {{{ function getSequenceName($sqn)
-
- /**
- * adds sequence name formatting to a sequence name
- *
- * @param string name of the sequence
- *
- * @return string formatted sequence name
- *
- * @access public
- */
- function getSequenceName($sqn)
- {
- if (false === $this->options['disable_smart_seqname']) {
- if (strpos($sqn, '_') !== false) {
- list($table, $field) = explode('_', $sqn, 2);
- }
- $schema_list = $this->queryOne("SELECT array_to_string(current_schemas(false), ',')");
- if (PEAR::isError($schema_list) || empty($schema_list) || count($schema_list) < 2) {
- $order_by = ' a.attnum';
- $schema_clause = ' AND n.nspname=current_schema()';
- } else {
- $schemas = explode(',', $schema_list);
- $schema_clause = ' AND n.nspname IN ('.$schema_list.')';
- $counter = 1;
- $order_by = ' CASE ';
- foreach ($schemas as $schema) {
- $order_by .= ' WHEN n.nspname='.$schema.' THEN '.$counter++;
- }
- $order_by .= ' ELSE '.$counter.' END, a.attnum';
- }
-
- $query = "SELECT substring((SELECT substring(pg_get_expr(d.adbin, d.adrelid) for 128)
- FROM pg_attrdef d
- WHERE d.adrelid = a.attrelid
- AND d.adnum = a.attnum
- AND a.atthasdef
- ) FROM 'nextval[^\']*\'([^\']*)')
- FROM pg_attribute a
- LEFT JOIN pg_class c ON c.oid = a.attrelid
- LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef
- LEFT JOIN pg_namespace n ON c.relnamespace = n.oid
- WHERE (c.relname = ".$this->quote($sqn, 'text');
- if (!empty($field)) {
- $query .= " OR (c.relname = ".$this->quote($table, 'text')." AND a.attname = ".$this->quote($field, 'text').")";
- }
- $query .= " )"
- .$schema_clause."
- AND NOT a.attisdropped
- AND a.attnum > 0
- AND pg_get_expr(d.adbin, d.adrelid) LIKE 'nextval%'
- ORDER BY ".$order_by;
- $seqname = $this->queryOne($query);
- if (!PEAR::isError($seqname) && !empty($seqname) && is_string($seqname)) {
- return $seqname;
- }
- }
-
- return sprintf($this->options['seqname_format'],
- preg_replace('/[^\w\$.]/i', '_', $sqn));
- }
-
- // }}}
- // {{{ nextID()
-
- /**
- * Returns the next free id of a sequence
- *
- * @param string $seq_name name of the sequence
- * @param boolean $ondemand when true the sequence is
- * automatic created, if it
- * not exists
- * @return mixed MDB2 Error Object or id
- * @access public
- */
- function nextID($seq_name, $ondemand = true)
- {
- $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
- $query = "SELECT NEXTVAL('$sequence_name')";
- $this->expectError(MDB2_ERROR_NOSUCHTABLE);
- $result = $this->queryOne($query, 'integer');
- $this->popExpect();
- if (PEAR::isError($result)) {
- if ($ondemand && $result->getCode() == MDB2_ERROR_NOSUCHTABLE) {
- $this->loadModule('Manager', null, true);
- $result = $this->manager->createSequence($seq_name);
- if (PEAR::isError($result)) {
- return $this->raiseError($result, null, null,
- 'on demand sequence could not be created', __FUNCTION__);
- }
- return $this->nextId($seq_name, false);
- }
- }
- return $result;
- }
-
- // }}}
- // {{{ lastInsertID()
-
- /**
- * Returns the autoincrement ID if supported or $id or fetches the current
- * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
- *
- * @param string $table name of the table into which a new row was inserted
- * @param string $field name of the field into which a new row was inserted
- * @return mixed MDB2 Error Object or id
- * @access public
- */
- function lastInsertID($table = null, $field = null)
- {
- if (empty($table) && empty($field)) {
- return $this->queryOne('SELECT lastval()', 'integer');
- }
- $seq = $table.(empty($field) ? '' : '_'.$field);
- $sequence_name = $this->getSequenceName($seq);
- return $this->queryOne("SELECT currval('$sequence_name')", 'integer');
- }
-
- // }}}
- // {{{ currID()
-
- /**
- * Returns the current id of a sequence
- *
- * @param string $seq_name name of the sequence
- * @return mixed MDB2 Error Object or id
- * @access public
- */
- function currID($seq_name)
- {
- $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
- return $this->queryOne("SELECT last_value FROM $sequence_name", 'integer');
- }
-}
-
-/**
- * MDB2 PostGreSQL result driver
- *
- * @package MDB2
- * @category Database
- * @author Paul Cooper <pgc@ucecom.com>
- */
-class MDB2_Result_pgsql extends MDB2_Result_Common
-{
- // }}}
- // {{{ fetchRow()
-
- /**
- * Fetch a row and insert the data into an existing array.
- *
- * @param int $fetchmode how the array data should be indexed
- * @param int $rownum number of the row where the data can be found
- * @return int data array on success, a MDB2 error on failure
- * @access public
- */
- function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
- {
- if (!is_null($rownum)) {
- $seek = $this->seek($rownum);
- if (PEAR::isError($seek)) {
- return $seek;
- }
- }
- if ($fetchmode == MDB2_FETCHMODE_DEFAULT) {
- $fetchmode = $this->db->fetchmode;
- }
- if ($fetchmode & MDB2_FETCHMODE_ASSOC) {
- $row = @pg_fetch_array($this->result, null, PGSQL_ASSOC);
- if (is_array($row)
- && $this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE
- ) {
- $row = array_change_key_case($row, $this->db->options['field_case']);
- }
- } else {
- $row = @pg_fetch_row($this->result);
- }
- if (!$row) {
- if ($this->result === false) {
- $err =& $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'resultset has already been freed', __FUNCTION__);
- return $err;
- }
- $null = null;
- return $null;
- }
- $mode = $this->db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL;
- $rtrim = false;
- if ($this->db->options['portability'] & MDB2_PORTABILITY_RTRIM) {
- if (empty($this->types)) {
- $mode += MDB2_PORTABILITY_RTRIM;
- } else {
- $rtrim = true;
- }
- }
- if ($mode) {
- $this->db->_fixResultArrayValues($row, $mode);
- }
- if (!empty($this->types)) {
- $row = $this->db->datatype->convertResultRow($this->types, $row, $rtrim);
- }
- if (!empty($this->values)) {
- $this->_assignBindColumns($row);
- }
- if ($fetchmode === MDB2_FETCHMODE_OBJECT) {
- $object_class = $this->db->options['fetch_class'];
- if ($object_class == 'stdClass') {
- $row = (object) $row;
- } else {
- $row = &new $object_class($row);
- }
- }
- ++$this->rownum;
- return $row;
- }
-
- // }}}
- // {{{ _getColumnNames()
-
- /**
- * Retrieve the names of columns returned by the DBMS in a query result.
- *
- * @return mixed Array variable that holds the names of columns as keys
- * or an MDB2 error on failure.
- * Some DBMS may not return any columns when the result set
- * does not contain any rows.
- * @access private
- */
- function _getColumnNames()
- {
- $columns = array();
- $numcols = $this->numCols();
- if (PEAR::isError($numcols)) {
- return $numcols;
- }
- for ($column = 0; $column < $numcols; $column++) {
- $column_name = @pg_field_name($this->result, $column);
- $columns[$column_name] = $column;
- }
- if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $columns = array_change_key_case($columns, $this->db->options['field_case']);
- }
- return $columns;
- }
-
- // }}}
- // {{{ numCols()
-
- /**
- * Count the number of columns returned by the DBMS in a query result.
- *
- * @access public
- * @return mixed integer value with the number of columns, a MDB2 error
- * on failure
- */
- function numCols()
- {
- $cols = @pg_num_fields($this->result);
- if (is_null($cols)) {
- if ($this->result === false) {
- return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'resultset has already been freed', __FUNCTION__);
- } elseif (is_null($this->result)) {
- return count($this->types);
- }
- return $this->db->raiseError(null, null, null,
- 'Could not get column count', __FUNCTION__);
- }
- return $cols;
- }
-
- // }}}
- // {{{ nextResult()
-
- /**
- * Move the internal result pointer to the next available result
- *
- * @return true on success, false if there is no more result set or an error object on failure
- * @access public
- */
- function nextResult()
- {
- $connection = $this->db->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
-
- if (!($this->result = @pg_get_result($connection))) {
- return false;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ free()
-
- /**
- * Free the internal resources associated with result.
- *
- * @return boolean true on success, false if result is invalid
- * @access public
- */
- function free()
- {
- if (is_resource($this->result) && $this->db->connection) {
- $free = @pg_free_result($this->result);
- if ($free === false) {
- return $this->db->raiseError(null, null, null,
- 'Could not free result', __FUNCTION__);
- }
- }
- $this->result = false;
- return MDB2_OK;
- }
-}
-
-/**
- * MDB2 PostGreSQL buffered result driver
- *
- * @package MDB2
- * @category Database
- * @author Paul Cooper <pgc@ucecom.com>
- */
-class MDB2_BufferedResult_pgsql extends MDB2_Result_pgsql
-{
- // {{{ seek()
-
- /**
- * Seek to a specific row in a result set
- *
- * @param int $rownum number of the row where the data can be found
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function seek($rownum = 0)
- {
- if ($this->rownum != ($rownum - 1) && !@pg_result_seek($this->result, $rownum)) {
- if ($this->result === false) {
- return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'resultset has already been freed', __FUNCTION__);
- } elseif (is_null($this->result)) {
- return MDB2_OK;
- }
- return $this->db->raiseError(MDB2_ERROR_INVALID, null, null,
- 'tried to seek to an invalid row number ('.$rownum.')', __FUNCTION__);
- }
- $this->rownum = $rownum - 1;
- return MDB2_OK;
- }
-
- // }}}
- // {{{ valid()
-
- /**
- * Check if the end of the result set has been reached
- *
- * @return mixed true or false on sucess, a MDB2 error on failure
- * @access public
- */
- function valid()
- {
- $numrows = $this->numRows();
- if (PEAR::isError($numrows)) {
- return $numrows;
- }
- return $this->rownum < ($numrows - 1);
- }
-
- // }}}
- // {{{ numRows()
-
- /**
- * Returns the number of rows in a result object
- *
- * @return mixed MDB2 Error Object or the number of rows
- * @access public
- */
- function numRows()
- {
- $rows = @pg_num_rows($this->result);
- if (is_null($rows)) {
- if ($this->result === false) {
- return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'resultset has already been freed', __FUNCTION__);
- } elseif (is_null($this->result)) {
- return 0;
- }
- return $this->db->raiseError(null, null, null,
- 'Could not get row count', __FUNCTION__);
- }
- return $rows;
- }
-}
-
-/**
- * MDB2 PostGreSQL statement driver
- *
- * @package MDB2
- * @category Database
- * @author Paul Cooper <pgc@ucecom.com>
- */
-class MDB2_Statement_pgsql extends MDB2_Statement_Common
-{
- // {{{ _execute()
-
- /**
- * Execute a prepared query statement helper method.
- *
- * @param mixed $result_class string which specifies which result class to use
- * @param mixed $result_wrap_class string which specifies which class to wrap results in
- * @return mixed a result handle or MDB2_OK on success, a MDB2 error on failure
- * @access private
- */
- function &_execute($result_class = true, $result_wrap_class = false)
- {
- if (is_null($this->statement)) {
- $result =& parent::_execute($result_class, $result_wrap_class);
- return $result;
- }
- $this->db->last_query = $this->query;
- $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'pre', 'parameters' => $this->values));
- if ($this->db->getOption('disable_query')) {
- $result = $this->is_manip ? 0 : null;
- return $result;
- }
-
- $connection = $this->db->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
-
- $query = false;
- $parameters = array();
- // todo: disabled until pg_execute() bytea issues are cleared up
- if (true || !function_exists('pg_execute')) {
- $query = 'EXECUTE '.$this->statement;
- }
- if (!empty($this->positions)) {
- foreach ($this->positions as $parameter) {
- if (!array_key_exists($parameter, $this->values)) {
- return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
- }
- $value = $this->values[$parameter];
- $type = array_key_exists($parameter, $this->types) ? $this->types[$parameter] : null;
- if (is_resource($value) || $type == 'clob' || $type == 'blob' || $this->db->options['lob_allow_url_include']) {
- if (!is_resource($value) && preg_match('/^(\w+:\/\/)(.*)$/', $value, $match)) {
- if ($match[1] == 'file://') {
- $value = $match[2];
- }
- $value = @fopen($value, 'r');
- $close = true;
- }
- if (is_resource($value)) {
- $data = '';
- while (!@feof($value)) {
- $data.= @fread($value, $this->db->options['lob_buffer_length']);
- }
- if ($close) {
- @fclose($value);
- }
- $value = $data;
- }
- }
- $quoted = $this->db->quote($value, $type, $query);
- if (PEAR::isError($quoted)) {
- return $quoted;
- }
- $parameters[] = $quoted;
- }
- if ($query) {
- $query.= ' ('.implode(', ', $parameters).')';
- }
- }
-
- if (!$query) {
- $result = @pg_execute($connection, $this->statement, $parameters);
- if (!$result) {
- $err =& $this->db->raiseError(null, null, null,
- 'Unable to execute statement', __FUNCTION__);
- return $err;
- }
- } else {
- $result = $this->db->_doQuery($query, $this->is_manip, $connection);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
-
- if ($this->is_manip) {
- $affected_rows = $this->db->_affectedRows($connection, $result);
- return $affected_rows;
- }
-
- $result =& $this->db->_wrapResult($result, $this->result_types,
- $result_class, $result_wrap_class, $this->limit, $this->offset);
- $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'post', 'result' => $result));
- return $result;
- }
-
- // }}}
- // {{{ free()
-
- /**
- * Release resources allocated for the specified prepared query.
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function free()
- {
- if (is_null($this->positions)) {
- return $this->db->raiseError(MDB2_ERROR, null, null,
- 'Prepared statement has already been freed', __FUNCTION__);
- }
- $result = MDB2_OK;
-
- if (!is_null($this->statement)) {
- $connection = $this->db->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- $query = 'DEALLOCATE PREPARE '.$this->statement;
- $result = $this->db->_doQuery($query, true, $connection);
- }
-
- parent::free();
- return $result;
- }
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2006 Manuel Lemos, Tomas V.V.Cox, |
-// | Stig. S. Bakken, Lukas Smith |
-// | All rights reserved. |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
-// | API as well as database abstraction for PHP applications. |
-// | This LICENSE is in the BSD license style. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | |
-// | Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution. |
-// | |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
-// | POSSIBILITY OF SUCH DAMAGE. |
-// +----------------------------------------------------------------------+
-// | Author: Lukas Smith <smith@pooteeweet.org> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Extended.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
-
-/**
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-
-/**
- * Used by autoPrepare()
- */
-define('MDB2_AUTOQUERY_INSERT', 1);
-define('MDB2_AUTOQUERY_UPDATE', 2);
-define('MDB2_AUTOQUERY_DELETE', 3);
-define('MDB2_AUTOQUERY_SELECT', 4);
-
-/**
- * MDB2_Extended: class which adds several high level methods to MDB2
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Extended extends MDB2_Module_Common
-{
- // {{{ autoPrepare()
-
- /**
- * Generate an insert, update or delete query and call prepare() on it
- *
- * @param string table
- * @param array the fields names
- * @param int type of query to build
- * MDB2_AUTOQUERY_INSERT
- * MDB2_AUTOQUERY_UPDATE
- * MDB2_AUTOQUERY_DELETE
- * MDB2_AUTOQUERY_SELECT
- * @param string (in case of update and delete queries, this string will be put after the sql WHERE statement)
- * @param array that contains the types of the placeholders
- * @param mixed array that contains the types of the columns in
- * the result set or MDB2_PREPARE_RESULT, if set to
- * MDB2_PREPARE_MANIP the query is handled as a manipulation query
- *
- * @return resource handle for the query
- * @see buildManipSQL
- * @access public
- */
- function autoPrepare($table, $table_fields, $mode = MDB2_AUTOQUERY_INSERT,
- $where = false, $types = null, $result_types = MDB2_PREPARE_MANIP)
- {
- $query = $this->buildManipSQL($table, $table_fields, $mode, $where);
- if (PEAR::isError($query)) {
- return $query;
- }
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- $lobs = array();
- foreach ((array)$types as $param => $type) {
- if (($type == 'clob') || ($type == 'blob')) {
- $lobs[$param] = $table_fields[$param];
- }
- }
- return $db->prepare($query, $types, $result_types, $lobs);
- }
-
- // }}}
- // {{{ autoExecute()
-
- /**
- * Generate an insert, update or delete query and call prepare() and execute() on it
- *
- * @param string name of the table
- * @param array assoc ($key=>$value) where $key is a field name and $value its value
- * @param int type of query to build
- * MDB2_AUTOQUERY_INSERT
- * MDB2_AUTOQUERY_UPDATE
- * MDB2_AUTOQUERY_DELETE
- * MDB2_AUTOQUERY_SELECT
- * @param string (in case of update and delete queries, this string will be put after the sql WHERE statement)
- * @param array that contains the types of the placeholders
- * @param string which specifies which result class to use
- * @param mixed array that contains the types of the columns in
- * the result set or MDB2_PREPARE_RESULT, if set to
- * MDB2_PREPARE_MANIP the query is handled as a manipulation query
- *
- * @return bool|MDB2_Error true on success, a MDB2 error on failure
- * @see buildManipSQL
- * @see autoPrepare
- * @access public
- */
- function &autoExecute($table, $fields_values, $mode = MDB2_AUTOQUERY_INSERT,
- $where = false, $types = null, $result_class = true, $result_types = MDB2_PREPARE_MANIP)
- {
- $fields_values = (array)$fields_values;
- if ($mode == MDB2_AUTOQUERY_SELECT) {
- if (is_array($result_types)) {
- $keys = array_keys($result_types);
- } elseif (!empty($fields_values)) {
- $keys = $fields_values;
- } else {
- $keys = array();
- }
- } else {
- $keys = array_keys($fields_values);
- }
- $params = array_values($fields_values);
- if (empty($params)) {
- $query = $this->buildManipSQL($table, $keys, $mode, $where);
-
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- if ($mode == MDB2_AUTOQUERY_SELECT) {
- $result =& $db->query($query, $result_types, $result_class);
- } else {
- $result = $db->exec($query);
- }
- } else {
- $stmt = $this->autoPrepare($table, $keys, $mode, $where, $types, $result_types);
- if (PEAR::isError($stmt)) {
- return $stmt;
- }
- $result =& $stmt->execute($params, $result_class);
- $stmt->free();
- }
- return $result;
- }
-
- // }}}
- // {{{ buildManipSQL()
-
- /**
- * Make automaticaly an sql query for prepare()
- *
- * Example : buildManipSQL('table_sql', array('field1', 'field2', 'field3'), MDB2_AUTOQUERY_INSERT)
- * will return the string : INSERT INTO table_sql (field1,field2,field3) VALUES (?,?,?)
- * NB : - This belongs more to a SQL Builder class, but this is a simple facility
- * - Be carefull ! If you don't give a $where param with an UPDATE/DELETE query, all
- * the records of the table will be updated/deleted !
- *
- * @param string name of the table
- * @param ordered array containing the fields names
- * @param int type of query to build
- * MDB2_AUTOQUERY_INSERT
- * MDB2_AUTOQUERY_UPDATE
- * MDB2_AUTOQUERY_DELETE
- * MDB2_AUTOQUERY_SELECT
- * @param string (in case of update and delete queries, this string will be put after the sql WHERE statement)
- *
- * @return string sql query for prepare()
- * @access public
- */
- function buildManipSQL($table, $table_fields, $mode, $where = false)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if ($db->options['quote_identifier']) {
- $table = $db->quoteIdentifier($table);
- }
-
- if (!empty($table_fields) && $db->options['quote_identifier']) {
- foreach ($table_fields as $key => $field) {
- $table_fields[$key] = $db->quoteIdentifier($field);
- }
- }
-
- if ($where !== false && !is_null($where)) {
- if (is_array($where)) {
- $where = implode(' AND ', $where);
- }
- $where = ' WHERE '.$where;
- }
-
- switch ($mode) {
- case MDB2_AUTOQUERY_INSERT:
- if (empty($table_fields)) {
- return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'Insert requires table fields', __FUNCTION__);
- }
- $cols = implode(', ', $table_fields);
- $values = '?'.str_repeat(', ?', (count($table_fields) - 1));
- return 'INSERT INTO '.$table.' ('.$cols.') VALUES ('.$values.')';
- break;
- case MDB2_AUTOQUERY_UPDATE:
- if (empty($table_fields)) {
- return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'Update requires table fields', __FUNCTION__);
- }
- $set = implode(' = ?, ', $table_fields).' = ?';
- $sql = 'UPDATE '.$table.' SET '.$set.$where;
- return $sql;
- break;
- case MDB2_AUTOQUERY_DELETE:
- $sql = 'DELETE FROM '.$table.$where;
- return $sql;
- break;
- case MDB2_AUTOQUERY_SELECT:
- $cols = !empty($table_fields) ? implode(', ', $table_fields) : '*';
- $sql = 'SELECT '.$cols.' FROM '.$table.$where;
- return $sql;
- break;
- }
- return $db->raiseError(MDB2_ERROR_SYNTAX, null, null,
- 'Non existant mode', __FUNCTION__);
- }
-
- // }}}
- // {{{ limitQuery()
-
- /**
- * Generates a limited query
- *
- * @param string query
- * @param array that contains the types of the columns in the result set
- * @param integer the numbers of rows to fetch
- * @param integer the row to start to fetching
- * @param string which specifies which result class to use
- * @param mixed string which specifies which class to wrap results in
- *
- * @return MDB2_Result|MDB2_Error result set on success, a MDB2 error on failure
- * @access public
- */
- function &limitQuery($query, $types, $limit, $offset = 0, $result_class = true,
- $result_wrap_class = false)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $result = $db->setLimit($limit, $offset);
- if (PEAR::isError($result)) {
- return $result;
- }
- $result =& $db->query($query, $types, $result_class, $result_wrap_class);
- return $result;
- }
-
- // }}}
- // {{{ execParam()
-
- /**
- * Execute a parameterized DML statement.
- *
- * @param string the SQL query
- * @param array if supplied, prepare/execute will be used
- * with this array as execute parameters
- * @param array that contains the types of the values defined in $params
- *
- * @return int|MDB2_Error affected rows on success, a MDB2 error on failure
- * @access public
- */
- function execParam($query, $params = array(), $param_types = null)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- settype($params, 'array');
- if (empty($params)) {
- return $db->exec($query);
- }
-
- $stmt = $db->prepare($query, $param_types, MDB2_PREPARE_MANIP);
- if (PEAR::isError($stmt)) {
- return $stmt;
- }
-
- $result = $stmt->execute($params);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- $stmt->free();
- return $result;
- }
-
- // }}}
- // {{{ getOne()
-
- /**
- * Fetch the first column of the first row of data returned from a query.
- * Takes care of doing the query and freeing the results when finished.
- *
- * @param string the SQL query
- * @param string that contains the type of the column in the result set
- * @param array if supplied, prepare/execute will be used
- * with this array as execute parameters
- * @param array that contains the types of the values defined in $params
- * @param int|string which column to return
- *
- * @return scalar|MDB2_Error data on success, a MDB2 error on failure
- * @access public
- */
- function getOne($query, $type = null, $params = array(),
- $param_types = null, $colnum = 0)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- settype($params, 'array');
- settype($type, 'array');
- if (empty($params)) {
- return $db->queryOne($query, $type, $colnum);
- }
-
- $stmt = $db->prepare($query, $param_types, $type);
- if (PEAR::isError($stmt)) {
- return $stmt;
- }
-
- $result = $stmt->execute($params);
- if (!MDB2::isResultCommon($result)) {
- return $result;
- }
-
- $one = $result->fetchOne($colnum);
- $stmt->free();
- $result->free();
- return $one;
- }
-
- // }}}
- // {{{ getRow()
-
- /**
- * Fetch the first row of data returned from a query. Takes care
- * of doing the query and freeing the results when finished.
- *
- * @param string the SQL query
- * @param array that contains the types of the columns in the result set
- * @param array if supplied, prepare/execute will be used
- * with this array as execute parameters
- * @param array that contains the types of the values defined in $params
- * @param int the fetch mode to use
- *
- * @return array|MDB2_Error data on success, a MDB2 error on failure
- * @access public
- */
- function getRow($query, $types = null, $params = array(),
- $param_types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- settype($params, 'array');
- if (empty($params)) {
- return $db->queryRow($query, $types, $fetchmode);
- }
-
- $stmt = $db->prepare($query, $param_types, $types);
- if (PEAR::isError($stmt)) {
- return $stmt;
- }
-
- $result = $stmt->execute($params);
- if (!MDB2::isResultCommon($result)) {
- return $result;
- }
-
- $row = $result->fetchRow($fetchmode);
- $stmt->free();
- $result->free();
- return $row;
- }
-
- // }}}
- // {{{ getCol()
-
- /**
- * Fetch a single column from a result set and return it as an
- * indexed array.
- *
- * @param string the SQL query
- * @param string that contains the type of the column in the result set
- * @param array if supplied, prepare/execute will be used
- * with this array as execute parameters
- * @param array that contains the types of the values defined in $params
- * @param int|string which column to return
- *
- * @return array|MDB2_Error data on success, a MDB2 error on failure
- * @access public
- */
- function getCol($query, $type = null, $params = array(),
- $param_types = null, $colnum = 0)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- settype($params, 'array');
- settype($type, 'array');
- if (empty($params)) {
- return $db->queryCol($query, $type, $colnum);
- }
-
- $stmt = $db->prepare($query, $param_types, $type);
- if (PEAR::isError($stmt)) {
- return $stmt;
- }
-
- $result = $stmt->execute($params);
- if (!MDB2::isResultCommon($result)) {
- return $result;
- }
-
- $col = $result->fetchCol($colnum);
- $stmt->free();
- $result->free();
- return $col;
- }
-
- // }}}
- // {{{ getAll()
-
- /**
- * Fetch all the rows returned from a query.
- *
- * @param string the SQL query
- * @param array that contains the types of the columns in the result set
- * @param array if supplied, prepare/execute will be used
- * with this array as execute parameters
- * @param array that contains the types of the values defined in $params
- * @param int the fetch mode to use
- * @param bool if set to true, the $all will have the first
- * column as its first dimension
- * @param bool $force_array used only when the query returns exactly
- * two columns. If true, the values of the returned array will be
- * one-element arrays instead of scalars.
- * @param bool $group if true, the values of the returned array is
- * wrapped in another array. If the same key value (in the first
- * column) repeats itself, the values will be appended to this array
- * instead of overwriting the existing values.
- *
- * @return array|MDB2_Error data on success, a MDB2 error on failure
- * @access public
- */
- function getAll($query, $types = null, $params = array(),
- $param_types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT,
- $rekey = false, $force_array = false, $group = false)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- settype($params, 'array');
- if (empty($params)) {
- return $db->queryAll($query, $types, $fetchmode, $rekey, $force_array, $group);
- }
-
- $stmt = $db->prepare($query, $param_types, $types);
- if (PEAR::isError($stmt)) {
- return $stmt;
- }
-
- $result = $stmt->execute($params);
- if (!MDB2::isResultCommon($result)) {
- return $result;
- }
-
- $all = $result->fetchAll($fetchmode, $rekey, $force_array, $group);
- $stmt->free();
- $result->free();
- return $all;
- }
-
- // }}}
- // {{{ getAssoc()
-
- /**
- * Fetch the entire result set of a query and return it as an
- * associative array using the first column as the key.
- *
- * If the result set contains more than two columns, the value
- * will be an array of the values from column 2-n. If the result
- * set contains only two columns, the returned value will be a
- * scalar with the value of the second column (unless forced to an
- * array with the $force_array parameter). A MDB2 error code is
- * returned on errors. If the result set contains fewer than two
- * columns, a MDB2_ERROR_TRUNCATED error is returned.
- *
- * For example, if the table 'mytable' contains:
- * <pre>
- * ID TEXT DATE
- * --------------------------------
- * 1 'one' 944679408
- * 2 'two' 944679408
- * 3 'three' 944679408
- * </pre>
- * Then the call getAssoc('SELECT id,text FROM mytable') returns:
- * <pre>
- * array(
- * '1' => 'one',
- * '2' => 'two',
- * '3' => 'three',
- * )
- * </pre>
- * ...while the call getAssoc('SELECT id,text,date FROM mytable') returns:
- * <pre>
- * array(
- * '1' => array('one', '944679408'),
- * '2' => array('two', '944679408'),
- * '3' => array('three', '944679408')
- * )
- * </pre>
- *
- * If the more than one row occurs with the same value in the
- * first column, the last row overwrites all previous ones by
- * default. Use the $group parameter if you don't want to
- * overwrite like this. Example:
- * <pre>
- * getAssoc('SELECT category,id,name FROM mytable', null, null
- * MDB2_FETCHMODE_ASSOC, false, true) returns:
- * array(
- * '1' => array(array('id' => '4', 'name' => 'number four'),
- * array('id' => '6', 'name' => 'number six')
- * ),
- * '9' => array(array('id' => '4', 'name' => 'number four'),
- * array('id' => '6', 'name' => 'number six')
- * )
- * )
- * </pre>
- *
- * Keep in mind that database functions in PHP usually return string
- * values for results regardless of the database's internal type.
- *
- * @param string the SQL query
- * @param array that contains the types of the columns in the result set
- * @param array if supplied, prepare/execute will be used
- * with this array as execute parameters
- * @param array that contains the types of the values defined in $params
- * @param bool $force_array used only when the query returns
- * exactly two columns. If TRUE, the values of the returned array
- * will be one-element arrays instead of scalars.
- * @param bool $group if TRUE, the values of the returned array
- * is wrapped in another array. If the same key value (in the first
- * column) repeats itself, the values will be appended to this array
- * instead of overwriting the existing values.
- *
- * @return array|MDB2_Error data on success, a MDB2 error on failure
- * @access public
- */
- function getAssoc($query, $types = null, $params = array(), $param_types = null,
- $fetchmode = MDB2_FETCHMODE_DEFAULT, $force_array = false, $group = false)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- settype($params, 'array');
- if (empty($params)) {
- return $db->queryAll($query, $types, $fetchmode, true, $force_array, $group);
- }
-
- $stmt = $db->prepare($query, $param_types, $types);
- if (PEAR::isError($stmt)) {
- return $stmt;
- }
-
- $result = $stmt->execute($params);
- if (!MDB2::isResultCommon($result)) {
- return $result;
- }
-
- $all = $result->fetchAll($fetchmode, true, $force_array, $group);
- $stmt->free();
- $result->free();
- return $all;
- }
-
- // }}}
- // {{{ executeMultiple()
-
- /**
- * This function does several execute() calls on the same statement handle.
- * $params must be an array indexed numerically from 0, one execute call is
- * done for every 'row' in the array.
- *
- * If an error occurs during execute(), executeMultiple() does not execute
- * the unfinished rows, but rather returns that error.
- *
- * @param resource query handle from prepare()
- * @param array numeric array containing the data to insert into the query
- *
- * @return bool|MDB2_Error true on success, a MDB2 error on failure
- * @access public
- * @see prepare(), execute()
- */
- function executeMultiple(&$stmt, $params = null)
- {
- for ($i = 0, $j = count($params); $i < $j; $i++) {
- $result = $stmt->execute($params[$i]);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ getBeforeID()
-
- /**
- * Returns the next free id of a sequence if the RDBMS
- * does not support auto increment
- *
- * @param string name of the table into which a new row was inserted
- * @param string name of the field into which a new row was inserted
- * @param bool when true the sequence is automatic created, if it not exists
- * @param bool if the returned value should be quoted
- *
- * @return int|MDB2_Error id on success, a MDB2 error on failure
- * @access public
- */
- function getBeforeID($table, $field = null, $ondemand = true, $quote = true)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if ($db->supports('auto_increment') !== true) {
- $seq = $table.(empty($field) ? '' : '_'.$field);
- $id = $db->nextID($seq, $ondemand);
- if (!$quote || PEAR::isError($id)) {
- return $id;
- }
- return $db->quote($id, 'integer');
- } elseif (!$quote) {
- return null;
- }
- return 'NULL';
- }
-
- // }}}
- // {{{ getAfterID()
-
- /**
- * Returns the autoincrement ID if supported or $id
- *
- * @param mixed value as returned by getBeforeId()
- * @param string name of the table into which a new row was inserted
- * @param string name of the field into which a new row was inserted
- *
- * @return int|MDB2_Error id on success, a MDB2 error on failure
- * @access public
- */
- function getAfterID($id, $table, $field = null)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if ($db->supports('auto_increment') !== true) {
- return $id;
- }
- return $db->lastInsertID($table, $field);
- }
-
- // }}}
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP version 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2006 Manuel Lemos, Tomas V.V.Cox, |
-// | Stig. S. Bakken, Lukas Smith |
-// | All rights reserved. |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
-// | API as well as database abstraction for PHP applications. |
-// | This LICENSE is in the BSD license style. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | |
-// | Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution. |
-// | |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
-// | POSSIBILITY OF SUCH DAMAGE. |
-// +----------------------------------------------------------------------+
-// | Author: Lukas Smith <smith@pooteeweet.org> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Iterator.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
-
-/**
- * PHP5 Iterator
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Iterator implements Iterator
-{
- protected $fetchmode;
- protected $result;
- protected $row;
-
- // {{{ constructor
-
- /**
- * Constructor
- */
- public function __construct($result, $fetchmode = MDB2_FETCHMODE_DEFAULT)
- {
- $this->result = $result;
- $this->fetchmode = $fetchmode;
- }
- // }}}
-
- // {{{ seek()
-
- /**
- * Seek forward to a specific row in a result set
- *
- * @param int number of the row where the data can be found
- *
- * @return void
- * @access public
- */
- public function seek($rownum)
- {
- $this->row = null;
- if ($this->result) {
- $this->result->seek($rownum);
- }
- }
- // }}}
-
- // {{{ next()
-
- /**
- * Fetch next row of data
- *
- * @return void
- * @access public
- */
- public function next()
- {
- $this->row = null;
- }
- // }}}
-
- // {{{ current()
-
- /**
- * return a row of data
- *
- * @return void
- * @access public
- */
- public function current()
- {
- if (is_null($this->row)) {
- $row = $this->result->fetchRow($this->fetchmode);
- if (PEAR::isError($row)) {
- $row = false;
- }
- $this->row = $row;
- }
- return $this->row;
- }
- // }}}
-
- // {{{ valid()
-
- /**
- * Check if the end of the result set has been reached
- *
- * @return bool true/false, false is also returned on failure
- * @access public
- */
- public function valid()
- {
- return (bool)$this->current();
- }
- // }}}
-
- // {{{ free()
-
- /**
- * Free the internal resources associated with result.
- *
- * @return bool|MDB2_Error true on success, false|MDB2_Error if result is invalid
- * @access public
- */
- public function free()
- {
- if ($this->result) {
- return $this->result->free();
- }
- $this->result = false;
- $this->row = null;
- return false;
- }
- // }}}
-
- // {{{ key()
-
- /**
- * Returns the row number
- *
- * @return int|bool|MDB2_Error true on success, false|MDB2_Error if result is invalid
- * @access public
- */
- public function key()
- {
- if ($this->result) {
- return $this->result->rowCount();
- }
- return false;
- }
- // }}}
-
- // {{{ rewind()
-
- /**
- * Seek to the first row in a result set
- *
- * @return void
- * @access public
- */
- public function rewind()
- {
- }
- // }}}
-
- // {{{ destructor
-
- /**
- * Destructor
- */
- public function __destruct()
- {
- $this->free();
- }
- // }}}
-}
-
-/**
- * PHP5 buffered Iterator
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_BufferedIterator extends MDB2_Iterator implements SeekableIterator
-{
- // {{{ valid()
-
- /**
- * Check if the end of the result set has been reached
- *
- * @return bool|MDB2_Error true on success, false|MDB2_Error if result is invalid
- * @access public
- */
- public function valid()
- {
- if ($this->result) {
- return $this->result->valid();
- }
- return false;
- }
- // }}}
-
- // {{{count()
-
- /**
- * Returns the number of rows in a result object
- *
- * @return int|MDB2_Error number of rows, false|MDB2_Error if result is invalid
- * @access public
- */
- public function count()
- {
- if ($this->result) {
- return $this->result->numRows();
- }
- return false;
- }
- // }}}
-
- // {{{ rewind()
-
- /**
- * Seek to the first row in a result set
- *
- * @return void
- * @access public
- */
- public function rewind()
- {
- $this->seek(0);
- }
- // }}}
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP version 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2006 Manuel Lemos, Tomas V.V.Cox, |
-// | Stig. S. Bakken, Lukas Smith |
-// | All rights reserved. |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
-// | API as well as database abstraction for PHP applications. |
-// | This LICENSE is in the BSD license style. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | |
-// | Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution. |
-// | |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
-// | POSSIBILITY OF SUCH DAMAGE. |
-// +----------------------------------------------------------------------+
-// | Author: Lukas Smith <smith@pooteeweet.org> |
-// +----------------------------------------------------------------------+
-//
-// $Id: LOB.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
-
-/**
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-
-require_once 'MDB2.php';
-
-/**
- * MDB2_LOB: user land stream wrapper implementation for LOB support
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_LOB
-{
- /**
- * contains the key to the global MDB2 instance array of the associated
- * MDB2 instance
- *
- * @var integer
- * @access protected
- */
- var $db_index;
-
- /**
- * contains the key to the global MDB2_LOB instance array of the associated
- * MDB2_LOB instance
- *
- * @var integer
- * @access protected
- */
- var $lob_index;
-
- // {{{ stream_open()
-
- /**
- * open stream
- *
- * @param string specifies the URL that was passed to fopen()
- * @param string the mode used to open the file
- * @param int holds additional flags set by the streams API
- * @param string not used
- *
- * @return bool
- * @access public
- */
- function stream_open($path, $mode, $options, &$opened_path)
- {
- if (!preg_match('/^rb?\+?$/', $mode)) {
- return false;
- }
- $url = parse_url($path);
- if (empty($url['host'])) {
- return false;
- }
- $this->db_index = (int)$url['host'];
- if (!isset($GLOBALS['_MDB2_databases'][$this->db_index])) {
- return false;
- }
- $db =& $GLOBALS['_MDB2_databases'][$this->db_index];
- $this->lob_index = (int)$url['user'];
- if (!isset($db->datatype->lobs[$this->lob_index])) {
- return false;
- }
- return true;
- }
- // }}}
-
- // {{{ stream_read()
-
- /**
- * read stream
- *
- * @param int number of bytes to read
- *
- * @return string
- * @access public
- */
- function stream_read($count)
- {
- if (isset($GLOBALS['_MDB2_databases'][$this->db_index])) {
- $db =& $GLOBALS['_MDB2_databases'][$this->db_index];
- $db->datatype->_retrieveLOB($db->datatype->lobs[$this->lob_index]);
-
- $data = $db->datatype->_readLOB($db->datatype->lobs[$this->lob_index], $count);
- $length = strlen($data);
- if ($length == 0) {
- $db->datatype->lobs[$this->lob_index]['endOfLOB'] = true;
- }
- $db->datatype->lobs[$this->lob_index]['position'] += $length;
- return $data;
- }
- }
- // }}}
-
- // {{{ stream_write()
-
- /**
- * write stream, note implemented
- *
- * @param string data
- *
- * @return int
- * @access public
- */
- function stream_write($data)
- {
- return 0;
- }
- // }}}
-
- // {{{ stream_tell()
-
- /**
- * return the current position
- *
- * @return int current position
- * @access public
- */
- function stream_tell()
- {
- if (isset($GLOBALS['_MDB2_databases'][$this->db_index])) {
- $db =& $GLOBALS['_MDB2_databases'][$this->db_index];
- return $db->datatype->lobs[$this->lob_index]['position'];
- }
- }
- // }}}
-
- // {{{ stream_eof()
-
- /**
- * Check if stream reaches EOF
- *
- * @return bool
- * @access public
- */
- function stream_eof()
- {
- if (!isset($GLOBALS['_MDB2_databases'][$this->db_index])) {
- return true;
- }
-
- $db =& $GLOBALS['_MDB2_databases'][$this->db_index];
- $result = $db->datatype->_endOfLOB($db->datatype->lobs[$this->lob_index]);
- if (version_compare(phpversion(), "5.0", ">=")
- && version_compare(phpversion(), "5.1", "<")
- ) {
- return !$result;
- }
- return $result;
- }
- // }}}
-
- // {{{ stream_seek()
-
- /**
- * Seek stream, not implemented
- *
- * @param int offset
- * @param int whence
- *
- * @return bool
- * @access public
- */
- function stream_seek($offset, $whence)
- {
- return false;
- }
- // }}}
-
- // {{{ stream_stat()
-
- /**
- * return information about stream
- *
- * @access public
- */
- function stream_stat()
- {
- if (isset($GLOBALS['_MDB2_databases'][$this->db_index])) {
- $db =& $GLOBALS['_MDB2_databases'][$this->db_index];
- return array(
- 'db_index' => $this->db_index,
- 'lob_index' => $this->lob_index,
- );
- }
- }
- // }}}
-
- // {{{ stream_close()
-
- /**
- * close stream
- *
- * @access public
- */
- function stream_close()
- {
- if (isset($GLOBALS['_MDB2_databases'][$this->db_index])) {
- $db =& $GLOBALS['_MDB2_databases'][$this->db_index];
- if (isset($db->datatype->lobs[$this->lob_index])) {
- $db->datatype->_destroyLOB($db->datatype->lobs[$this->lob_index]);
- unset($db->datatype->lobs[$this->lob_index]);
- }
- }
- }
- // }}}
-}
-
-// register streams wrapper
-if (!stream_wrapper_register("MDB2LOB", "MDB2_LOB")) {
- MDB2::raiseError();
- return false;
-}
-
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Ian Eure <ieure@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Type.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
-
-require_once 'PEAR.php';
-
-$_fileCmd = &PEAR::getStaticProperty('MIME_Type', 'fileCmd');
-$_fileCmd = 'file';
-
-/**
- * Class for working with MIME types
- *
- * @version @version@
- * @package @package@
- * @author Ian Eure <ieure@php.net>
- */
-class MIME_Type {
- /**
- * The MIME media type
- *
- * @var string
- */
- var $media = '';
-
- /**
- * The MIME media sub-type
- *
- * @var string
- */
- var $subType = '';
-
- /**
- * Optional MIME parameters
- *
- * @var array
- */
- var $parameters = array();
-
- /**
- * List of valid media types
- *
- * @var array
- */
- var $validMediaTypes = array(
- 'text',
- 'image',
- 'audio',
- 'video',
- 'application',
- 'multipart',
- 'message'
- );
-
-
- /**
- * Constructor.
- *
- * If $type is set, if will be parsed and the appropriate class vars set. If not,
- * you get an empty class. This is useful, but not quite as useful as parsing a
- * type.
- *
- * @param string $type MIME type
- * @return void
- */
- function MIME_Type($type = false)
- {
- if ($type) {
- $this->parse($type);
- }
- }
-
-
- /**
- * Parse a mime-type
- *
- * @param $type string MIME type to parse
- * @return void
- */
- function parse($type)
- {
- $this->media = $this->getMedia($type);
- $this->subType = $this->getSubType($type);
- if (MIME_Type::hasParameters($type)) {
- require_once 'MIME/Type/Parameter.php';
- foreach (MIME_Type::getParameters($type) as $param) {
- $param = &new MIME_Type_Parameter($param);
- $this->parameters[$param->name] = $param;
- }
- }
- }
-
-
- /**
- * Does this type have any parameters?
- *
- * @param $type string MIME type to check
- * @return boolean true if $type has parameters, false otherwise
- * @static
- */
- function hasParameters($type)
- {
- if (strstr($type, ';')) {
- return true;
- }
- return false;
- }
-
-
- /**
- * Get a MIME type's parameters
- *
- * @param $type string MIME type to get parameters of
- * @return array $type's parameters
- * @static
- */
- function getParameters($type)
- {
- $params = array();
- $tmp = explode(';', $type);
- for ($i = 1; $i < count($tmp); $i++) {
- $params[] = trim($tmp[$i]);
- }
- return $params;
- }
-
-
- /**
- * Strip paramaters from a MIME type string
- *
- * @param string $type MIME type string
- * @return string MIME type with parameters removed
- * @static
- */
- function stripParameters($type)
- {
- if (strstr($type, ';')) {
- return substr($type, 0, strpos($type, ';'));
- }
- return $type;
- }
-
-
- /**
- * Get a MIME type's media
- *
- * @note 'media' refers to the portion before the first slash
- * @param $type string MIME type to get media of
- * @return string $type's media
- * @static
- */
- function getMedia($type)
- {
- $tmp = explode('/', $type);
- return strtolower($tmp[0]);
- }
-
-
- /**
- * Get a MIME type's subtype
- *
- * @param $type string MIME type to get subtype of
- * @return string $type's subtype
- * @static
- */
- function getSubType($type)
- {
- $tmp = explode('/', $type);
- $tmp = explode(';', $tmp[1]);
- return strtolower(trim($tmp[0]));
- }
-
-
- /**
- * Create a textual MIME type from object values
- *
- * This function performs the opposite function of parse().
- *
- * @return string MIME type string
- */
- function get()
- {
- $type = strtolower($this->media.'/'.$this->subType);
- if (count($this->parameters)) {
- foreach ($this->parameters as $key => $null) {
- $type .= '; '.$this->parameters[$key]->get();
- }
- }
- return $type;
- }
-
-
- /**
- * Is this type experimental?
- *
- * @note Experimental types are denoted by a leading 'x-' in the media or
- * subtype, e.g. text/x-vcard or x-world/x-vrml.
- * @param string $type MIME type to check
- * @return boolean true if $type is experimental, false otherwise
- * @static
- */
- function isExperimental($type)
- {
- if (substr(MIME_Type::getMedia($type), 0, 2) == 'x-' ||
- substr(MIME_Type::getSubType($type), 0, 2) == 'x-') {
- return true;
- }
- return false;
- }
-
-
- /**
- * Is this a vendor MIME type?
- *
- * @note Vendor types are denoted with a leading 'vnd. in the subtype.
- * @param string $type MIME type to check
- * @return boolean true if $type is a vendor type, false otherwise
- * @static
- */
- function isVendor($type)
- {
- if (substr(MIME_Type::getSubType($type), 0, 4) == 'vnd.') {
- return true;
- }
- return false;
- }
-
-
- /**
- * Is this a wildcard type?
- *
- * @param string $type MIME type to check
- * @return boolean true if $type is a wildcard, false otherwise
- * @static
- */
- function isWildcard($type)
- {
- if ($type == '*/*' || MIME_Type::getSubtype($type) == '*') {
- return true;
- }
- return false;
- }
-
-
- /**
- * Perform a wildcard match on a MIME type
- *
- * Example:
- * MIME_Type::wildcardMatch('image/*', 'image/png')
- *
- * @param string $card Wildcard to check against
- * @param string $type MIME type to check
- * @return boolean true if there was a match, false otherwise
- */
- function wildcardMatch($card, $type)
- {
- if (!MIME_Type::isWildcard($card)) {
- return false;
- }
-
- if ($card == '*/*') {
- return true;
- }
-
- if (MIME_Type::getMedia($card) ==
- MIME_Type::getMedia($type)) {
- return true;
- }
- return false;
- }
-
-
- /**
- * Add a parameter to this type
- *
- * @param string $name Attribute name
- * @param string $value Attribute value
- * @param string $comment Comment for this parameter
- * @return void
- */
- function addParameter($name, $value, $comment = false)
- {
- $tmp = &new MIME_Type_Parameter;
- $tmp->name = $name;
- $tmp->value = $value;
- $tmp->comment = $comment;
- $this->parameters[$name] = $tmp;
- }
-
-
- /**
- * Remove a parameter from this type
- *
- * @param string $name Parameter name
- * @return void
- */
- function removeParameter($name)
- {
- unset ($this->parameters[$name]);
- }
-
-
- /**
- * Autodetect a file's MIME-type
- *
- * This function may be called staticly.
- *
- * @param string $file Path to the file to get the type of
- * @param bool $params Append MIME parameters if true
- * @return string $file's MIME-type on success, PEAR_Error otherwise
- * @since 1.0.0beta1
- * @static
- */
- function autoDetect($file, $params = false)
- {
- @include_once 'System/Command.php';
- if (function_exists('mime_content_type')) {
- $type = mime_content_type($file);
- } else if (class_exists('System_Command')) {
- $type = MIME_Type::_fileAutoDetect($file);
- } else {
- return PEAR::raiseError("Sorry, can't autodetect; you need the mime_magic extension or System_Command and 'file' installed to use this function.");
- }
-
- // _fileAutoDetect() may have returned an error.
- if (PEAR::isError($type)) {
- return $type;
- }
-
- // Don't return an empty string
- if (!$type || !strlen($type)) {
- return PEAR::raiseError("Sorry, couldn't determine file type.");
- }
-
- // Strip parameters if present & requested
- if (MIME_Type::hasParameters($type) && !$params) {
- $type = MIME_Type::stripParameters($type);
- }
-
- return $type;
- }
-
- /**
- * Autodetect a file's MIME-type with 'file' and System_Command
- *
- * This function may be called staticly.
- *
- * @param string $file Path to the file to get the type of
- * @return string $file's MIME-type
- * @since 1.0.0beta1
- * @static
- */
- function _fileAutoDetect($file)
- {
- // Sanity checks
- if (!file_exists($file)) {
- return PEAR::raiseError("File \"$file\" doesn't exist");
- }
-
- if (!is_readable($file)) {
- return PEAR::raiseError("File \"$file\" is not readable");
- }
-
- $cmd = new System_Command;
-
-
- // Make sure we have the 'file' command.
- $fileCmd = PEAR::getStaticProperty('MIME_Type', 'fileCmd');
- if (!$cmd->which($fileCmd)) {
- unset($cmd);
- return PEAR::raiseError("Can't find file command \"{$fileCmd}\"");
- }
-
- $cmd->pushCommand($fileCmd, "-bi '{$file}'");
- $res = $cmd->execute();
- unset($cmd);
-
- return $res;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Ian Eure <ieure@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Parameter.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
-
-/**
- * Class for working with MIME type parameters
- *
- * @version @version@
- * @package @package@
- * @author Ian Eure <ieure@php.net>
- */
-class MIME_Type_Parameter {
- /**
- * Parameter name
- *
- * @var string
- */
- var $name;
-
- /**
- * Parameter value
- *
- * @var string
- */
- var $value;
-
- /**
- * Parameter comment
- *
- * @var string
- */
- var $comment;
-
-
- /**
- * Constructor.
- *
- * @param string $param MIME parameter to parse, if set.
- * @return void
- */
- function MIME_Type_Parameter($param = false)
- {
- if ($param) {
- $this->parse($param);
- }
- }
-
-
- /**
- * Parse a MIME type parameter and set object fields
- *
- * @param string $param MIME type parameter to parse
- * @return void
- */
- function parse($param)
- {
- $this->name = $this->getAttribute($param);
- $this->value = $this->getValue($param);
- if ($this->hasComment($param)) {
- $this->comment = $this->getComment($param);
- }
- }
-
-
- /**
- * Get a parameter attribute (e.g. name)
- *
- * @param string MIME type parameter
- * @return string Attribute name
- * @static
- */
- function getAttribute($param)
- {
- $tmp = explode('=', $param);
- return trim($tmp[0]);
- }
-
-
- /**
- * Get a parameter value
- *
- * @param string $param MIME type parameter
- * @return string Value
- * @static
- */
- function getValue($param)
- {
- $tmp = explode('=', $param);
- $value = $tmp[1];
- if (MIME_Type_Parameter::hasComment($param)) {
- $cs = strpos($value, '(');
- $value = substr($value, 0, $cs);
- }
- return trim($value, '" ');
- }
-
-
- /**
- * Get a parameter comment
- *
- * @param string $param MIME type parameter
- * @return string Parameter comment
- * @see getComment()
- * @static
- */
- function getComment($param)
- {
- $cs = strpos($param, '(');
- $comment = substr($param, $cs);
- return trim($comment, '() ');
- }
-
-
- /**
- * Does this parameter have a comment?
- *
- * @param string $param MIME type parameter
- * @return boolean true if $param has a comment, false otherwise
- * @static
- */
- function hasComment($param)
- {
- if (strstr($param, '(')) {
- return true;
- }
- return false;
- }
-
-
- /**
- * Get a string representation of this parameter
- *
- * This function performs the oppsite of parse()
- *
- * @return string String representation of parameter
- */
- function get()
- {
- $val = $this->name.'="'.$this->value.'"';
- if ($this->comment) {
- $val .= ' ('.$this->comment.')';
- }
- return $val;
- }
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Chuck Hagenbuch <chuck@horde.org> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Mail.php,v 1.1.1.1 2008/04/28 15:20:46 jamie Exp $
-
-require_once 'PEAR.php';
-
-/**
- * PEAR's Mail:: interface. Defines the interface for implementing
- * mailers under the PEAR hierarchy, and provides supporting functions
- * useful in multiple mailer backends.
- *
- * @access public
- * @version $Revision: 1.1.1.1 $
- * @package Mail
- */
-class Mail
-{
- /**
- * Line terminator used for separating header lines.
- * @var string
- */
- var $sep = "\r\n";
-
- /**
- * Provides an interface for generating Mail:: objects of various
- * types
- *
- * @param string $driver The kind of Mail:: object to instantiate.
- * @param array $params The parameters to pass to the Mail:: object.
- * @return object Mail a instance of the driver class or if fails a PEAR Error
- * @access public
- */
- function &factory($driver, $params = array())
- {
- $driver = strtolower($driver);
- @include_once 'Mail/' . $driver . '.php';
- $class = 'Mail_' . $driver;
- if (class_exists($class)) {
- $mailer = new $class($params);
- return $mailer;
- } else {
- return PEAR::raiseError('Unable to find class for driver ' . $driver);
- }
- }
-
- /**
- * Implements Mail::send() function using php's built-in mail()
- * command.
- *
- * @param mixed $recipients Either a comma-seperated list of recipients
- * (RFC822 compliant), or an array of recipients,
- * each RFC822 valid. This may contain recipients not
- * specified in the headers, for Bcc:, resending
- * messages, etc.
- *
- * @param array $headers The array of headers to send with the mail, in an
- * associative array, where the array key is the
- * header name (ie, 'Subject'), and the array value
- * is the header value (ie, 'test'). The header
- * produced from those values would be 'Subject:
- * test'.
- *
- * @param string $body The full text of the message body, including any
- * Mime parts, etc.
- *
- * @return mixed Returns true on success, or a PEAR_Error
- * containing a descriptive error message on
- * failure.
- * @access public
- * @deprecated use Mail_mail::send instead
- */
- function send($recipients, $headers, $body)
- {
- $this->_sanitizeHeaders($headers);
-
- // if we're passed an array of recipients, implode it.
- if (is_array($recipients)) {
- $recipients = implode(', ', $recipients);
- }
-
- // get the Subject out of the headers array so that we can
- // pass it as a seperate argument to mail().
- $subject = '';
- if (isset($headers['Subject'])) {
- $subject = $headers['Subject'];
- unset($headers['Subject']);
- }
-
- // flatten the headers out.
- list(,$text_headers) = Mail::prepareHeaders($headers);
-
- return mail($recipients, $subject, $body, $text_headers);
-
- }
-
- /**
- * Sanitize an array of mail headers by removing any additional header
- * strings present in a legitimate header's value. The goal of this
- * filter is to prevent mail injection attacks.
- *
- * @param array $headers The associative array of headers to sanitize.
- *
- * @access private
- */
- function _sanitizeHeaders(&$headers)
- {
- foreach ($headers as $key => $value) {
- $headers[$key] =
- preg_replace('=((<CR>|<LF>|0x0A/%0A|0x0D/%0D|\\n|\\r)\S).*=i',
- null, $value);
- }
- }
-
- /**
- * Take an array of mail headers and return a string containing
- * text usable in sending a message.
- *
- * @param array $headers The array of headers to prepare, in an associative
- * array, where the array key is the header name (ie,
- * 'Subject'), and the array value is the header
- * value (ie, 'test'). The header produced from those
- * values would be 'Subject: test'.
- *
- * @return mixed Returns false if it encounters a bad address,
- * otherwise returns an array containing two
- * elements: Any From: address found in the headers,
- * and the plain text version of the headers.
- * @access private
- */
- function prepareHeaders($headers)
- {
- $lines = array();
- $from = null;
-
- foreach ($headers as $key => $value) {
- if (strcasecmp($key, 'From') === 0) {
- include_once 'Mail/RFC822.php';
- $parser = &new Mail_RFC822();
- $addresses = $parser->parseAddressList($value, 'localhost', false);
- if (PEAR::isError($addresses)) {
- return $addresses;
- }
-
- $from = $addresses[0]->mailbox . '@' . $addresses[0]->host;
-
- // Reject envelope From: addresses with spaces.
- if (strstr($from, ' ')) {
- return false;
- }
-
- $lines[] = $key . ': ' . $value;
- } elseif (strcasecmp($key, 'Received') === 0) {
- $received = array();
- if (is_array($value)) {
- foreach ($value as $line) {
- $received[] = $key . ': ' . $line;
- }
- }
- else {
- $received[] = $key . ': ' . $value;
- }
- // Put Received: headers at the top. Spam detectors often
- // flag messages with Received: headers after the Subject:
- // as spam.
- $lines = array_merge($received, $lines);
- } else {
- // If $value is an array (i.e., a list of addresses), convert
- // it to a comma-delimited string of its elements (addresses).
- if (is_array($value)) {
- $value = implode(', ', $value);
- }
- $lines[] = $key . ': ' . $value;
- }
- }
-
- return array($from, join($this->sep, $lines));
- }
-
- /**
- * Take a set of recipients and parse them, returning an array of
- * bare addresses (forward paths) that can be passed to sendmail
- * or an smtp server with the rcpt to: command.
- *
- * @param mixed Either a comma-seperated list of recipients
- * (RFC822 compliant), or an array of recipients,
- * each RFC822 valid.
- *
- * @return mixed An array of forward paths (bare addresses) or a PEAR_Error
- * object if the address list could not be parsed.
- * @access private
- */
- function parseRecipients($recipients)
- {
- include_once 'Mail/RFC822.php';
-
- // if we're passed an array, assume addresses are valid and
- // implode them before parsing.
- if (is_array($recipients)) {
- $recipients = implode(', ', $recipients);
- }
-
- // Parse recipients, leaving out all personal info. This is
- // for smtp recipients, etc. All relevant personal information
- // should already be in the headers.
- $addresses = Mail_RFC822::parseAddressList($recipients, 'localhost', false);
-
- // If parseAddressList() returned a PEAR_Error object, just return it.
- if (PEAR::isError($addresses)) {
- return $addresses;
- }
-
- $recipients = array();
- if (is_array($addresses)) {
- foreach ($addresses as $ob) {
- $recipients[] = $ob->mailbox . '@' . $ob->host;
- }
- }
-
- return $recipients;
- }
-
-}
+++ /dev/null
-<?php
-// +-----------------------------------------------------------------------+
-// | Copyright (c) 2001-2002, Richard Heyes |
-// | All rights reserved. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | o Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | o Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution.|
-// | o The names of the authors may not be used to endorse or promote |
-// | products derived from this software without specific prior written |
-// | permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
-// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT |
-// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
-// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
-// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
-// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
-// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
-// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
-// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
-// | |
-// +-----------------------------------------------------------------------+
-// | Authors: Richard Heyes <richard@phpguru.org> |
-// | Chuck Hagenbuch <chuck@horde.org> |
-// +-----------------------------------------------------------------------+
-
-/**
- * RFC 822 Email address list validation Utility
- *
- * What is it?
- *
- * This class will take an address string, and parse it into it's consituent
- * parts, be that either addresses, groups, or combinations. Nested groups
- * are not supported. The structure it returns is pretty straight forward,
- * and is similar to that provided by the imap_rfc822_parse_adrlist(). Use
- * print_r() to view the structure.
- *
- * How do I use it?
- *
- * $address_string = 'My Group: "Richard" <richard@localhost> (A comment), ted@example.com (Ted Bloggs), Barney;';
- * $structure = Mail_RFC822::parseAddressList($address_string, 'example.com', true)
- * print_r($structure);
- *
- * @author Richard Heyes <richard@phpguru.org>
- * @author Chuck Hagenbuch <chuck@horde.org>
- * @version $Revision: 1.1.1.1 $
- * @license BSD
- * @package Mail
- */
-class Mail_RFC822 {
-
- /**
- * The address being parsed by the RFC822 object.
- * @var string $address
- */
- var $address = '';
-
- /**
- * The default domain to use for unqualified addresses.
- * @var string $default_domain
- */
- var $default_domain = 'localhost';
-
- /**
- * Should we return a nested array showing groups, or flatten everything?
- * @var boolean $nestGroups
- */
- var $nestGroups = true;
-
- /**
- * Whether or not to validate atoms for non-ascii characters.
- * @var boolean $validate
- */
- var $validate = true;
-
- /**
- * The array of raw addresses built up as we parse.
- * @var array $addresses
- */
- var $addresses = array();
-
- /**
- * The final array of parsed address information that we build up.
- * @var array $structure
- */
- var $structure = array();
-
- /**
- * The current error message, if any.
- * @var string $error
- */
- var $error = null;
-
- /**
- * An internal counter/pointer.
- * @var integer $index
- */
- var $index = null;
-
- /**
- * The number of groups that have been found in the address list.
- * @var integer $num_groups
- * @access public
- */
- var $num_groups = 0;
-
- /**
- * A variable so that we can tell whether or not we're inside a
- * Mail_RFC822 object.
- * @var boolean $mailRFC822
- */
- var $mailRFC822 = true;
-
- /**
- * A limit after which processing stops
- * @var int $limit
- */
- var $limit = null;
-
- /**
- * Sets up the object. The address must either be set here or when
- * calling parseAddressList(). One or the other.
- *
- * @access public
- * @param string $address The address(es) to validate.
- * @param string $default_domain Default domain/host etc. If not supplied, will be set to localhost.
- * @param boolean $nest_groups Whether to return the structure with groups nested for easier viewing.
- * @param boolean $validate Whether to validate atoms. Turn this off if you need to run addresses through before encoding the personal names, for instance.
- *
- * @return object Mail_RFC822 A new Mail_RFC822 object.
- */
- function Mail_RFC822($address = null, $default_domain = null, $nest_groups = null, $validate = null, $limit = null)
- {
- if (isset($address)) $this->address = $address;
- if (isset($default_domain)) $this->default_domain = $default_domain;
- if (isset($nest_groups)) $this->nestGroups = $nest_groups;
- if (isset($validate)) $this->validate = $validate;
- if (isset($limit)) $this->limit = $limit;
- }
-
- /**
- * Starts the whole process. The address must either be set here
- * or when creating the object. One or the other.
- *
- * @access public
- * @param string $address The address(es) to validate.
- * @param string $default_domain Default domain/host etc.
- * @param boolean $nest_groups Whether to return the structure with groups nested for easier viewing.
- * @param boolean $validate Whether to validate atoms. Turn this off if you need to run addresses through before encoding the personal names, for instance.
- *
- * @return array A structured array of addresses.
- */
- function parseAddressList($address = null, $default_domain = null, $nest_groups = null, $validate = null, $limit = null)
- {
- if (!isset($this) || !isset($this->mailRFC822)) {
- $obj = new Mail_RFC822($address, $default_domain, $nest_groups, $validate, $limit);
- return $obj->parseAddressList();
- }
-
- if (isset($address)) $this->address = $address;
- if (isset($default_domain)) $this->default_domain = $default_domain;
- if (isset($nest_groups)) $this->nestGroups = $nest_groups;
- if (isset($validate)) $this->validate = $validate;
- if (isset($limit)) $this->limit = $limit;
-
- $this->structure = array();
- $this->addresses = array();
- $this->error = null;
- $this->index = null;
-
- // Unfold any long lines in $this->address.
- $this->address = preg_replace('/\r?\n/', "\r\n", $this->address);
- $this->address = preg_replace('/\r\n(\t| )+/', ' ', $this->address);
-
- while ($this->address = $this->_splitAddresses($this->address));
-
- if ($this->address === false || isset($this->error)) {
- require_once 'PEAR.php';
- return PEAR::raiseError($this->error);
- }
-
- // Validate each address individually. If we encounter an invalid
- // address, stop iterating and return an error immediately.
- foreach ($this->addresses as $address) {
- $valid = $this->_validateAddress($address);
-
- if ($valid === false || isset($this->error)) {
- require_once 'PEAR.php';
- return PEAR::raiseError($this->error);
- }
-
- if (!$this->nestGroups) {
- $this->structure = array_merge($this->structure, $valid);
- } else {
- $this->structure[] = $valid;
- }
- }
-
- return $this->structure;
- }
-
- /**
- * Splits an address into separate addresses.
- *
- * @access private
- * @param string $address The addresses to split.
- * @return boolean Success or failure.
- */
- function _splitAddresses($address)
- {
- if (!empty($this->limit) && count($this->addresses) == $this->limit) {
- return '';
- }
-
- if ($this->_isGroup($address) && !isset($this->error)) {
- $split_char = ';';
- $is_group = true;
- } elseif (!isset($this->error)) {
- $split_char = ',';
- $is_group = false;
- } elseif (isset($this->error)) {
- return false;
- }
-
- // Split the string based on the above ten or so lines.
- $parts = explode($split_char, $address);
- $string = $this->_splitCheck($parts, $split_char);
-
- // If a group...
- if ($is_group) {
- // If $string does not contain a colon outside of
- // brackets/quotes etc then something's fubar.
-
- // First check there's a colon at all:
- if (strpos($string, ':') === false) {
- $this->error = 'Invalid address: ' . $string;
- return false;
- }
-
- // Now check it's outside of brackets/quotes:
- if (!$this->_splitCheck(explode(':', $string), ':')) {
- return false;
- }
-
- // We must have a group at this point, so increase the counter:
- $this->num_groups++;
- }
-
- // $string now contains the first full address/group.
- // Add to the addresses array.
- $this->addresses[] = array(
- 'address' => trim($string),
- 'group' => $is_group
- );
-
- // Remove the now stored address from the initial line, the +1
- // is to account for the explode character.
- $address = trim(substr($address, strlen($string) + 1));
-
- // If the next char is a comma and this was a group, then
- // there are more addresses, otherwise, if there are any more
- // chars, then there is another address.
- if ($is_group && substr($address, 0, 1) == ','){
- $address = trim(substr($address, 1));
- return $address;
-
- } elseif (strlen($address) > 0) {
- return $address;
-
- } else {
- return '';
- }
-
- // If you got here then something's off
- return false;
- }
-
- /**
- * Checks for a group at the start of the string.
- *
- * @access private
- * @param string $address The address to check.
- * @return boolean Whether or not there is a group at the start of the string.
- */
- function _isGroup($address)
- {
- // First comma not in quotes, angles or escaped:
- $parts = explode(',', $address);
- $string = $this->_splitCheck($parts, ',');
-
- // Now we have the first address, we can reliably check for a
- // group by searching for a colon that's not escaped or in
- // quotes or angle brackets.
- if (count($parts = explode(':', $string)) > 1) {
- $string2 = $this->_splitCheck($parts, ':');
- return ($string2 !== $string);
- } else {
- return false;
- }
- }
-
- /**
- * A common function that will check an exploded string.
- *
- * @access private
- * @param array $parts The exloded string.
- * @param string $char The char that was exploded on.
- * @return mixed False if the string contains unclosed quotes/brackets, or the string on success.
- */
- function _splitCheck($parts, $char)
- {
- $string = $parts[0];
-
- for ($i = 0; $i < count($parts); $i++) {
- if ($this->_hasUnclosedQuotes($string)
- || $this->_hasUnclosedBrackets($string, '<>')
- || $this->_hasUnclosedBrackets($string, '[]')
- || $this->_hasUnclosedBrackets($string, '()')
- || substr($string, -1) == '\\') {
- if (isset($parts[$i + 1])) {
- $string = $string . $char . $parts[$i + 1];
- } else {
- $this->error = 'Invalid address spec. Unclosed bracket or quotes';
- return false;
- }
- } else {
- $this->index = $i;
- break;
- }
- }
-
- return $string;
- }
-
- /**
- * Checks if a string has an unclosed quotes or not.
- *
- * @access private
- * @param string $string The string to check.
- * @return boolean True if there are unclosed quotes inside the string, false otherwise.
- */
- function _hasUnclosedQuotes($string)
- {
- $string = explode('"', $string);
- $string_cnt = count($string);
-
- for ($i = 0; $i < (count($string) - 1); $i++)
- if (substr($string[$i], -1) == '\\')
- $string_cnt--;
-
- return ($string_cnt % 2 === 0);
- }
-
- /**
- * Checks if a string has an unclosed brackets or not. IMPORTANT:
- * This function handles both angle brackets and square brackets;
- *
- * @access private
- * @param string $string The string to check.
- * @param string $chars The characters to check for.
- * @return boolean True if there are unclosed brackets inside the string, false otherwise.
- */
- function _hasUnclosedBrackets($string, $chars)
- {
- $num_angle_start = substr_count($string, $chars[0]);
- $num_angle_end = substr_count($string, $chars[1]);
-
- $this->_hasUnclosedBracketsSub($string, $num_angle_start, $chars[0]);
- $this->_hasUnclosedBracketsSub($string, $num_angle_end, $chars[1]);
-
- if ($num_angle_start < $num_angle_end) {
- $this->error = 'Invalid address spec. Unmatched quote or bracket (' . $chars . ')';
- return false;
- } else {
- return ($num_angle_start > $num_angle_end);
- }
- }
-
- /**
- * Sub function that is used only by hasUnclosedBrackets().
- *
- * @access private
- * @param string $string The string to check.
- * @param integer &$num The number of occurences.
- * @param string $char The character to count.
- * @return integer The number of occurences of $char in $string, adjusted for backslashes.
- */
- function _hasUnclosedBracketsSub($string, &$num, $char)
- {
- $parts = explode($char, $string);
- for ($i = 0; $i < count($parts); $i++){
- if (substr($parts[$i], -1) == '\\' || $this->_hasUnclosedQuotes($parts[$i]))
- $num--;
- if (isset($parts[$i + 1]))
- $parts[$i + 1] = $parts[$i] . $char . $parts[$i + 1];
- }
-
- return $num;
- }
-
- /**
- * Function to begin checking the address.
- *
- * @access private
- * @param string $address The address to validate.
- * @return mixed False on failure, or a structured array of address information on success.
- */
- function _validateAddress($address)
- {
- $is_group = false;
- $addresses = array();
-
- if ($address['group']) {
- $is_group = true;
-
- // Get the group part of the name
- $parts = explode(':', $address['address']);
- $groupname = $this->_splitCheck($parts, ':');
- $structure = array();
-
- // And validate the group part of the name.
- if (!$this->_validatePhrase($groupname)){
- $this->error = 'Group name did not validate.';
- return false;
- } else {
- // Don't include groups if we are not nesting
- // them. This avoids returning invalid addresses.
- if ($this->nestGroups) {
- $structure = new stdClass;
- $structure->groupname = $groupname;
- }
- }
-
- $address['address'] = ltrim(substr($address['address'], strlen($groupname . ':')));
- }
-
- // If a group then split on comma and put into an array.
- // Otherwise, Just put the whole address in an array.
- if ($is_group) {
- while (strlen($address['address']) > 0) {
- $parts = explode(',', $address['address']);
- $addresses[] = $this->_splitCheck($parts, ',');
- $address['address'] = trim(substr($address['address'], strlen(end($addresses) . ',')));
- }
- } else {
- $addresses[] = $address['address'];
- }
-
- // Check that $addresses is set, if address like this:
- // Groupname:;
- // Then errors were appearing.
- if (!count($addresses)){
- $this->error = 'Empty group.';
- return false;
- }
-
- // Trim the whitespace from all of the address strings.
- array_map('trim', $addresses);
-
- // Validate each mailbox.
- // Format could be one of: name <geezer@domain.com>
- // geezer@domain.com
- // geezer
- // ... or any other format valid by RFC 822.
- for ($i = 0; $i < count($addresses); $i++) {
- if (!$this->validateMailbox($addresses[$i])) {
- if (empty($this->error)) {
- $this->error = 'Validation failed for: ' . $addresses[$i];
- }
- return false;
- }
- }
-
- // Nested format
- if ($this->nestGroups) {
- if ($is_group) {
- $structure->addresses = $addresses;
- } else {
- $structure = $addresses[0];
- }
-
- // Flat format
- } else {
- if ($is_group) {
- $structure = array_merge($structure, $addresses);
- } else {
- $structure = $addresses;
- }
- }
-
- return $structure;
- }
-
- /**
- * Function to validate a phrase.
- *
- * @access private
- * @param string $phrase The phrase to check.
- * @return boolean Success or failure.
- */
- function _validatePhrase($phrase)
- {
- // Splits on one or more Tab or space.
- $parts = preg_split('/[ \\x09]+/', $phrase, -1, PREG_SPLIT_NO_EMPTY);
-
- $phrase_parts = array();
- while (count($parts) > 0){
- $phrase_parts[] = $this->_splitCheck($parts, ' ');
- for ($i = 0; $i < $this->index + 1; $i++)
- array_shift($parts);
- }
-
- foreach ($phrase_parts as $part) {
- // If quoted string:
- if (substr($part, 0, 1) == '"') {
- if (!$this->_validateQuotedString($part)) {
- return false;
- }
- continue;
- }
-
- // Otherwise it's an atom:
- if (!$this->_validateAtom($part)) return false;
- }
-
- return true;
- }
-
- /**
- * Function to validate an atom which from rfc822 is:
- * atom = 1*<any CHAR except specials, SPACE and CTLs>
- *
- * If validation ($this->validate) has been turned off, then
- * validateAtom() doesn't actually check anything. This is so that you
- * can split a list of addresses up before encoding personal names
- * (umlauts, etc.), for example.
- *
- * @access private
- * @param string $atom The string to check.
- * @return boolean Success or failure.
- */
- function _validateAtom($atom)
- {
- if (!$this->validate) {
- // Validation has been turned off; assume the atom is okay.
- return true;
- }
-
- // Check for any char from ASCII 0 - ASCII 127
- if (!preg_match('/^[\\x00-\\x7E]+$/i', $atom, $matches)) {
- return false;
- }
-
- // Check for specials:
- if (preg_match('/[][()<>@,;\\:". ]/', $atom)) {
- return false;
- }
-
- // Check for control characters (ASCII 0-31):
- if (preg_match('/[\\x00-\\x1F]+/', $atom)) {
- return false;
- }
-
- return true;
- }
-
- /**
- * Function to validate quoted string, which is:
- * quoted-string = <"> *(qtext/quoted-pair) <">
- *
- * @access private
- * @param string $qstring The string to check
- * @return boolean Success or failure.
- */
- function _validateQuotedString($qstring)
- {
- // Leading and trailing "
- $qstring = substr($qstring, 1, -1);
-
- // Perform check, removing quoted characters first.
- return !preg_match('/[\x0D\\\\"]/', preg_replace('/\\\\./', '', $qstring));
- }
-
- /**
- * Function to validate a mailbox, which is:
- * mailbox = addr-spec ; simple address
- * / phrase route-addr ; name and route-addr
- *
- * @access public
- * @param string &$mailbox The string to check.
- * @return boolean Success or failure.
- */
- function validateMailbox(&$mailbox)
- {
- // A couple of defaults.
- $phrase = '';
- $comment = '';
- $comments = array();
-
- // Catch any RFC822 comments and store them separately.
- $_mailbox = $mailbox;
- while (strlen(trim($_mailbox)) > 0) {
- $parts = explode('(', $_mailbox);
- $before_comment = $this->_splitCheck($parts, '(');
- if ($before_comment != $_mailbox) {
- // First char should be a (.
- $comment = substr(str_replace($before_comment, '', $_mailbox), 1);
- $parts = explode(')', $comment);
- $comment = $this->_splitCheck($parts, ')');
- $comments[] = $comment;
-
- // +1 is for the trailing )
- $_mailbox = substr($_mailbox, strpos($_mailbox, $comment)+strlen($comment)+1);
- } else {
- break;
- }
- }
-
- foreach ($comments as $comment) {
- $mailbox = str_replace("($comment)", '', $mailbox);
- }
-
- $mailbox = trim($mailbox);
-
- // Check for name + route-addr
- if (substr($mailbox, -1) == '>' && substr($mailbox, 0, 1) != '<') {
- $parts = explode('<', $mailbox);
- $name = $this->_splitCheck($parts, '<');
-
- $phrase = trim($name);
- $route_addr = trim(substr($mailbox, strlen($name.'<'), -1));
-
- if ($this->_validatePhrase($phrase) === false || ($route_addr = $this->_validateRouteAddr($route_addr)) === false) {
- return false;
- }
-
- // Only got addr-spec
- } else {
- // First snip angle brackets if present.
- if (substr($mailbox, 0, 1) == '<' && substr($mailbox, -1) == '>') {
- $addr_spec = substr($mailbox, 1, -1);
- } else {
- $addr_spec = $mailbox;
- }
-
- if (($addr_spec = $this->_validateAddrSpec($addr_spec)) === false) {
- return false;
- }
- }
-
- // Construct the object that will be returned.
- $mbox = new stdClass();
-
- // Add the phrase (even if empty) and comments
- $mbox->personal = $phrase;
- $mbox->comment = isset($comments) ? $comments : array();
-
- if (isset($route_addr)) {
- $mbox->mailbox = $route_addr['local_part'];
- $mbox->host = $route_addr['domain'];
- $route_addr['adl'] !== '' ? $mbox->adl = $route_addr['adl'] : '';
- } else {
- $mbox->mailbox = $addr_spec['local_part'];
- $mbox->host = $addr_spec['domain'];
- }
-
- $mailbox = $mbox;
- return true;
- }
-
- /**
- * This function validates a route-addr which is:
- * route-addr = "<" [route] addr-spec ">"
- *
- * Angle brackets have already been removed at the point of
- * getting to this function.
- *
- * @access private
- * @param string $route_addr The string to check.
- * @return mixed False on failure, or an array containing validated address/route information on success.
- */
- function _validateRouteAddr($route_addr)
- {
- // Check for colon.
- if (strpos($route_addr, ':') !== false) {
- $parts = explode(':', $route_addr);
- $route = $this->_splitCheck($parts, ':');
- } else {
- $route = $route_addr;
- }
-
- // If $route is same as $route_addr then the colon was in
- // quotes or brackets or, of course, non existent.
- if ($route === $route_addr){
- unset($route);
- $addr_spec = $route_addr;
- if (($addr_spec = $this->_validateAddrSpec($addr_spec)) === false) {
- return false;
- }
- } else {
- // Validate route part.
- if (($route = $this->_validateRoute($route)) === false) {
- return false;
- }
-
- $addr_spec = substr($route_addr, strlen($route . ':'));
-
- // Validate addr-spec part.
- if (($addr_spec = $this->_validateAddrSpec($addr_spec)) === false) {
- return false;
- }
- }
-
- if (isset($route)) {
- $return['adl'] = $route;
- } else {
- $return['adl'] = '';
- }
-
- $return = array_merge($return, $addr_spec);
- return $return;
- }
-
- /**
- * Function to validate a route, which is:
- * route = 1#("@" domain) ":"
- *
- * @access private
- * @param string $route The string to check.
- * @return mixed False on failure, or the validated $route on success.
- */
- function _validateRoute($route)
- {
- // Split on comma.
- $domains = explode(',', trim($route));
-
- foreach ($domains as $domain) {
- $domain = str_replace('@', '', trim($domain));
- if (!$this->_validateDomain($domain)) return false;
- }
-
- return $route;
- }
-
- /**
- * Function to validate a domain, though this is not quite what
- * you expect of a strict internet domain.
- *
- * domain = sub-domain *("." sub-domain)
- *
- * @access private
- * @param string $domain The string to check.
- * @return mixed False on failure, or the validated domain on success.
- */
- function _validateDomain($domain)
- {
- // Note the different use of $subdomains and $sub_domains
- $subdomains = explode('.', $domain);
-
- while (count($subdomains) > 0) {
- $sub_domains[] = $this->_splitCheck($subdomains, '.');
- for ($i = 0; $i < $this->index + 1; $i++)
- array_shift($subdomains);
- }
-
- foreach ($sub_domains as $sub_domain) {
- if (!$this->_validateSubdomain(trim($sub_domain)))
- return false;
- }
-
- // Managed to get here, so return input.
- return $domain;
- }
-
- /**
- * Function to validate a subdomain:
- * subdomain = domain-ref / domain-literal
- *
- * @access private
- * @param string $subdomain The string to check.
- * @return boolean Success or failure.
- */
- function _validateSubdomain($subdomain)
- {
- if (preg_match('|^\[(.*)]$|', $subdomain, $arr)){
- if (!$this->_validateDliteral($arr[1])) return false;
- } else {
- if (!$this->_validateAtom($subdomain)) return false;
- }
-
- // Got here, so return successful.
- return true;
- }
-
- /**
- * Function to validate a domain literal:
- * domain-literal = "[" *(dtext / quoted-pair) "]"
- *
- * @access private
- * @param string $dliteral The string to check.
- * @return boolean Success or failure.
- */
- function _validateDliteral($dliteral)
- {
- return !preg_match('/(.)[][\x0D\\\\]/', $dliteral, $matches) && $matches[1] != '\\';
- }
-
- /**
- * Function to validate an addr-spec.
- *
- * addr-spec = local-part "@" domain
- *
- * @access private
- * @param string $addr_spec The string to check.
- * @return mixed False on failure, or the validated addr-spec on success.
- */
- function _validateAddrSpec($addr_spec)
- {
- $addr_spec = trim($addr_spec);
-
- // Split on @ sign if there is one.
- if (strpos($addr_spec, '@') !== false) {
- $parts = explode('@', $addr_spec);
- $local_part = $this->_splitCheck($parts, '@');
- $domain = substr($addr_spec, strlen($local_part . '@'));
-
- // No @ sign so assume the default domain.
- } else {
- $local_part = $addr_spec;
- $domain = $this->default_domain;
- }
-
- if (($local_part = $this->_validateLocalPart($local_part)) === false) return false;
- if (($domain = $this->_validateDomain($domain)) === false) return false;
-
- // Got here so return successful.
- return array('local_part' => $local_part, 'domain' => $domain);
- }
-
- /**
- * Function to validate the local part of an address:
- * local-part = word *("." word)
- *
- * @access private
- * @param string $local_part
- * @return mixed False on failure, or the validated local part on success.
- */
- function _validateLocalPart($local_part)
- {
- $parts = explode('.', $local_part);
- $words = array();
-
- // Split the local_part into words.
- while (count($parts) > 0){
- $words[] = $this->_splitCheck($parts, '.');
- for ($i = 0; $i < $this->index + 1; $i++) {
- array_shift($parts);
- }
- }
-
- // Validate each word.
- foreach ($words as $word) {
- // If this word contains an unquoted space, it is invalid. (6.2.4)
- if (strpos($word, ' ') && $word[0] !== '"')
- {
- return false;
- }
-
- if ($this->_validatePhrase(trim($word)) === false) return false;
- }
-
- // Managed to get here, so return the input.
- return $local_part;
- }
-
- /**
- * Returns an approximate count of how many addresses are in the
- * given string. This is APPROXIMATE as it only splits based on a
- * comma which has no preceding backslash. Could be useful as
- * large amounts of addresses will end up producing *large*
- * structures when used with parseAddressList().
- *
- * @param string $data Addresses to count
- * @return int Approximate count
- */
- function approximateCount($data)
- {
- return count(preg_split('/(?<!\\\\),/', $data));
- }
-
- /**
- * This is a email validating function separate to the rest of the
- * class. It simply validates whether an email is of the common
- * internet form: <user>@<domain>. This can be sufficient for most
- * people. Optional stricter mode can be utilised which restricts
- * mailbox characters allowed to alphanumeric, full stop, hyphen
- * and underscore.
- *
- * @param string $data Address to check
- * @param boolean $strict Optional stricter mode
- * @return mixed False if it fails, an indexed array
- * username/domain if it matches
- */
- function isValidInetAddress($data, $strict = false)
- {
- $regex = $strict ? '/^([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})$/i' : '/^([*+!.&#$|\'\\%\/0-9a-z^_`{}=?~:-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})$/i';
- if (preg_match($regex, trim($data), $matches)) {
- return array($matches[1], $matches[2]);
- } else {
- return false;
- }
- }
-
-}
+++ /dev/null
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Chuck Hagenbuch <chuck@horde.org> |
-// +----------------------------------------------------------------------+
-//
-// $Id: mail.php,v 1.1.1.1 2008/04/28 15:20:50 jamie Exp $
-
-/**
- * internal PHP-mail() implementation of the PEAR Mail:: interface.
- * @package Mail
- * @version $Revision: 1.1.1.1 $
- */
-class Mail_mail extends Mail {
-
- /**
- * Any arguments to pass to the mail() function.
- * @var string
- */
- var $_params = '';
-
- /**
- * Constructor.
- *
- * Instantiates a new Mail_mail:: object based on the parameters
- * passed in.
- *
- * @param array $params Extra arguments for the mail() function.
- */
- function Mail_mail($params = null)
- {
- /* The other mail implementations accept parameters as arrays.
- * In the interest of being consistent, explode an array into
- * a string of parameter arguments. */
- if (is_array($params)) {
- $this->_params = join(' ', $params);
- } else {
- $this->_params = $params;
- }
-
- /* Because the mail() function may pass headers as command
- * line arguments, we can't guarantee the use of the standard
- * "\r\n" separator. Instead, we use the system's native line
- * separator. */
- if (defined('PHP_EOL')) {
- $this->sep = PHP_EOL;
- } else {
- $this->sep = (strpos(PHP_OS, 'WIN') === false) ? "\n" : "\r\n";
- }
- }
-
- /**
- * Implements Mail_mail::send() function using php's built-in mail()
- * command.
- *
- * @param mixed $recipients Either a comma-seperated list of recipients
- * (RFC822 compliant), or an array of recipients,
- * each RFC822 valid. This may contain recipients not
- * specified in the headers, for Bcc:, resending
- * messages, etc.
- *
- * @param array $headers The array of headers to send with the mail, in an
- * associative array, where the array key is the
- * header name (ie, 'Subject'), and the array value
- * is the header value (ie, 'test'). The header
- * produced from those values would be 'Subject:
- * test'.
- *
- * @param string $body The full text of the message body, including any
- * Mime parts, etc.
- *
- * @return mixed Returns true on success, or a PEAR_Error
- * containing a descriptive error message on
- * failure.
- *
- * @access public
- */
- function send($recipients, $headers, $body)
- {
- $this->_sanitizeHeaders($headers);
-
- // If we're passed an array of recipients, implode it.
- if (is_array($recipients)) {
- $recipients = implode(', ', $recipients);
- }
-
- // Get the Subject out of the headers array so that we can
- // pass it as a seperate argument to mail().
- $subject = '';
- if (isset($headers['Subject'])) {
- $subject = $headers['Subject'];
- unset($headers['Subject']);
- }
-
- /*
- * Also remove the To: header. The mail() function will add its own
- * To: header based on the contents of $recipients.
- */
- unset($headers['To']);
-
- // Flatten the headers out.
- $headerElements = $this->prepareHeaders($headers);
- if (PEAR::isError($headerElements)) {
- return $headerElements;
- }
- list(, $text_headers) = $headerElements;
-
- /*
- * We only use mail()'s optional fifth parameter if the additional
- * parameters have been provided and we're not running in safe mode.
- */
- if (empty($this->_params) || ini_get('safe_mode')) {
- $result = mail($recipients, $subject, $body, $text_headers);
- } else {
- $result = mail($recipients, $subject, $body, $text_headers,
- $this->_params);
- }
-
- /*
- * If the mail() function returned failure, we need to create a
- * PEAR_Error object and return it instead of the boolean result.
- */
- if ($result === false) {
- $result = PEAR::raiseError('mail() returned failure');
- }
-
- return $result;
- }
-
-}
+++ /dev/null
-<?php
-/**
- * The Mail_Mime class is used to create MIME E-mail messages
- *
- * The Mail_Mime class provides an OO interface to create MIME
- * enabled email messages. This way you can create emails that
- * contain plain-text bodies, HTML bodies, attachments, inline
- * images and specific headers.
- *
- * Compatible with PHP versions 4 and 5
- *
- * LICENSE: This LICENSE is in the BSD license style.
- * Copyright (c) 2002-2003, Richard Heyes <richard@phpguru.org>
- * Copyright (c) 2003-2006, PEAR <pear-group@php.net>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or
- * without modification, are permitted provided that the following
- * conditions are met:
- *
- * - Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * - Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * - Neither the name of the authors, nor the names of its contributors
- * may be used to endorse or promote products derived from this
- * software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- *
- * @category Mail
- * @package Mail_Mime
- * @author Richard Heyes <richard@phpguru.org>
- * @author Tomas V.V. Cox <cox@idecnet.com>
- * @author Cipriano Groenendal <cipri@php.net>
- * @author Sean Coates <sean@php.net>
- * @copyright 2003-2006 PEAR <pear-group@php.net>
- * @license http://www.opensource.org/licenses/bsd-license.php BSD License
- * @version CVS: $Id: mime.php,v 1.1.1.1 2008/04/28 15:20:50 jamie Exp $
- * @link http://pear.php.net/package/Mail_mime
- *
- * This class is based on HTML Mime Mail class from
- * Richard Heyes <richard@phpguru.org> which was based also
- * in the mime_mail.class by Tobias Ratschiller <tobias@dnet.it>
- * and Sascha Schumann <sascha@schumann.cx>
- */
-
-
-/**
- * require PEAR
- *
- * This package depends on PEAR to raise errors.
- */
-require_once 'PEAR.php';
-
-/**
- * require Mail_mimePart
- *
- * Mail_mimePart contains the code required to
- * create all the different parts a mail can
- * consist of.
- */
-require_once 'Mail/mimePart.php';
-
-
-/**
- * The Mail_Mime class provides an OO interface to create MIME
- * enabled email messages. This way you can create emails that
- * contain plain-text bodies, HTML bodies, attachments, inline
- * images and specific headers.
- *
- * @category Mail
- * @package Mail_Mime
- * @author Richard Heyes <richard@phpguru.org>
- * @author Tomas V.V. Cox <cox@idecnet.com>
- * @author Cipriano Groenendal <cipri@php.net>
- * @author Sean Coates <sean@php.net>
- * @copyright 2003-2006 PEAR <pear-group@php.net>
- * @license http://www.opensource.org/licenses/bsd-license.php BSD License
- * @version Release: @package_version@
- * @link http://pear.php.net/package/Mail_mime
- */
-class Mail_mime
-{
- /**
- * Contains the plain text part of the email
- *
- * @var string
- * @access private
- */
- var $_txtbody;
-
- /**
- * Contains the html part of the email
- *
- * @var string
- * @access private
- */
- var $_htmlbody;
-
- /**
- * contains the mime encoded text
- *
- * @var string
- * @access private
- */
- var $_mime;
-
- /**
- * contains the multipart content
- *
- * @var string
- * @access private
- */
- var $_multipart;
-
- /**
- * list of the attached images
- *
- * @var array
- * @access private
- */
- var $_html_images = array();
-
- /**
- * list of the attachements
- *
- * @var array
- * @access private
- */
- var $_parts = array();
-
- /**
- * Build parameters
- *
- * @var array
- * @access private
- */
- var $_build_params = array();
-
- /**
- * Headers for the mail
- *
- * @var array
- * @access private
- */
- var $_headers = array();
-
- /**
- * End Of Line sequence (for serialize)
- *
- * @var string
- * @access private
- */
- var $_eol;
-
-
- /**
- * Constructor function.
- *
- * @param string $crlf what type of linebreak to use.
- * Defaults to "\r\n"
- *
- * @return void
- *
- * @access public
- */
- function Mail_mime($crlf = "\r\n")
- {
- $this->_setEOL($crlf);
- $this->_build_params = array(
- 'head_encoding' => 'quoted-printable',
- 'text_encoding' => '7bit',
- 'html_encoding' => 'quoted-printable',
- '7bit_wrap' => 998,
- 'html_charset' => 'ISO-8859-1',
- 'text_charset' => 'ISO-8859-1',
- 'head_charset' => 'ISO-8859-1'
- );
- }
-
- /**
- * wakeup function called by unserialize. It re-sets the EOL constant
- *
- * @access private
- * @return void
- */
- function __wakeup()
- {
- $this->_setEOL($this->_eol);
- }
-
-
- /**
- * Accessor function to set the body text. Body text is used if
- * it's not an html mail being sent or else is used to fill the
- * text/plain part that emails clients who don't support
- * html should show.
- *
- * @param string $data Either a string or
- * the file name with the contents
- * @param bool $isfile If true the first param should be treated
- * as a file name, else as a string (default)
- * @param bool $append If true the text or file is appended to
- * the existing body, else the old body is
- * overwritten
- *
- * @return mixed true on success or PEAR_Error object
- * @access public
- */
- function setTXTBody($data, $isfile = false, $append = false)
- {
- if (!$isfile) {
- if (!$append) {
- $this->_txtbody = $data;
- } else {
- $this->_txtbody .= $data;
- }
- } else {
- $cont = $this->_file2str($data);
- if (PEAR::isError($cont)) {
- return $cont;
- }
- if (!$append) {
- $this->_txtbody = $cont;
- } else {
- $this->_txtbody .= $cont;
- }
- }
- return true;
- }
-
- /**
- * Adds a html part to the mail.
- *
- * @param string $data either a string or the file name with the
- * contents
- * @param bool $isfile a flag that determines whether $data is a
- * filename, or a string(false, default)
- *
- * @return bool true on success
- * @access public
- */
- function setHTMLBody($data, $isfile = false)
- {
- if (!$isfile) {
- $this->_htmlbody = $data;
- } else {
- $cont = $this->_file2str($data);
- if (PEAR::isError($cont)) {
- return $cont;
- }
- $this->_htmlbody = $cont;
- }
-
- return true;
- }
-
- /**
- * Adds an image to the list of embedded images.
- *
- * @param string $file the image file name OR image data itself
- * @param string $c_type the content type
- * @param string $name the filename of the image.
- * Only used if $file is the image data.
- * @param bool $isfile whether $file is a filename or not.
- * Defaults to true
- *
- * @return bool true on success
- * @access public
- */
- function addHTMLImage($file, $c_type='application/octet-stream',
- $name = '', $isfile = true)
- {
- $filedata = ($isfile === true) ? $this->_file2str($file)
- : $file;
- if ($isfile === true) {
- $filename = ($name == '' ? $file : $name);
- } else {
- $filename = $name;
- }
- if (PEAR::isError($filedata)) {
- return $filedata;
- }
- $this->_html_images[] = array(
- 'body' => $filedata,
- 'name' => $filename,
- 'c_type' => $c_type,
- 'cid' => md5(uniqid(time()))
- );
- return true;
- }
-
- /**
- * Adds a file to the list of attachments.
- *
- * @param string $file The file name of the file to attach
- * OR the file contents itself
- * @param string $c_type The content type
- * @param string $name The filename of the attachment
- * Only use if $file is the contents
- * @param bool $isfile Whether $file is a filename or not
- * Defaults to true
- * @param string $encoding The type of encoding to use.
- * Defaults to base64.
- * Possible values: 7bit, 8bit, base64,
- * or quoted-printable.
- * @param string $disposition The content-disposition of this file
- * Defaults to attachment.
- * Possible values: attachment, inline.
- * @param string $charset The character set used in the filename
- * of this attachment.
- * @param string $language The language of the attachment
- * @param string $location The RFC 2557.4 location of the attachment
- *
- * @return mixed true on success or PEAR_Error object
- * @access public
- */
- function addAttachment($file,
- $c_type = 'application/octet-stream',
- $name = '',
- $isfile = true,
- $encoding = 'base64',
- $disposition = 'attachment',
- $charset = '',
- $language = '',
- $location = '')
- {
- $filedata = ($isfile === true) ? $this->_file2str($file)
- : $file;
- if ($isfile === true) {
- // Force the name the user supplied, otherwise use $file
- $filename = (strlen($name)) ? $name : $file;
- } else {
- $filename = $name;
- }
- if (!strlen($filename)) {
- $msg = "The supplied filename for the attachment can't be empty";
- $err = PEAR::raiseError($msg);
- return $err;
- }
- $filename = basename($filename);
- if (PEAR::isError($filedata)) {
- return $filedata;
- }
-
- $this->_parts[] = array(
- 'body' => $filedata,
- 'name' => $filename,
- 'c_type' => $c_type,
- 'encoding' => $encoding,
- 'charset' => $charset,
- 'language' => $language,
- 'location' => $location,
- 'disposition' => $disposition
- );
- return true;
- }
-
- /**
- * Get the contents of the given file name as string
- *
- * @param string $file_name path of file to process
- *
- * @return string contents of $file_name
- * @access private
- */
- function &_file2str($file_name)
- {
- if (!is_readable($file_name)) {
- $err = PEAR::raiseError('File is not readable ' . $file_name);
- return $err;
- }
- if (!$fd = fopen($file_name, 'rb')) {
- $err = PEAR::raiseError('Could not open ' . $file_name);
- return $err;
- }
- $filesize = filesize($file_name);
- if ($filesize == 0) {
- $cont = "";
- } else {
- if ($magic_quote_setting = get_magic_quotes_runtime()) {
- set_magic_quotes_runtime(0);
- }
- $cont = fread($fd, $filesize);
- if ($magic_quote_setting) {
- set_magic_quotes_runtime($magic_quote_setting);
- }
- }
- fclose($fd);
- return $cont;
- }
-
- /**
- * Adds a text subpart to the mimePart object and
- * returns it during the build process.
- *
- * @param mixed &$obj The object to add the part to, or
- * null if a new object is to be created.
- * @param string $text The text to add.
- *
- * @return object The text mimePart object
- * @access private
- */
- function &_addTextPart(&$obj, $text)
- {
- $params['content_type'] = 'text/plain';
- $params['encoding'] = $this->_build_params['text_encoding'];
- $params['charset'] = $this->_build_params['text_charset'];
- if (is_object($obj)) {
- $ret = $obj->addSubpart($text, $params);
- return $ret;
- } else {
- $ret = new Mail_mimePart($text, $params);
- return $ret;
- }
- }
-
- /**
- * Adds a html subpart to the mimePart object and
- * returns it during the build process.
- *
- * @param mixed &$obj The object to add the part to, or
- * null if a new object is to be created.
- *
- * @return object The html mimePart object
- * @access private
- */
- function &_addHtmlPart(&$obj)
- {
- $params['content_type'] = 'text/html';
- $params['encoding'] = $this->_build_params['html_encoding'];
- $params['charset'] = $this->_build_params['html_charset'];
- if (is_object($obj)) {
- $ret = $obj->addSubpart($this->_htmlbody, $params);
- return $ret;
- } else {
- $ret = new Mail_mimePart($this->_htmlbody, $params);
- return $ret;
- }
- }
-
- /**
- * Creates a new mimePart object, using multipart/mixed as
- * the initial content-type and returns it during the
- * build process.
- *
- * @return object The multipart/mixed mimePart object
- * @access private
- */
- function &_addMixedPart()
- {
- $params = array();
- $params['content_type'] = 'multipart/mixed';
-
- //Create empty multipart/mixed Mail_mimePart object to return
- $ret = new Mail_mimePart('', $params);
- return $ret;
- }
-
- /**
- * Adds a multipart/alternative part to a mimePart
- * object (or creates one), and returns it during
- * the build process.
- *
- * @param mixed &$obj The object to add the part to, or
- * null if a new object is to be created.
- *
- * @return object The multipart/mixed mimePart object
- * @access private
- */
- function &_addAlternativePart(&$obj)
- {
- $params['content_type'] = 'multipart/alternative';
- if (is_object($obj)) {
- return $obj->addSubpart('', $params);
- } else {
- $ret = new Mail_mimePart('', $params);
- return $ret;
- }
- }
-
- /**
- * Adds a multipart/related part to a mimePart
- * object (or creates one), and returns it during
- * the build process.
- *
- * @param mixed &$obj The object to add the part to, or
- * null if a new object is to be created
- *
- * @return object The multipart/mixed mimePart object
- * @access private
- */
- function &_addRelatedPart(&$obj)
- {
- $params['content_type'] = 'multipart/related';
- if (is_object($obj)) {
- return $obj->addSubpart('', $params);
- } else {
- $ret = new Mail_mimePart('', $params);
- return $ret;
- }
- }
-
- /**
- * Adds an html image subpart to a mimePart object
- * and returns it during the build process.
- *
- * @param object &$obj The mimePart to add the image to
- * @param array $value The image information
- *
- * @return object The image mimePart object
- * @access private
- */
- function &_addHtmlImagePart(&$obj, $value)
- {
- $params['content_type'] = $value['c_type'];
- $params['encoding'] = 'base64';
- $params['disposition'] = 'inline';
- $params['dfilename'] = $value['name'];
- $params['cid'] = $value['cid'];
-
- $ret = $obj->addSubpart($value['body'], $params);
- return $ret;
-
- }
-
- /**
- * Adds an attachment subpart to a mimePart object
- * and returns it during the build process.
- *
- * @param object &$obj The mimePart to add the image to
- * @param array $value The attachment information
- *
- * @return object The image mimePart object
- * @access private
- */
- function &_addAttachmentPart(&$obj, $value)
- {
- $params['dfilename'] = $value['name'];
- $params['encoding'] = $value['encoding'];
- if ($value['charset']) {
- $params['charset'] = $value['charset'];
- }
- if ($value['language']) {
- $params['language'] = $value['language'];
- }
- if ($value['location']) {
- $params['location'] = $value['location'];
- }
- $params['content_type'] = $value['c_type'];
- $params['disposition'] = isset($value['disposition']) ?
- $value['disposition'] : 'attachment';
- $ret = $obj->addSubpart($value['body'], $params);
- return $ret;
- }
-
- /**
- * Returns the complete e-mail, ready to send using an alternative
- * mail delivery method. Note that only the mailpart that is made
- * with Mail_Mime is created. This means that,
- * YOU WILL HAVE NO TO: HEADERS UNLESS YOU SET IT YOURSELF
- * using the $xtra_headers parameter!
- *
- * @param string $separation The separation etween these two parts.
- * @param array $build_params The Build parameters passed to the
- * &get() function. See &get for more info.
- * @param array $xtra_headers The extra headers that should be passed
- * to the &headers() function.
- * See that function for more info.
- * @param bool $overwrite Overwrite the existing headers with new.
- *
- * @return string The complete e-mail.
- * @access public
- */
- function getMessage(
- $separation = null,
- $build_params = null,
- $xtra_headers = null,
- $overwrite = false
- )
- {
- if ($separation === null) {
- $separation = MAIL_MIME_CRLF;
- }
- $body = $this->get($build_params);
- $head = $this->txtHeaders($xtra_headers, $overwrite);
- $mail = $head . $separation . $body;
- return $mail;
- }
-
-
- /**
- * Builds the multipart message from the list ($this->_parts) and
- * returns the mime content.
- *
- * @param array $build_params Build parameters that change the way the email
- * is built. Should be associative. Can contain:
- * head_encoding - What encoding to use for the headers.
- * Options: quoted-printable or base64
- * Default is quoted-printable
- * text_encoding - What encoding to use for plain text
- * Options: 7bit, 8bit,
- * base64, or quoted-printable
- * Default is 7bit
- * html_encoding - What encoding to use for html
- * Options: 7bit, 8bit,
- * base64, or quoted-printable
- * Default is quoted-printable
- * 7bit_wrap - Number of characters before text is
- * wrapped in 7bit encoding
- * Default is 998
- * html_charset - The character set to use for html.
- * Default is iso-8859-1
- * text_charset - The character set to use for text.
- * Default is iso-8859-1
- * head_charset - The character set to use for headers.
- * Default is iso-8859-1
- *
- * @return string The mime content
- * @access public
- */
- function &get($build_params = null)
- {
- if (isset($build_params)) {
- while (list($key, $value) = each($build_params)) {
- $this->_build_params[$key] = $value;
- }
- }
-
- if (isset($this->_headers['From'])){
- $domain = @strstr($this->_headers['From'],'@');
- //Bug #11381: Illegal characters in domain ID
- $domain = str_replace(array("<", ">", "&", "(", ")", " ", "\"", "'"), "", $domain);
- $domain = urlencode($domain);
- foreach($this->_html_images as $i => $img){
- $this->_html_images[$i]['cid'] = $this->_html_images[$i]['cid'] . $domain;
- }
- }
-
- if (count($this->_html_images) AND isset($this->_htmlbody)) {
- foreach ($this->_html_images as $key => $value) {
- $regex = array();
- $regex[] = '#(\s)((?i)src|background|href(?-i))\s*=\s*(["\']?)' .
- preg_quote($value['name'], '#') . '\3#';
- $regex[] = '#(?i)url(?-i)\(\s*(["\']?)' .
- preg_quote($value['name'], '#') . '\1\s*\)#';
-
- $rep = array();
- $rep[] = '\1\2=\3cid:' . $value['cid'] .'\3';
- $rep[] = 'url(\1cid:' . $value['cid'] . '\2)';
-
- $this->_htmlbody = preg_replace($regex, $rep, $this->_htmlbody);
- $this->_html_images[$key]['name'] =
- basename($this->_html_images[$key]['name']);
- }
- }
-
- $null = null;
- $attachments = count($this->_parts) ? true : false;
- $html_images = count($this->_html_images) ? true : false;
- $html = strlen($this->_htmlbody) ? true : false;
- $text = (!$html AND strlen($this->_txtbody)) ? true : false;
-
- switch (true) {
- case $text AND !$attachments:
- $message =& $this->_addTextPart($null, $this->_txtbody);
- break;
-
- case !$text AND !$html AND $attachments:
- $message =& $this->_addMixedPart();
- for ($i = 0; $i < count($this->_parts); $i++) {
- $this->_addAttachmentPart($message, $this->_parts[$i]);
- }
- break;
-
- case $text AND $attachments:
- $message =& $this->_addMixedPart();
- $this->_addTextPart($message, $this->_txtbody);
- for ($i = 0; $i < count($this->_parts); $i++) {
- $this->_addAttachmentPart($message, $this->_parts[$i]);
- }
- break;
-
- case $html AND !$attachments AND !$html_images:
- if (isset($this->_txtbody)) {
- $message =& $this->_addAlternativePart($null);
- $this->_addTextPart($message, $this->_txtbody);
- $this->_addHtmlPart($message);
- } else {
- $message =& $this->_addHtmlPart($null);
- }
- break;
-
- case $html AND !$attachments AND $html_images:
- $message =& $this->_addRelatedPart($null);
- if (isset($this->_txtbody)) {
- $alt =& $this->_addAlternativePart($message);
- $this->_addTextPart($alt, $this->_txtbody);
- $this->_addHtmlPart($alt);
- } else {
- $this->_addHtmlPart($message);
- }
- for ($i = 0; $i < count($this->_html_images); $i++) {
- $this->_addHtmlImagePart($message, $this->_html_images[$i]);
- }
- break;
-
- case $html AND $attachments AND !$html_images:
- $message =& $this->_addMixedPart();
- if (isset($this->_txtbody)) {
- $alt =& $this->_addAlternativePart($message);
- $this->_addTextPart($alt, $this->_txtbody);
- $this->_addHtmlPart($alt);
- } else {
- $this->_addHtmlPart($message);
- }
- for ($i = 0; $i < count($this->_parts); $i++) {
- $this->_addAttachmentPart($message, $this->_parts[$i]);
- }
- break;
-
- case $html AND $attachments AND $html_images:
- $message =& $this->_addMixedPart();
- if (isset($this->_txtbody)) {
- $alt =& $this->_addAlternativePart($message);
- $this->_addTextPart($alt, $this->_txtbody);
- $rel =& $this->_addRelatedPart($alt);
- } else {
- $rel =& $this->_addRelatedPart($message);
- }
- $this->_addHtmlPart($rel);
- for ($i = 0; $i < count($this->_html_images); $i++) {
- $this->_addHtmlImagePart($rel, $this->_html_images[$i]);
- }
- for ($i = 0; $i < count($this->_parts); $i++) {
- $this->_addAttachmentPart($message, $this->_parts[$i]);
- }
- break;
-
- }
-
- if (isset($message)) {
- $output = $message->encode();
-
- $this->_headers = array_merge($this->_headers,
- $output['headers']);
- $body = $output['body'];
- return $body;
-
- } else {
- $ret = false;
- return $ret;
- }
- }
-
- /**
- * Returns an array with the headers needed to prepend to the email
- * (MIME-Version and Content-Type). Format of argument is:
- * $array['header-name'] = 'header-value';
- *
- * @param array $xtra_headers Assoc array with any extra headers.
- * Optional.
- * @param bool $overwrite Overwrite already existing headers.
- *
- * @return array Assoc array with the mime headers
- * @access public
- */
- function &headers($xtra_headers = null, $overwrite = false)
- {
- // Content-Type header should already be present,
- // So just add mime version header
- $headers['MIME-Version'] = '1.0';
- if (isset($xtra_headers)) {
- $headers = array_merge($headers, $xtra_headers);
- }
- if ($overwrite) {
- $this->_headers = array_merge($this->_headers, $headers);
- } else {
- $this->_headers = array_merge($headers, $this->_headers);
- }
-
- $encodedHeaders = $this->_encodeHeaders($this->_headers);
- return $encodedHeaders;
- }
-
- /**
- * Get the text version of the headers
- * (usefull if you want to use the PHP mail() function)
- *
- * @param array $xtra_headers Assoc array with any extra headers.
- * Optional.
- * @param bool $overwrite Overwrite the existing heaers with new.
- *
- * @return string Plain text headers
- * @access public
- */
- function txtHeaders($xtra_headers = null, $overwrite = false)
- {
- $headers = $this->headers($xtra_headers, $overwrite);
-
- $ret = '';
- foreach ($headers as $key => $val) {
- $ret .= "$key: $val" . MAIL_MIME_CRLF;
- }
- return $ret;
- }
-
- /**
- * Sets the Subject header
- *
- * @param string $subject String to set the subject to.
- *
- * @return void
- * @access public
- */
- function setSubject($subject)
- {
- $this->_headers['Subject'] = $subject;
- }
-
- /**
- * Set an email to the From (the sender) header
- *
- * @param string $email The email address to use
- *
- * @return void
- * @access public
- */
- function setFrom($email)
- {
- $this->_headers['From'] = $email;
- }
-
- /**
- * Add an email to the Cc (carbon copy) header
- * (multiple calls to this method are allowed)
- *
- * @param string $email The email direction to add
- *
- * @return void
- * @access public
- */
- function addCc($email)
- {
- if (isset($this->_headers['Cc'])) {
- $this->_headers['Cc'] .= ", $email";
- } else {
- $this->_headers['Cc'] = $email;
- }
- }
-
- /**
- * Add an email to the Bcc (blank carbon copy) header
- * (multiple calls to this method are allowed)
- *
- * @param string $email The email direction to add
- *
- * @return void
- * @access public
- */
- function addBcc($email)
- {
- if (isset($this->_headers['Bcc'])) {
- $this->_headers['Bcc'] .= ", $email";
- } else {
- $this->_headers['Bcc'] = $email;
- }
- }
-
- /**
- * Since the PHP send function requires you to specifiy
- * recipients (To: header) separately from the other
- * headers, the To: header is not properly encoded.
- * To fix this, you can use this public method to
- * encode your recipients before sending to the send
- * function
- *
- * @param string $recipients A comma-delimited list of recipients
- *
- * @return string Encoded data
- * @access public
- */
- function encodeRecipients($recipients)
- {
- $input = array("To" => $recipients);
- $retval = $this->_encodeHeaders($input);
- return $retval["To"] ;
- }
-
- /**
- * Encodes a header as per RFC2047
- *
- * @param array $input The header data to encode
- * @param array $params Extra build parameters
- *
- * @return array Encoded data
- * @access private
- */
- function _encodeHeaders($input, $params = array())
- {
-
- $build_params = $this->_build_params;
- while (list($key, $value) = each($params)) {
- $build_params[$key] = $value;
- }
- //$hdr_name: Name of the heaer
- //$hdr_value: Full line of header value.
- //$hdr_value_out: The recombined $hdr_val-atoms, or the encoded string.
-
- $useIconv = true;
- if (isset($build_params['ignore-iconv'])) {
- $useIconv = !$build_params['ignore-iconv'];
- }
- foreach ($input as $hdr_name => $hdr_value) {
- if (preg_match('#([\x80-\xFF]){1}#', $hdr_value)) {
- if (function_exists('iconv_mime_encode') && $useIconv) {
- $imePrefs = array();
- if ($build_params['head_encoding'] == 'base64') {
- $imePrefs['scheme'] = 'B';
- } else {
- $imePrefs['scheme'] = 'Q';
- }
- $imePrefs['input-charset'] = $build_params['head_charset'];
- $imePrefs['output-charset'] = $build_params['head_charset'];
- $imePrefs['line-length'] = 74;
- $imePrefs['line-break-chars'] = "\r\n"; //Specified in RFC2047
-
- $hdr_value = iconv_mime_encode($hdr_name, $hdr_value, $imePrefs);
- $hdr_value = preg_replace("#^{$hdr_name}\:\ #", "", $hdr_value);
- } elseif ($build_params['head_encoding'] == 'base64') {
- //Base64 encoding has been selected.
- //Base64 encode the entire string
- $hdr_value = base64_encode($hdr_value);
-
- //Generate the header using the specified params and dynamicly
- //determine the maximum length of such strings.
- //75 is the value specified in the RFC. The first -2 is there so
- //the later regexp doesn't break any of the translated chars.
- //The -2 on the first line-regexp is to compensate for the ": "
- //between the header-name and the header value
- $prefix = '=?' . $build_params['head_charset'] . '?B?';
- $suffix = '?=';
- $maxLength = 75 - strlen($prefix . $suffix) - 2;
- $maxLength1stLine = $maxLength - strlen($hdr_name) - 2;
-
- //We can cut base4 every 4 characters, so the real max
- //we can get must be rounded down.
- $maxLength = $maxLength - ($maxLength % 4);
- $maxLength1stLine = $maxLength1stLine - ($maxLength1stLine % 4);
-
- $cutpoint = $maxLength1stLine;
- $hdr_value_out = $hdr_value;
- $output = "";
- while ($hdr_value_out) {
- //Split translated string at every $maxLength
- $part = substr($hdr_value_out, 0, $cutpoint);
- $hdr_value_out = substr($hdr_value_out, $cutpoint);
- $cutpoint = $maxLength;
- //RFC 2047 specifies that any split header should
- //be seperated by a CRLF SPACE.
- if ($output) {
- $output .= "\r\n ";
- }
- $output .= $prefix . $part . $suffix;
- }
- $hdr_value = $output;
- } else {
- //quoted-printable encoding has been selected
-
- //Fix for Bug #10298, Ota Mares <om@viazenetti.de>
- //Check if there is a double quote at beginning or end of
- //the string to prevent that an open or closing quote gets
- //ignored because it is encapsuled by an encoding pre/suffix.
- //Remove the double quote and set the specific prefix or
- //suffix variable so that we can concat the encoded string and
- //the double quotes back together to get the intended string.
- $quotePrefix = $quoteSuffix = '';
- if ($hdr_value{0} == '"') {
- $hdr_value = substr($hdr_value, 1);
- $quotePrefix = '"';
- }
- if ($hdr_value{strlen($hdr_value)-1} == '"') {
- $hdr_value = substr($hdr_value, 0, -1);
- $quoteSuffix = '"';
- }
-
- //Generate the header using the specified params and dynamicly
- //determine the maximum length of such strings.
- //75 is the value specified in the RFC. The -2 is there so
- //the later regexp doesn't break any of the translated chars.
- //The -2 on the first line-regexp is to compensate for the ": "
- //between the header-name and the header value
- $prefix = '=?' . $build_params['head_charset'] . '?Q?';
- $suffix = '?=';
- $maxLength = 75 - strlen($prefix . $suffix) - 2 - 1;
- $maxLength1stLine = $maxLength - strlen($hdr_name) - 2;
- $maxLength = $maxLength - 1;
-
- //Replace all special characters used by the encoder.
- $search = array('=', '_', '?', ' ');
- $replace = array('=3D', '=5F', '=3F', '_');
- $hdr_value = str_replace($search, $replace, $hdr_value);
-
- //Replace all extended characters (\x80-xFF) with their
- //ASCII values.
- $hdr_value = preg_replace('#([\x80-\xFF])#e',
- '"=" . strtoupper(dechex(ord("\1")))',
- $hdr_value);
-
- //This regexp will break QP-encoded text at every $maxLength
- //but will not break any encoded letters.
- $reg1st = "|(.{0,$maxLength1stLine}[^\=][^\=])|";
- $reg2nd = "|(.{0,$maxLength}[^\=][^\=])|";
- //Fix for Bug #10298, Ota Mares <om@viazenetti.de>
- //Concat the double quotes and encoded string together
- $hdr_value = $quotePrefix . $hdr_value . $quoteSuffix;
-
-
- $hdr_value_out = $hdr_value;
- $realMax = $maxLength1stLine + strlen($prefix . $suffix);
- if (strlen($hdr_value_out) >= $realMax) {
- //Begin with the regexp for the first line.
- $reg = $reg1st;
- $output = "";
- while ($hdr_value_out) {
- //Split translated string at every $maxLength
- //But make sure not to break any translated chars.
- $found = preg_match($reg, $hdr_value_out, $matches);
-
- //After this first line, we need to use a different
- //regexp for the first line.
- $reg = $reg2nd;
-
- //Save the found part and encapsulate it in the
- //prefix & suffix. Then remove the part from the
- //$hdr_value_out variable.
- if ($found) {
- $part = $matches[0];
- $len = strlen($matches[0]);
- $hdr_value_out = substr($hdr_value_out, $len);
- } else {
- $part = $hdr_value_out;
- $hdr_value_out = "";
- }
-
- //RFC 2047 specifies that any split header should
- //be seperated by a CRLF SPACE
- if ($output) {
- $output .= "\r\n ";
- }
- $output .= $prefix . $part . $suffix;
- }
- $hdr_value_out = $output;
- } else {
- $hdr_value_out = $prefix . $hdr_value_out . $suffix;
- }
- $hdr_value = $hdr_value_out;
- }
- }
- $input[$hdr_name] = $hdr_value;
- }
- return $input;
- }
-
- /**
- * Set the object's end-of-line and define the constant if applicable.
- *
- * @param string $eol End Of Line sequence
- *
- * @return void
- * @access private
- */
- function _setEOL($eol)
- {
- $this->_eol = $eol;
- if (!defined('MAIL_MIME_CRLF')) {
- define('MAIL_MIME_CRLF', $this->_eol, true);
- }
- }
-
-
-
-} // End of class
+++ /dev/null
-<?php
-/**
- * The Mail_mimePart class is used to create MIME E-mail messages
- *
- * This class enables you to manipulate and build a mime email
- * from the ground up. The Mail_Mime class is a userfriendly api
- * to this class for people who aren't interested in the internals
- * of mime mail.
- * This class however allows full control over the email.
- *
- * Compatible with PHP versions 4 and 5
- *
- * LICENSE: This LICENSE is in the BSD license style.
- * Copyright (c) 2002-2003, Richard Heyes <richard@phpguru.org>
- * Copyright (c) 2003-2006, PEAR <pear-group@php.net>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or
- * without modification, are permitted provided that the following
- * conditions are met:
- *
- * - Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * - Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * - Neither the name of the authors, nor the names of its contributors
- * may be used to endorse or promote products derived from this
- * software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- *
- * @category Mail
- * @package Mail_Mime
- * @author Richard Heyes <richard@phpguru.org>
- * @author Cipriano Groenendal <cipri@php.net>
- * @author Sean Coates <sean@php.net>
- * @copyright 2003-2006 PEAR <pear-group@php.net>
- * @license http://www.opensource.org/licenses/bsd-license.php BSD License
- * @version CVS: $Id: mimePart.php,v 1.1.1.1 2008/04/28 15:20:50 jamie Exp $
- * @link http://pear.php.net/package/Mail_mime
- */
-
-
-/**
- * The Mail_mimePart class is used to create MIME E-mail messages
- *
- * This class enables you to manipulate and build a mime email
- * from the ground up. The Mail_Mime class is a userfriendly api
- * to this class for people who aren't interested in the internals
- * of mime mail.
- * This class however allows full control over the email.
- *
- * @category Mail
- * @package Mail_Mime
- * @author Richard Heyes <richard@phpguru.org>
- * @author Cipriano Groenendal <cipri@php.net>
- * @author Sean Coates <sean@php.net>
- * @copyright 2003-2006 PEAR <pear-group@php.net>
- * @license http://www.opensource.org/licenses/bsd-license.php BSD License
- * @version Release: @package_version@
- * @link http://pear.php.net/package/Mail_mime
- */
-class Mail_mimePart {
-
- /**
- * The encoding type of this part
- *
- * @var string
- * @access private
- */
- var $_encoding;
-
- /**
- * An array of subparts
- *
- * @var array
- * @access private
- */
- var $_subparts;
-
- /**
- * The output of this part after being built
- *
- * @var string
- * @access private
- */
- var $_encoded;
-
- /**
- * Headers for this part
- *
- * @var array
- * @access private
- */
- var $_headers;
-
- /**
- * The body of this part (not encoded)
- *
- * @var string
- * @access private
- */
- var $_body;
-
- /**
- * Constructor.
- *
- * Sets up the object.
- *
- * @param $body - The body of the mime part if any.
- * @param $params - An associative array of parameters:
- * content_type - The content type for this part eg multipart/mixed
- * encoding - The encoding to use, 7bit, 8bit, base64, or quoted-printable
- * cid - Content ID to apply
- * disposition - Content disposition, inline or attachment
- * dfilename - Optional filename parameter for content disposition
- * description - Content description
- * charset - Character set to use
- * @access public
- */
- function Mail_mimePart($body = '', $params = array())
- {
- if (!defined('MAIL_MIMEPART_CRLF')) {
- define('MAIL_MIMEPART_CRLF', defined('MAIL_MIME_CRLF') ? MAIL_MIME_CRLF : "\r\n", TRUE);
- }
-
- $contentType = array();
- $contentDisp = array();
- foreach ($params as $key => $value) {
- switch ($key) {
- case 'content_type':
- $contentType['type'] = $value;
- //$headers['Content-Type'] = $value . (isset($charset) ? '; charset="' . $charset . '"' : '');
- break;
-
- case 'encoding':
- $this->_encoding = $value;
- $headers['Content-Transfer-Encoding'] = $value;
- break;
-
- case 'cid':
- $headers['Content-ID'] = '<' . $value . '>';
- break;
-
- case 'disposition':
- $contentDisp['disp'] = $value;
- break;
-
- case 'dfilename':
- $contentDisp['filename'] = $value;
- $contentType['name'] = $value;
- break;
-
- case 'description':
- $headers['Content-Description'] = $value;
- break;
-
- case 'charset':
- $contentType['charset'] = $value;
- $contentDisp['charset'] = $value;
- break;
-
- case 'language':
- $contentType['language'] = $value;
- $contentDisp['language'] = $value;
- break;
-
- case 'location':
- $headers['Content-Location'] = $value;
- break;
-
- }
- }
- if (isset($contentType['type'])) {
- $headers['Content-Type'] = $contentType['type'];
- if (isset($contentType['name'])) {
- $headers['Content-Type'] .= ';' . MAIL_MIMEPART_CRLF;
- $headers['Content-Type'] .= $this->_buildHeaderParam('name', $contentType['name'],
- isset($contentType['charset']) ? $contentType['charset'] : 'US-ASCII',
- isset($contentType['language']) ? $contentType['language'] : NULL);
- } elseif (isset($contentType['charset'])) {
- $headers['Content-Type'] .= "; charset=\"{$contentType['charset']}\"";
- }
- }
-
-
- if (isset($contentDisp['disp'])) {
- $headers['Content-Disposition'] = $contentDisp['disp'];
- if (isset($contentDisp['filename'])) {
- $headers['Content-Disposition'] .= ';' . MAIL_MIMEPART_CRLF;
- $headers['Content-Disposition'] .= $this->_buildHeaderParam('filename', $contentDisp['filename'],
- isset($contentDisp['charset']) ? $contentDisp['charset'] : 'US-ASCII',
- isset($contentDisp['language']) ? $contentDisp['language'] : NULL);
- }
- }
-
-
-
-
- // Default content-type
- if (!isset($headers['Content-Type'])) {
- $headers['Content-Type'] = 'text/plain';
- }
-
- //Default encoding
- if (!isset($this->_encoding)) {
- $this->_encoding = '7bit';
- }
-
- // Assign stuff to member variables
- $this->_encoded = array();
- $this->_headers = $headers;
- $this->_body = $body;
- }
-
- /**
- * encode()
- *
- * Encodes and returns the email. Also stores
- * it in the encoded member variable
- *
- * @return An associative array containing two elements,
- * body and headers. The headers element is itself
- * an indexed array.
- * @access public
- */
- function encode()
- {
- $encoded =& $this->_encoded;
-
- if (count($this->_subparts)) {
- srand((double)microtime()*1000000);
- $boundary = '=_' . md5(rand() . microtime());
- $this->_headers['Content-Type'] .= ';' . MAIL_MIMEPART_CRLF . "\t" . 'boundary="' . $boundary . '"';
-
- // Add body parts to $subparts
- for ($i = 0; $i < count($this->_subparts); $i++) {
- $headers = array();
- $tmp = $this->_subparts[$i]->encode();
- foreach ($tmp['headers'] as $key => $value) {
- $headers[] = $key . ': ' . $value;
- }
- $subparts[] = implode(MAIL_MIMEPART_CRLF, $headers) . MAIL_MIMEPART_CRLF . MAIL_MIMEPART_CRLF . $tmp['body'] . MAIL_MIMEPART_CRLF;
- }
-
- $encoded['body'] = '--' . $boundary . MAIL_MIMEPART_CRLF .
- rtrim(implode('--' . $boundary . MAIL_MIMEPART_CRLF , $subparts), MAIL_MIMEPART_CRLF) . MAIL_MIMEPART_CRLF .
- '--' . $boundary.'--' . MAIL_MIMEPART_CRLF;
-
- } else {
- $encoded['body'] = $this->_getEncodedData($this->_body, $this->_encoding);
- }
-
- // Add headers to $encoded
- $encoded['headers'] =& $this->_headers;
-
- return $encoded;
- }
-
- /**
- * &addSubPart()
- *
- * Adds a subpart to current mime part and returns
- * a reference to it
- *
- * @param $body The body of the subpart, if any.
- * @param $params The parameters for the subpart, same
- * as the $params argument for constructor.
- * @return A reference to the part you just added. It is
- * crucial if using multipart/* in your subparts that
- * you use =& in your script when calling this function,
- * otherwise you will not be able to add further subparts.
- * @access public
- */
- function &addSubPart($body, $params)
- {
- $this->_subparts[] = new Mail_mimePart($body, $params);
- return $this->_subparts[count($this->_subparts) - 1];
- }
-
- /**
- * _getEncodedData()
- *
- * Returns encoded data based upon encoding passed to it
- *
- * @param $data The data to encode.
- * @param $encoding The encoding type to use, 7bit, base64,
- * or quoted-printable.
- * @access private
- */
- function _getEncodedData($data, $encoding)
- {
- switch ($encoding) {
- case '8bit':
- case '7bit':
- return $data;
- break;
-
- case 'quoted-printable':
- return $this->_quotedPrintableEncode($data);
- break;
-
- case 'base64':
- return rtrim(chunk_split(base64_encode($data), 76, MAIL_MIMEPART_CRLF));
- break;
-
- default:
- return $data;
- }
- }
-
- /**
- * quotedPrintableEncode()
- *
- * Encodes data to quoted-printable standard.
- *
- * @param $input The data to encode
- * @param $line_max Optional max line length. Should
- * not be more than 76 chars
- *
- * @access private
- */
- function _quotedPrintableEncode($input , $line_max = 76)
- {
- $lines = preg_split("/\r?\n/", $input);
- $eol = MAIL_MIMEPART_CRLF;
- $escape = '=';
- $output = '';
-
- while (list(, $line) = each($lines)) {
-
- $line = preg_split('||', $line, -1, PREG_SPLIT_NO_EMPTY);
- $linlen = count($line);
- $newline = '';
-
- for ($i = 0; $i < $linlen; $i++) {
- $char = $line[$i];
- $dec = ord($char);
-
- if (($dec == 32) AND ($i == ($linlen - 1))) { // convert space at eol only
- $char = '=20';
-
- } elseif (($dec == 9) AND ($i == ($linlen - 1))) { // convert tab at eol only
- $char = '=09';
- } elseif ($dec == 9) {
- ; // Do nothing if a tab.
- } elseif (($dec == 61) OR ($dec < 32 ) OR ($dec > 126)) {
- $char = $escape . strtoupper(sprintf('%02s', dechex($dec)));
- } elseif (($dec == 46) AND ($newline == '')) {
- //Bug #9722: convert full-stop at bol
- //Some Windows servers need this, won't break anything (cipri)
- $char = '=2E';
- }
-
- if ((strlen($newline) + strlen($char)) >= $line_max) { // MAIL_MIMEPART_CRLF is not counted
- $output .= $newline . $escape . $eol; // soft line break; " =\r\n" is okay
- $newline = '';
- }
- $newline .= $char;
- } // end of for
- $output .= $newline . $eol;
- }
- $output = substr($output, 0, -1 * strlen($eol)); // Don't want last crlf
- return $output;
- }
-
- /**
- * _buildHeaderParam()
- *
- * Encodes the paramater of a header.
- *
- * @param $name The name of the header-parameter
- * @param $value The value of the paramter
- * @param $charset The characterset of $value
- * @param $language The language used in $value
- * @param $maxLength The maximum length of a line. Defauls to 75
- *
- * @access private
- */
- function _buildHeaderParam($name, $value, $charset=NULL, $language=NULL, $maxLength=75)
- {
- //If we find chars to encode, or if charset or language
- //is not any of the defaults, we need to encode the value.
- $shouldEncode = 0;
- $secondAsterisk = '';
- if (preg_match('#([\x80-\xFF]){1}#', $value)) {
- $shouldEncode = 1;
- } elseif ($charset && (strtolower($charset) != 'us-ascii')) {
- $shouldEncode = 1;
- } elseif ($language && ($language != 'en' && $language != 'en-us')) {
- $shouldEncode = 1;
- }
- if ($shouldEncode) {
- $search = array('%', ' ', "\t");
- $replace = array('%25', '%20', '%09');
- $encValue = str_replace($search, $replace, $value);
- $encValue = preg_replace('#([\x80-\xFF])#e', '"%" . strtoupper(dechex(ord("\1")))', $encValue);
- $value = "$charset'$language'$encValue";
- $secondAsterisk = '*';
- }
- $header = " {$name}{$secondAsterisk}=\"{$value}\"; ";
- if (strlen($header) <= $maxLength) {
- return $header;
- }
-
- $preLength = strlen(" {$name}*0{$secondAsterisk}=\"");
- $sufLength = strlen("\";");
- $maxLength = MAX(16, $maxLength - $preLength - $sufLength - 2);
- $maxLengthReg = "|(.{0,$maxLength}[^\%][^\%])|";
-
- $headers = array();
- $headCount = 0;
- while ($value) {
- $matches = array();
- $found = preg_match($maxLengthReg, $value, $matches);
- if ($found) {
- $headers[] = " {$name}*{$headCount}{$secondAsterisk}=\"{$matches[0]}\"";
- $value = substr($value, strlen($matches[0]));
- } else {
- $headers[] = " {$name}*{$headCount}{$secondAsterisk}=\"{$value}\"";
- $value = "";
- }
- $headCount++;
- }
- $headers = implode(MAIL_MIMEPART_CRLF, $headers) . ';';
- return $headers;
- }
-} // End of class
+++ /dev/null
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Phil Kernick <philk@rotfl.com.au> |
-// +----------------------------------------------------------------------+
-//
-// $Id: null.php,v 1.1.1.1 2008/04/28 15:20:50 jamie Exp $
-//
-
-/**
- * Null implementation of the PEAR Mail:: interface.
- * @access public
- * @package Mail
- * @version $Revision: 1.1.1.1 $
- */
-class Mail_null extends Mail {
-
- /**
- * Implements Mail_null::send() function. Silently discards all
- * mail.
- *
- * @param mixed $recipients Either a comma-seperated list of recipients
- * (RFC822 compliant), or an array of recipients,
- * each RFC822 valid. This may contain recipients not
- * specified in the headers, for Bcc:, resending
- * messages, etc.
- *
- * @param array $headers The array of headers to send with the mail, in an
- * associative array, where the array key is the
- * header name (ie, 'Subject'), and the array value
- * is the header value (ie, 'test'). The header
- * produced from those values would be 'Subject:
- * test'.
- *
- * @param string $body The full text of the message body, including any
- * Mime parts, etc.
- *
- * @return mixed Returns true on success, or a PEAR_Error
- * containing a descriptive error message on
- * failure.
- * @access public
- */
- function send($recipients, $headers, $body)
- {
- return true;
- }
-
-}
+++ /dev/null
-#!@prefix@/bin/php -Cq
-<?php
-/**
-* PHAIL - stands for PHP Mail
-* @author Tomas V.V.Cox <cox@idecnet.com>
-*/
-require_once 'Mail.php';
-require_once 'Mail/mime.php';
-require_once 'Console/Getopt.php';
-
-$argv = Console_Getopt::readPHPArgv();
-$opts = Console_Getopt::getOpt($argv, 'f:c:s:t:a:b:');
-if (PEAR::isError($opts)) {
- usage($opts->getMessage());
-}
-
-PEAR::setErrorHandling(PEAR_ERROR_DIE);
-$mime = &new Mail_Mime;
-foreach ($opts[0] as $opt) {
- $param = $opt[1];
- switch ($opt[0]) {
- case 'f':
- $headers['From'] = $param; break;
- case 'c':
- $headers['Cc'] = $param; break;
- case 's':
- $headers['Subject'] = $param; break;
- case 't':
- $to = $param; break;
- case 'a':
- $mime->addAttachment($param); break;
- case 'b':
- $isfile = @is_file($param) ? true : false;
- $mime->setTXTBody($param, $isfile); break;
- }
-}
-
-$mbody = $mime->get();
-$headers = $mime->headers($headers);
-$mail =& Mail::factory('mail');
-$mail->send($to, $headers, $mbody);
-
-function usage($error)
-{
- die($error);
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Chuck Hagenbuch <chuck@horde.org> |
-// +----------------------------------------------------------------------+
-
-/**
- * Sendmail implementation of the PEAR Mail:: interface.
- * @access public
- * @package Mail
- * @version $Revision: 1.1.1.1 $
- */
-class Mail_sendmail extends Mail {
-
- /**
- * The location of the sendmail or sendmail wrapper binary on the
- * filesystem.
- * @var string
- */
- var $sendmail_path = '/usr/sbin/sendmail';
-
- /**
- * Any extra command-line parameters to pass to the sendmail or
- * sendmail wrapper binary.
- * @var string
- */
- var $sendmail_args = '-i';
-
- /**
- * Constructor.
- *
- * Instantiates a new Mail_sendmail:: object based on the parameters
- * passed in. It looks for the following parameters:
- * sendmail_path The location of the sendmail binary on the
- * filesystem. Defaults to '/usr/sbin/sendmail'.
- *
- * sendmail_args Any extra parameters to pass to the sendmail
- * or sendmail wrapper binary.
- *
- * If a parameter is present in the $params array, it replaces the
- * default.
- *
- * @param array $params Hash containing any parameters different from the
- * defaults.
- * @access public
- */
- function Mail_sendmail($params)
- {
- if (isset($params['sendmail_path'])) {
- $this->sendmail_path = $params['sendmail_path'];
- }
- if (isset($params['sendmail_args'])) {
- $this->sendmail_args = $params['sendmail_args'];
- }
-
- /*
- * Because we need to pass message headers to the sendmail program on
- * the commandline, we can't guarantee the use of the standard "\r\n"
- * separator. Instead, we use the system's native line separator.
- */
- if (defined('PHP_EOL')) {
- $this->sep = PHP_EOL;
- } else {
- $this->sep = (strpos(PHP_OS, 'WIN') === false) ? "\n" : "\r\n";
- }
- }
-
- /**
- * Implements Mail::send() function using the sendmail
- * command-line binary.
- *
- * @param mixed $recipients Either a comma-seperated list of recipients
- * (RFC822 compliant), or an array of recipients,
- * each RFC822 valid. This may contain recipients not
- * specified in the headers, for Bcc:, resending
- * messages, etc.
- *
- * @param array $headers The array of headers to send with the mail, in an
- * associative array, where the array key is the
- * header name (ie, 'Subject'), and the array value
- * is the header value (ie, 'test'). The header
- * produced from those values would be 'Subject:
- * test'.
- *
- * @param string $body The full text of the message body, including any
- * Mime parts, etc.
- *
- * @return mixed Returns true on success, or a PEAR_Error
- * containing a descriptive error message on
- * failure.
- * @access public
- */
- function send($recipients, $headers, $body)
- {
- $recipients = $this->parseRecipients($recipients);
- if (PEAR::isError($recipients)) {
- return $recipients;
- }
- $recipients = escapeShellCmd(implode(' ', $recipients));
-
- $this->_sanitizeHeaders($headers);
- $headerElements = $this->prepareHeaders($headers);
- if (PEAR::isError($headerElements)) {
- return $headerElements;
- }
- list($from, $text_headers) = $headerElements;
-
- if (!isset($from)) {
- return PEAR::raiseError('No from address given.');
- } elseif (strpos($from, ' ') !== false ||
- strpos($from, ';') !== false ||
- strpos($from, '&') !== false ||
- strpos($from, '`') !== false) {
- return PEAR::raiseError('From address specified with dangerous characters.');
- }
-
- $from = escapeShellCmd($from);
- $mail = @popen($this->sendmail_path . (!empty($this->sendmail_args) ? ' ' . $this->sendmail_args : '') . " -f$from -- $recipients", 'w');
- if (!$mail) {
- return PEAR::raiseError('Failed to open sendmail [' . $this->sendmail_path . '] for execution.');
- }
-
- // Write the headers following by two newlines: one to end the headers
- // section and a second to separate the headers block from the body.
- fputs($mail, $text_headers . $this->sep . $this->sep);
-
- fputs($mail, $body);
- $result = pclose($mail);
- if (version_compare(phpversion(), '4.2.3') == -1) {
- // With older php versions, we need to shift the pclose
- // result to get the exit code.
- $result = $result >> 8 & 0xFF;
- }
-
- if ($result != 0) {
- return PEAR::raiseError('sendmail returned error code ' . $result,
- $result);
- }
-
- return true;
- }
-
-}
+++ /dev/null
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Chuck Hagenbuch <chuck@horde.org> |
-// | Jon Parise <jon@php.net> |
-// +----------------------------------------------------------------------+
-
-/** Error: Failed to create a Net_SMTP object */
-define('PEAR_MAIL_SMTP_ERROR_CREATE', 10000);
-
-/** Error: Failed to connect to SMTP server */
-define('PEAR_MAIL_SMTP_ERROR_CONNECT', 10001);
-
-/** Error: SMTP authentication failure */
-define('PEAR_MAIL_SMTP_ERROR_AUTH', 10002);
-
-/** Error: No From: address has been provided */
-define('PEAR_MAIL_SMTP_ERROR_FROM', 10003);
-
-/** Error: Failed to set sender */
-define('PEAR_MAIL_SMTP_ERROR_SENDER', 10004);
-
-/** Error: Failed to add recipient */
-define('PEAR_MAIL_SMTP_ERROR_RECIPIENT', 10005);
-
-/** Error: Failed to send data */
-define('PEAR_MAIL_SMTP_ERROR_DATA', 10006);
-
-/**
- * SMTP implementation of the PEAR Mail interface. Requires the Net_SMTP class.
- * @access public
- * @package Mail
- * @version $Revision: 1.1.1.1 $
- */
-class Mail_smtp extends Mail {
-
- /**
- * SMTP connection object.
- *
- * @var object
- * @access private
- */
- var $_smtp = null;
-
- /**
- * The SMTP host to connect to.
- * @var string
- */
- var $host = 'localhost';
-
- /**
- * The port the SMTP server is on.
- * @var integer
- */
- var $port = 25;
-
- /**
- * Should SMTP authentication be used?
- *
- * This value may be set to true, false or the name of a specific
- * authentication method.
- *
- * If the value is set to true, the Net_SMTP package will attempt to use
- * the best authentication method advertised by the remote SMTP server.
- *
- * @var mixed
- */
- var $auth = false;
-
- /**
- * The username to use if the SMTP server requires authentication.
- * @var string
- */
- var $username = '';
-
- /**
- * The password to use if the SMTP server requires authentication.
- * @var string
- */
- var $password = '';
-
- /**
- * Hostname or domain that will be sent to the remote SMTP server in the
- * HELO / EHLO message.
- *
- * @var string
- */
- var $localhost = 'localhost';
-
- /**
- * SMTP connection timeout value. NULL indicates no timeout.
- *
- * @var integer
- */
- var $timeout = null;
-
- /**
- * Whether to use VERP or not. If not a boolean, the string value
- * will be used as the VERP separators.
- *
- * @var mixed boolean or string
- */
- var $verp = false;
-
- /**
- * Turn on Net_SMTP debugging?
- *
- * @var boolean $debug
- */
- var $debug = false;
-
- /**
- * Indicates whether or not the SMTP connection should persist over
- * multiple calls to the send() method.
- *
- * @var boolean
- */
- var $persist = false;
-
- /**
- * Constructor.
- *
- * Instantiates a new Mail_smtp:: object based on the parameters
- * passed in. It looks for the following parameters:
- * host The server to connect to. Defaults to localhost.
- * port The port to connect to. Defaults to 25.
- * auth SMTP authentication. Defaults to none.
- * username The username to use for SMTP auth. No default.
- * password The password to use for SMTP auth. No default.
- * localhost The local hostname / domain. Defaults to localhost.
- * timeout The SMTP connection timeout. Defaults to none.
- * verp Whether to use VERP or not. Defaults to false.
- * debug Activate SMTP debug mode? Defaults to false.
- * persist Should the SMTP connection persist?
- *
- * If a parameter is present in the $params array, it replaces the
- * default.
- *
- * @param array Hash containing any parameters different from the
- * defaults.
- * @access public
- */
- function Mail_smtp($params)
- {
- if (isset($params['host'])) $this->host = $params['host'];
- if (isset($params['port'])) $this->port = $params['port'];
- if (isset($params['auth'])) $this->auth = $params['auth'];
- if (isset($params['username'])) $this->username = $params['username'];
- if (isset($params['password'])) $this->password = $params['password'];
- if (isset($params['localhost'])) $this->localhost = $params['localhost'];
- if (isset($params['timeout'])) $this->timeout = $params['timeout'];
- if (isset($params['verp'])) $this->verp = $params['verp'];
- if (isset($params['debug'])) $this->debug = (boolean)$params['debug'];
- if (isset($params['persist'])) $this->persist = (boolean)$params['persist'];
-
- register_shutdown_function(array(&$this, '_Mail_smtp'));
- }
-
- /**
- * Destructor implementation to ensure that we disconnect from any
- * potentially-alive persistent SMTP connections.
- */
- function _Mail_smtp()
- {
- $this->disconnect();
- }
-
- /**
- * Implements Mail::send() function using SMTP.
- *
- * @param mixed $recipients Either a comma-seperated list of recipients
- * (RFC822 compliant), or an array of recipients,
- * each RFC822 valid. This may contain recipients not
- * specified in the headers, for Bcc:, resending
- * messages, etc.
- *
- * @param array $headers The array of headers to send with the mail, in an
- * associative array, where the array key is the
- * header name (e.g., 'Subject'), and the array value
- * is the header value (e.g., 'test'). The header
- * produced from those values would be 'Subject:
- * test'.
- *
- * @param string $body The full text of the message body, including any
- * Mime parts, etc.
- *
- * @return mixed Returns true on success, or a PEAR_Error
- * containing a descriptive error message on
- * failure.
- * @access public
- */
- function send($recipients, $headers, $body)
- {
- include_once 'Net/SMTP.php';
-
- /* If we don't already have an SMTP object, create one. */
- if (is_object($this->_smtp) === false) {
- $this->_smtp =& new Net_SMTP($this->host, $this->port,
- $this->localhost);
-
- /* If we still don't have an SMTP object at this point, fail. */
- if (is_object($this->_smtp) === false) {
- return PEAR::raiseError('Failed to create a Net_SMTP object',
- PEAR_MAIL_SMTP_ERROR_CREATE);
- }
-
- /* Configure the SMTP connection. */
- if ($this->debug) {
- $this->_smtp->setDebug(true);
- }
-
- /* Attempt to connect to the configured SMTP server. */
- if (PEAR::isError($res = $this->_smtp->connect($this->timeout))) {
- $error = $this->_error('Failed to connect to ' .
- $this->host . ':' . $this->port,
- $res);
- return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_CONNECT);
- }
-
- /* Attempt to authenticate if authentication has been enabled. */
- if ($this->auth) {
- $method = is_string($this->auth) ? $this->auth : '';
-
- if (PEAR::isError($res = $this->_smtp->auth($this->username,
- $this->password,
- $method))) {
- $error = $this->_error("$method authentication failure",
- $res);
- $this->_smtp->rset();
- return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_AUTH);
- }
- }
- }
-
- $this->_sanitizeHeaders($headers);
- $headerElements = $this->prepareHeaders($headers);
- if (PEAR::isError($headerElements)) {
- $this->_smtp->rset();
- return $headerElements;
- }
- list($from, $textHeaders) = $headerElements;
-
- /* Since few MTAs are going to allow this header to be forged
- * unless it's in the MAIL FROM: exchange, we'll use
- * Return-Path instead of From: if it's set. */
- if (!empty($headers['Return-Path'])) {
- $from = $headers['Return-Path'];
- }
-
- if (!isset($from)) {
- $this->_smtp->rset();
- return PEAR::raiseError('No From: address has been provided',
- PEAR_MAIL_SMTP_ERROR_FROM);
- }
-
- $args['verp'] = $this->verp;
- if (PEAR::isError($res = $this->_smtp->mailFrom($from, $args))) {
- $error = $this->_error("Failed to set sender: $from", $res);
- $this->_smtp->rset();
- return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_SENDER);
- }
-
- $recipients = $this->parseRecipients($recipients);
- if (PEAR::isError($recipients)) {
- $this->_smtp->rset();
- return $recipients;
- }
-
- foreach ($recipients as $recipient) {
- if (PEAR::isError($res = $this->_smtp->rcptTo($recipient))) {
- $error = $this->_error("Failed to add recipient: $recipient",
- $res);
- $this->_smtp->rset();
- return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_RECIPIENT);
- }
- }
-
- /* Send the message's headers and the body as SMTP data. */
- if (PEAR::isError($res = $this->_smtp->data($textHeaders . "\r\n\r\n" . $body))) {
- $error = $this->_error('Failed to send data', $res);
- $this->_smtp->rset();
- return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_DATA);
- }
-
- /* If persistent connections are disabled, destroy our SMTP object. */
- if ($this->persist === false) {
- $this->disconnect();
- }
-
- return true;
- }
-
- /**
- * Disconnect and destroy the current SMTP connection.
- *
- * @return boolean True if the SMTP connection no longer exists.
- *
- * @since 1.1.9
- * @access public
- */
- function disconnect()
- {
- /* If we have an SMTP object, disconnect and destroy it. */
- if (is_object($this->_smtp) && $this->_smtp->disconnect()) {
- $this->_smtp = null;
- }
-
- /* We are disconnected if we no longer have an SMTP object. */
- return ($this->_smtp === null);
- }
-
- /**
- * Build a standardized string describing the current SMTP error.
- *
- * @param string $text Custom string describing the error context.
- * @param object $error Reference to the current PEAR_Error object.
- *
- * @return string A string describing the current SMTP error.
- *
- * @since 1.1.7
- * @access private
- */
- function _error($text, &$error)
- {
- /* Split the SMTP response into a code and a response string. */
- list($code, $response) = $this->_smtp->getResponse();
-
- /* Build our standardized error string. */
- $msg = $text;
- $msg .= ' [SMTP: ' . $error->getMessage();
- $msg .= " (code: $code, response: $response)]";
-
- return $msg;
- }
-
-}
+++ /dev/null
-<?xml version="1.0" encoding="ISO-8859-1"?>
-
-<!ENTITY lt "&#60;">
-<!ENTITY gt ">">
-<!ENTITY amp "&#38;">
-<!ENTITY apos "'">
-<!ENTITY quot """>
-<!ENTITY crlf " ">
-
-<!ELEMENT email (header+, (body | mimepart+))>
-<!ELEMENT mimepart (header+, (body | mimepart+))>
-<!ELEMENT body (#PCDATA)>
-<!ELEMENT header ((headername|headervalue|parameter)*)>
-<!ELEMENT headername (#PCDATA)>
-<!ELEMENT headervalue (#PCDATA)>
-<!ELEMENT parameter ((paramname|paramvalue)+)>
-<!ELEMENT paramvalue (#PCDATA)>
-<!ELEMENT paramname (#PCDATA)>
-
+++ /dev/null
-<?xml version="1.0" encoding="ISO-8859-1"?>
-<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format">
-<xsl:output method="text" omit-xml-declaration="yes" indent="no"/>
-<xsl:preserve-space elements="headervalue paramvalue body"/>
-
- <xsl:template name="mimepart">
-
- <xsl:variable name="boundary">
- <xsl:for-each select="./header">
- <xsl:if test="string(./headername) = 'Content-Type'">
- <xsl:for-each select="./parameter">
- <xsl:if test="string(./paramname) = 'boundary'">
- <xsl:value-of select="paramvalue"/>
- </xsl:if>
- </xsl:for-each>
- </xsl:if>
- </xsl:for-each>
- </xsl:variable>
-
- <xsl:for-each select="header">
-
- <xsl:value-of select="headername"/>
- <xsl:text>: </xsl:text>
- <xsl:value-of select="headervalue"/>
-
- <xsl:if test="count(./parameter) = 0">
- <xsl:text> </xsl:text>
- </xsl:if>
-
- <xsl:for-each select="parameter">
- <xsl:text>; 	</xsl:text>
- <xsl:value-of select="paramname"/>
- <xsl:text>="</xsl:text>
- <xsl:value-of select="paramvalue"/>
- <xsl:text>"</xsl:text>
- </xsl:for-each>
-
- <xsl:if test="count(./parameter) > 0">
- <xsl:text> </xsl:text>
- </xsl:if>
-
- </xsl:for-each>
-
- <xsl:text> </xsl:text>
-
- <!-- Which to do, print a body or process subparts? -->
- <xsl:choose>
- <xsl:when test="count(./mimepart) = 0">
- <xsl:value-of select="body"/>
- <xsl:text> </xsl:text>
- </xsl:when>
-
- <xsl:otherwise>
- <xsl:for-each select="mimepart">
- <xsl:text>--</xsl:text><xsl:value-of select="$boundary"/><xsl:text> </xsl:text>
- <xsl:call-template name="mimepart"/>
- </xsl:for-each>
-
- <xsl:text>--</xsl:text><xsl:value-of select="$boundary"/><xsl:text>-- </xsl:text>
-
- </xsl:otherwise>
- </xsl:choose>
- </xsl:template>
-
-<!-- This is where the stylesheet really starts, matching the top level email element -->
- <xsl:template match="email">
- <xsl:call-template name="mimepart"/>
- </xsl:template>
-
-</xsl:stylesheet>
\ No newline at end of file
+++ /dev/null
-<?php
-
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-
-/**
- * Net_Curl
- *
- * LICENSE: This source file is subject to version 3.0 of the PHP license
- * that is available through the world-wide-web at the following URI:
- * http://www.php.net/license/3_0.txt. If you did not receive a copy of
- * the PHP License and are unable to obtain it through the web, please
- * send a note to license@php.net so we can mail you a copy immediately.
- *
- * @category Net
- * @package Net_Curl
- * @author David Costa <gurugeek@php.net>
- * @author Sterling Hughes <sterling@php.net>
- * @author Joe Stump <joe@joestump.net>
- * @copyright 1997-2005 The PHP Group
- * @license http://www.php.net/license/3_0.txt PHP License 3.0
- * @version CVS: $Revision: 1.1.1.1 $
- * @link http://pear.php.net/package/Net_Curl
- */
-
-require_once('PEAR.php');
-
-class Net_Curl
-{
- // {{{ Public Properties
- /**
- * The URL for cURL to work with
- *
- * @var string $url
- * @access public
- */
- var $url;
-
- /**
- * The Username for standard HTTP Authentication
- *
- * @var string $username
- * @access public
- */
- var $username = '';
-
- /**
- * The Password for standard HTTP Authentication
- *
- * @var string $password
- * @access public
- */
- var $password = '';
-
- /**
- * The SSL version for the transfer
- *
- * @var integer $sslVersion
- * @access public
- */
- var $sslVersion;
-
- /**
- * The filename of the SSL certificate
- *
- * @var string $sslCert
- * @access public
- */
- var $sslCert;
-
- /**
- * The password corresponding to the certificate
- * in the $sslCert property
- *
- * @var string $sslCertPasswd
- * @access public
- */
- var $sslCertPasswd;
-
- /**
- * User Agent string when making an HTTP request
- *
- * @var string $userAgent
- * @access public
- */
- var $userAgent;
-
- /**
- * Whether or not to include the header in the results
- * of the CURL transfer
- *
- * @var boolean $header
- */
- var $header = false;
-
- /**
- * Whether or not to output debug information while executing a
- * curl transfer
- *
- * @var boolean $verbose
- * @access public
- */
- var $verbose = false;
-
- /**
- * Whether or not to display a progress meter for the current transfer
- *
- * @var boolean $progress
- * @access public
- */
- var $progress = false;
-
- /**
- * Whether or not to suppress error messages
- *
- * @var boolean $mute
- * @access public
- */
- var $mute = false;
-
- /**
- * Whether or not to follow HTTP Location headers.
- *
- * @var boolean $followLocation
- * @access public
- */
- var $followLocation = true;
-
- /**
- * Whether or not to follow HTTP Location headers.
- *
- * @var boolean $follow_location
- * @access public
- * @deprecated
- */
- var $follow_location = false;
-
- /**
- * Time allowed for current transfer, in seconds. 0 means no limit
- *
- * @var int $timeout
- * @access public
- */
- var $timeout = 0;
-
- /**
- * Whether or not to return the results of the
- * current transfer
- *
- * @var boolean $returnTransfer
- * @access public
- */
- var $returnTransfer = true;
-
- /**
- * Whether or not to return the results of the
- * current transfer
- *
- * @var boolean $return_transfer
- * @access public
- * @deprecated
- */
- var $return_transfer = false;
-
- /**
- * The type of transfer to perform (ie. 'POST', 'GET', 'PUT', etc)
- *
- * @var string $type
- * @access public
- */
- var $type;
-
- /**
- * The file to upload
- *
- * @var string $file
- * @access public
- */
- var $file;
-
- /**
- * The file size of the file pointed to by the $file
- * property
- *
- * @var integer $fileSize
- * @access public
- */
- var $fileSize;
-
- /**
- * The file size of the file pointed to by the $file
- * property
- *
- * @var integer $file_size
- * @access public
- * @deprecated
- */
- var $file_size = false;
-
-
- /**
- * The cookies to send to the remote site
- *
- * @var array $cookies
- * @access public
- */
- var $cookies = array();
-
- /**
- * Additional HTTP headers to send to the remote site
- *
- * @var array $httpHeaders
- * @access public
- */
- var $httpHeaders = null;
-
- /**
- * Additional HTTP headers to send to the remote site
- *
- * @var array $http_headers
- * @access public
- * @deprecated
- */
- var $http_headers = false;
-
- /**
- * The fields to send in a 'POST' request
- *
- * @var array $fields
- * @access public
- */
- var $fields;
-
- /**
- * The proxy server to go through
- *
- * @var string $proxy
- * @access public
- */
- var $proxy;
-
- /**
- * The username for the Proxy server
- *
- * @var string $proxyUser
- * @access public
- */
- var $proxyUser;
-
- /**
- * The password for the Proxy server
- *
- * @var string $proxyPassword
- * @access public
- */
- var $proxyPassword;
-
- /**
- * $verifyPeer
- *
- * FALSE to stop CURL from verifying the peer's certificate.
- * Alternate certificates to verify against can be specified
- * with the CURLOPT_CAINFO option or a certificate directory
- * can be specified with the CURLOPT_CAPATH option.
- * CURLOPT_SSL_VERIFYHOST may also need to be TRUE or FALSE
- * if CURLOPT_SSL_VERIFYPEER is disabled (it defaults to 2).
- *
- * @var boolean $verifyPeer
- * @access public
- */
- var $verifyPeer = true;
-
- /**
- * $verifyHost
- *
- * 0 : to stop CURL from verifying the host's certificate.
- * 1 : to check the existence of a common name in the SSL peer certificate.
- * 2 : to check the existence of a common name and also verify that it
- * matches the hostname provided.
- *
- * @var bool $verifyHost
- * @access public
- */
- var $verifyHost = 2;
-
- /**
- * $caInfo
- *
- * Set value for CURLOPT_CAINFO. The name of a file holding one or more
- * certificates to verify the peer with. This only makes sense when used
- * in combination with CURLOPT_SSL_VERIFYPEER. curl-ca-bundle.crt is
- * avaible on the Curl website http://curl.haxx.se/ for download inside
- * the packages.
- *
- * @var string $caInfo
- * @access public
- */
- var $caInfo = '';
-
- /**
- * $caPath
- *
- * Set value for CURLOPT_CAPATH. A directory that holds multiple CA
- * certificates. Use this option alongside CURLOPT_SSL_VERIFYPEER.
- *
- * @var string $caPath
- * @access public
- */
- var $caPath;
- // }}}
- // {{{ Private Properties
- /**
- * The current curl handle
- *
- * @var resource $_ch
- * @access private
- * @see Net_Curl::create()
- */
- var $_ch = null;
-
- /**
- * The file upload resource
- *
- * The CURLOPT_INFILE requires a file resource and not just a file name.
- * This is used by execute to open the file.
- *
- * @var resource $_fp
- * @access private
- * @see Net_Curl::execute()
- */
- var $_fp = null;
- // }}}
- // {{{ __construct($url = '', $userAgent = '')
- /**
- * The Net_Curl PHP 5.x constructor, called when a new Net_Curl object
- * is initialized (also called via 4.x constructor)
- *
- * @param string $url The URL to fetch (can be set using the $url property as well)
- * @param string $userAgent The userAgent string (can be set using the $userAgent property as well)
- * @access public
- * @author Joe Stump <joe@joestump.net>
- */
- function __construct($url = '', $userAgent = '')
- {
- if (is_string($url) && strlen($url)) {
- $this->url = $url;
- }
-
- if (is_string($userAgent) && strlen($userAgent)) {
- $this->userAgent = $userAgent;
- }
- }
- // }}}
- // {{{ Net_Curl($url = '', $userAgent = '')
- /**
- * Net_Curl
- *
- * PHP 4.x constructor.
- *
- * @access public
- * @author Joe Stump <joe@joestump.net>
- */
- function Net_Curl($url = '', $userAgent = '')
- {
- $this->__construct($url,$userAgent);
- }
- // }}}
- // {{{ execute()
- /**
- * Executes a prepared CURL transfer
- *
- * Run this function to execute your cURL request. If all goes well you
- * should get a string (the output from the remote host regarding your
- * request) or true (if you choose to output directly to the browser). If
- * something fails then PEAR_Error is returned.
- *
- * <code>
- * <?php
- * require_once('Net/Curl.php');
- *
- * $curl = & new Net_Curl('http://www.example.com');
- * $curl->fields = array('foo' => '1', 'bar' => 'apple');
- * $result = $curl->execute();
- * if (!PEAR::isError($result)) {
- * echo $result;
- * }
- * ?>
- * </code>
- *
- * @access public
- * @author Sterling Hughes <sterling@php.net>
- * @author Joe Stump <joe@joestump.net>
- * @return PEAR_Error on failure, true/result on success
- * @since PHP 4.0.5
- */
- function execute()
- {
- // Create cURL handle if it hasn't already been created
- if (!is_resource($this->_ch)) {
- $result = $this->create();
- if (PEAR::isError($result)) {
- return $result;
- }
- }
-
- // Map the deprecated variables and throw a bunch of errors
- $this->_mapDeprecatedVariables();
-
- // Default return value is true.
- $ret = true;
-
- // Basic stuff
- $ret = curl_setopt($this->_ch, CURLOPT_URL, $this->url);
- $ret = curl_setopt($this->_ch, CURLOPT_HEADER, $this->header);
-
- // Whether or not to return the transfer contents
- if ($this->returnTransfer === true) {
- $ret = curl_setopt($this->_ch, CURLOPT_RETURNTRANSFER, true);
- }
-
- // HTTP Authentication
- if ($this->username != '') {
- $ret = curl_setopt($this->_ch, CURLOPT_USERPWD, $this->username . ':' . $this->password);
- }
-
- // SSL Checks
- if (isset($this->sslVersion)) {
- $ret = curl_setopt($this->_ch, CURLOPT_SSLVERSION, $this->sslVersion);
- }
-
- if (isset($this->sslCert)) {
- $ret = curl_setopt($this->_ch, CURLOPT_SSLCERT, $this->sslCert);
- }
-
- if (isset($this->sslCertPasswd)) {
- $ret = curl_setopt($this->_ch, CURLOPT_SSLCERTPASSWD, $this->sslCertPasswd);
- }
-
- // Proxy Related checks
- if (isset($this->proxy)) {
- $ret = curl_setopt($this->_ch, CURLOPT_PROXY, $this->proxy);
- }
-
- if (isset($this->proxyUser) || isset($this->proxyPassword)) {
- $ret = curl_setopt($this->_ch, CURLOPT_PROXYUSERPWD, $this->proxyUser . ':' . $this->proxyPassword);
- }
-
- if (is_bool($this->verifyPeer)) {
- if(!$this->setOption(CURLOPT_SSL_VERIFYPEER,$this->verifyPeer)) {
- return PEAR::raiseError('Error setting CURLOPT_SSL_VERIFYPEER');
- }
- }
-
- if (is_numeric($this->verifyHost) && $this->verifyHost >= 0 &&
- $this->verifyHost <= 2) {
- if(!$this->setOption(CURLOPT_SSL_VERIFYHOST,$this->verifyHost)) {
- return PEAR::raiseError('Error setting CURLOPT_SSL_VERIFYPEER');
- }
- }
-
- if (is_bool($this->verifyPeer) && $this->verifyPeer == true) {
- if (isset($this->caInfo) && strlen($this->caInfo)) {
- if (file_exists($this->caInfo)) {
- if (!$this->setOption(CURLOPT_CAINFO,$this->caInfo)) {
- return PEAR::raiseError('Error setting CURLOPT_CAINFO');
- }
- } else {
- return PEAR::raiseError('Could not find CA info: '.$this->caInfo);
- }
- }
-
- if (isset($this->caPath) && is_string($this->caPath)) {
- if (!$this->setOption(CURLOPT_CAPATH,$this->caPath)) {
- return PEAR::raiseError('Error setting CURLOPT_CAPATH');
- }
- }
- }
-
- // Transfer type
- if (isset($this->type)) {
- switch (strtolower($this->type)) {
- case 'post':
- $ret = curl_setopt($this->_ch, CURLOPT_POST, true);
- break;
- case 'put':
- $ret = curl_setopt($this->_ch, CURLOPT_PUT, true);
- break;
- }
- }
-
- // Transfer upload, etc. related
- if (isset($this->file)) {
- if (!file_exists($this->file)) {
- return PEAR::raiseError('File does not exist: '.$this->file);
- }
-
- $this->_fp = fopen($this->file,'r');
- if (!is_resource($this->_fp)) {
- return PEAR::raiseError('Could not open file: '.$this->file);
- }
-
- if (!isset($this->fileSize)) {
- $this->fileSize = filesize($this->file);
- }
-
- $ret = curl_setopt($this->_ch, CURLOPT_INFILE, $this->_fp);
- $ret = curl_setopt($this->_ch, CURLOPT_INFILESIZE, $this->fileSize);
- $ret = curl_setopt($this->_ch, CURLOPT_UPLOAD, true);
- }
-
- if (isset($this->fields)) {
- if (!isset($this->type)) {
- $this->type = 'post';
- $ret = curl_setopt($this->_ch, CURLOPT_POST, true);
- }
-
- // If fields is an array then turn it into a string. Somtimes
- // cURL doesn't like fields as an array.
- if (is_array($this->fields)) {
- $sets = array();
- foreach ($this->fields as $key => $val) {
- $sets[] = $key . '=' . urlencode($val);
- }
-
- $fields = implode('&',$sets);
- } else {
- $fields = $this->fields;
- }
-
- $ret = curl_setopt($this->_ch, CURLOPT_POSTFIELDS, $fields);
- }
-
- // Error related
- if ($this->progress === true) {
- $ret = curl_setopt($this->_ch, CURLOPT_PROGRESS, true);
- }
-
- if ($this->verbose === true) {
- $ret = curl_setopt($this->_ch, CURLOPT_VERBOSE, true);
- }
-
- if ($this->mute !== true) {
- $ret = curl_setopt($this->_ch, CURLOPT_MUTE, false);
- }
-
- // If a Location: header is passed then follow it
- $ret = curl_setopt($this->_ch, CURLOPT_FOLLOWLOCATION, $this->followLocation);
-
- // If a timeout is set and is greater then zero then set it
- if (is_numeric($this->timeout) && $this->timeout > 0) {
- $ret = curl_setopt($this->_ch, CURLOPT_TIMEOUT, $this->timeout);
- }
-
- if (isset($this->userAgent)) {
- $ret = curl_setopt($this->_ch, CURLOPT_USERAGENT, $this->userAgent);
- }
-
- // Cookies
- if (is_array($this->cookies) && count($this->cookies)) {
- $cookieData = '';
- foreach ($this->cookies as $name => $value) {
- $cookieData .= $name . '=' . $value . ';';
- }
-
- $ret = curl_setopt($this->_ch, CURLOPT_COOKIE, $cookieData);
- }
-
- // Other HTTP headers
- if ($this->httpHeaders !== null) {
- if (is_array($this->httpHeaders)) {
- $ret = curl_setopt($this->_ch, CURLOPT_HTTPHEADER, $this->httpHeaders);
- } else {
- return PEAR::raiseError('Net_Curl::$httpHeaders must be an array');
- }
- }
-
- $ret = curl_exec($this->_ch);
-
- // Close the file before we return anything
- if (is_resource($this->_fp)) {
- fclose($this->_fp);
- }
-
- if (curl_errno($this->_ch)) {
- return PEAR::raiseError(curl_error($this->_ch), curl_errno($this->_ch));
- }
-
- // Check to make sure we get a 2XX/3XX code and not a 404 or something.
- $info = $this->getInfo();
- if (!isset($info['http_code'])) {
- return PEAR::raiseError('Unknown or invalid HTTP response');
- } else {
- $type = substr($info['http_code'],0,1);
- if ($type != 2 && $type != 3) {
- return PEAR::raiseError('Unexpected HTTP code: '.$info['http_code']);
- }
- }
-
- return $ret;
- }
- // }}}
- // {{{ setOption($option, $value)
- /**
- * setOption
- *
- * Set a option for your cURL session. Please note that the cURL handler
- * is NOT created before execute(). This is for error checking purposes.
- * You should use setOption() in the following manner:
- *
- * <code>
- * <?php
- *
- * require_once('Net/Curl.php');
- * $curl = & new Net_Curl('http://www.example.com');
- * $check = $curl->create();
- * if (!PEAR::isError($check)) {
- * $curl->setOption(CURLOPT_FOO,'bar');
- * $result = $curl->execute();
- * if (!PEAR::isError($result)) {
- * echo $result;
- * }
- * }
- *
- * ?>
- * </code>
- *
- * @author Joe Stump <joe@joestump.net>
- * @access public
- * @param int $option cURL constant (ie. CURLOPT_URL)
- * @param mixed $value
- * @return boolean
- */
- function setOption($option, $value)
- {
- if (is_resource($this->_ch)) {
- return curl_setopt($this->_ch, $option, $value);
- }
-
- return false;
- }
- // }}}
- // {{{ getInfo()
- /**
- * getInfo
- *
- * Returns the info from the cURL session. PEAR_Error if you try and run
- * this before you execute the session.
- *
- * @author Joe Stump <joe@joestump.net>
- * @access public
- * @return mixed PEAR_Error if there is no resource, info on success
- */
- function getInfo()
- {
- if (is_resource($this->_ch)) {
- return curl_getinfo($this->_ch);
- }
-
- return PEAR::isError('cURL handler does not exist!');
- }
- // }}}
- // {{{ create()
- /**
- * create
- *
- * Create a cURL resource. If curl_init() doesn't exist or we could not
- * create a resource it will error out.
- *
- * @author Joe Stump <joe@joestump.net>
- * @return mixed PEAR_Error on failure, true on success
- */
- function create()
- {
- if (!function_exists('curl_init')) {
- return PEAR::raiseError('Function curl_init() not found');
- }
-
- $this->_ch = curl_init();
- if (!is_resource($this->_ch)) {
- return PEAR::raiseError('Could not initialize cURL handler');
- }
-
- return true;
- }
- // }}}
- // {{{ verboseAll()
- /**
- * Set a verbose output
- *
- * Turns on super debugging mode by not suppressing errors, turning on
- * verbose mode, showing headers and displaying progress.
- *
- * @access public
- * @author David Costa <gurugeek@php.net>
- * @return void
- */
- function verboseAll()
- {
- $this->verbose = true;
- $this->mute = false;
- $this->header = true;
- $this->progress = true;
- }
- // }}}
- // {{{ verbose_all()
- /**
- * Set a verbose output
- *
- * @access public
- * @author David Costa <gurugeek@php.net>
- * @deprecated
- */
- function verbose_all()
- {
- $this->verboseAll();
- PEAR::raiseError('Net_Curl::verbose_all() is deprecated! Please use Net_Curl::verboseAll()'." <br />\n",null,PEAR_ERROR_PRINT);
-
- }
- // }}}
- // {{{ close()
- /**
- * Closes the curl transfer and finishes the object (kinda ;)
- *
- * @access public
- * @author Sterling Hughes <sterling@php.net>
- * @return void
- * @since PHP 4.0.5
- */
- function close()
- {
- if (is_resource($this->_ch)) {
- curl_close($this->_ch);
- }
- }
- // }}}
- // {{{ _mapDeprecatedVariables()
- /**
- * _mapDeprecatedVariables
- *
- * Maps deprecated variables into the appropriate places. It also throws
- * the necessary notices.
- *
- * @author Joe Stump <joe@joestump.net>
- * @access private
- * @return void
- */
- function _mapDeprecatedVariables() {
- $bad = array();
- if ($this->follow_location !== false) {
- if ($this->follow_location > 0) {
- $this->followLocation = true;
- } else {
- $this->followLocation = false;
- }
-
- $bad[] = array('follow_location','followLocation');
- }
-
- if ($this->return_transfer !== false) {
- if ($this->return_transfer > 0) {
- $this->returnTransfer = true;
- } else {
- $this->returnTransfer = false;
- }
-
- $bad[] = array('return_transfer','returnTransfer');
- }
-
- if ($this->file_size !== false) {
- $this->fileSize = $this->file_size;
- $bad[] = array('file_size','fileSize');
- }
-
- if ($this->http_headers !== false) {
- $this->httpHeaders = $this->http_headers;
- $bad[] = array('http_headers','httpHeaders');
- }
-
- foreach ($bad as $map) {
- PEAR::raiseError('Net_Curl::$'.$map[0].' is deprecated! Please use Net_Curl::$'.$map[1]." instead! <br />\n",null,PEAR_ERROR_PRINT);
- }
- }
- // {{{ __destruct()
- /**
- * __destruct
- *
- * PHP 5.x destructor. Runs Net_Curl::close() to make sure we close our
- * cURL connection.
- *
- * @author Joe Stump <joe@joestump.net>
- * @see Net_Curl::close()
- */
- function __destruct()
- {
- $this->close();
- }
- // }}}
-}
-
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Chuck Hagenbuch <chuck@horde.org> |
-// | Jon Parise <jon@php.net> |
-// | Damian Alejandro Fernandez Sosa <damlists@cnba.uba.ar> |
-// +----------------------------------------------------------------------+
-//
-// $Id: SMTP.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
-
-require_once 'PEAR.php';
-require_once 'Net/Socket.php';
-
-/**
- * Provides an implementation of the SMTP protocol using PEAR's
- * Net_Socket:: class.
- *
- * @package Net_SMTP
- * @author Chuck Hagenbuch <chuck@horde.org>
- * @author Jon Parise <jon@php.net>
- * @author Damian Alejandro Fernandez Sosa <damlists@cnba.uba.ar>
- *
- * @example basic.php A basic implementation of the Net_SMTP package.
- */
-class Net_SMTP
-{
- /**
- * The server to connect to.
- * @var string
- * @access public
- */
- var $host = 'localhost';
-
- /**
- * The port to connect to.
- * @var int
- * @access public
- */
- var $port = 25;
-
- /**
- * The value to give when sending EHLO or HELO.
- * @var string
- * @access public
- */
- var $localhost = 'localhost';
-
- /**
- * List of supported authentication methods, in preferential order.
- * @var array
- * @access public
- */
- var $auth_methods = array('DIGEST-MD5', 'CRAM-MD5', 'LOGIN', 'PLAIN');
-
- /**
- * Use SMTP command pipelining (specified in RFC 2920) if the SMTP
- * server supports it.
- *
- * When pipeling is enabled, rcptTo(), mailFrom(), sendFrom(),
- * somlFrom() and samlFrom() do not wait for a response from the
- * SMTP server but return immediately.
- *
- * @var bool
- * @access public
- */
- var $pipelining = false;
-
- /**
- * Number of pipelined commands.
- * @var int
- * @access private
- */
- var $_pipelined_commands = 0;
-
- /**
- * Should debugging output be enabled?
- * @var boolean
- * @access private
- */
- var $_debug = false;
-
- /**
- * The socket resource being used to connect to the SMTP server.
- * @var resource
- * @access private
- */
- var $_socket = null;
-
- /**
- * The most recent server response code.
- * @var int
- * @access private
- */
- var $_code = -1;
-
- /**
- * The most recent server response arguments.
- * @var array
- * @access private
- */
- var $_arguments = array();
-
- /**
- * Stores detected features of the SMTP server.
- * @var array
- * @access private
- */
- var $_esmtp = array();
-
- /**
- * Instantiates a new Net_SMTP object, overriding any defaults
- * with parameters that are passed in.
- *
- * If you have SSL support in PHP, you can connect to a server
- * over SSL using an 'ssl://' prefix:
- *
- * // 465 is a common smtps port.
- * $smtp = new Net_SMTP('ssl://mail.host.com', 465);
- * $smtp->connect();
- *
- * @param string $host The server to connect to.
- * @param integer $port The port to connect to.
- * @param string $localhost The value to give when sending EHLO or HELO.
- * @param boolean $pipeling Use SMTP command pipelining
- *
- * @access public
- * @since 1.0
- */
- function Net_SMTP($host = null, $port = null, $localhost = null, $pipelining = false)
- {
- if (isset($host)) {
- $this->host = $host;
- }
- if (isset($port)) {
- $this->port = $port;
- }
- if (isset($localhost)) {
- $this->localhost = $localhost;
- }
- $this->pipelining = $pipelining;
-
- $this->_socket = new Net_Socket();
-
- /* Include the Auth_SASL package. If the package is not
- * available, we disable the authentication methods that
- * depend upon it. */
- if ((@include_once 'Auth/SASL.php') === false) {
- $pos = array_search('DIGEST-MD5', $this->auth_methods);
- unset($this->auth_methods[$pos]);
- $pos = array_search('CRAM-MD5', $this->auth_methods);
- unset($this->auth_methods[$pos]);
- }
- }
-
- /**
- * Set the value of the debugging flag.
- *
- * @param boolean $debug New value for the debugging flag.
- *
- * @access public
- * @since 1.1.0
- */
- function setDebug($debug)
- {
- $this->_debug = $debug;
- }
-
- /**
- * Send the given string of data to the server.
- *
- * @param string $data The string of data to send.
- *
- * @return mixed True on success or a PEAR_Error object on failure.
- *
- * @access private
- * @since 1.1.0
- */
- function _send($data)
- {
- if ($this->_debug) {
- echo "DEBUG: Send: $data\n";
- }
-
- if (PEAR::isError($error = $this->_socket->write($data))) {
- return PEAR::raiseError('Failed to write to socket: ' .
- $error->getMessage());
- }
-
- return true;
- }
-
- /**
- * Send a command to the server with an optional string of
- * arguments. A carriage return / linefeed (CRLF) sequence will
- * be appended to each command string before it is sent to the
- * SMTP server - an error will be thrown if the command string
- * already contains any newline characters. Use _send() for
- * commands that must contain newlines.
- *
- * @param string $command The SMTP command to send to the server.
- * @param string $args A string of optional arguments to append
- * to the command.
- *
- * @return mixed The result of the _send() call.
- *
- * @access private
- * @since 1.1.0
- */
- function _put($command, $args = '')
- {
- if (!empty($args)) {
- $command .= ' ' . $args;
- }
-
- if (strcspn($command, "\r\n") !== strlen($command)) {
- return PEAR::raiseError('Commands cannot contain newlines');
- }
-
- return $this->_send($command . "\r\n");
- }
-
- /**
- * Read a reply from the SMTP server. The reply consists of a response
- * code and a response message.
- *
- * @param mixed $valid The set of valid response codes. These
- * may be specified as an array of integer
- * values or as a single integer value.
- * @param bool $later Do not parse the response now, but wait
- * until the last command in the pipelined
- * command group
- *
- * @return mixed True if the server returned a valid response code or
- * a PEAR_Error object is an error condition is reached.
- *
- * @access private
- * @since 1.1.0
- *
- * @see getResponse
- */
- function _parseResponse($valid, $later = false)
- {
- $this->_code = -1;
- $this->_arguments = array();
-
- if ($later) {
- $this->_pipelined_commands++;
- return true;
- }
-
- for ($i = 0; $i <= $this->_pipelined_commands; $i++) {
- while ($line = $this->_socket->readLine()) {
- if ($this->_debug) {
- echo "DEBUG: Recv: $line\n";
- }
-
- /* If we receive an empty line, the connection has been closed. */
- if (empty($line)) {
- $this->disconnect();
- return PEAR::raiseError('Connection was unexpectedly closed');
- }
-
- /* Read the code and store the rest in the arguments array. */
- $code = substr($line, 0, 3);
- $this->_arguments[] = trim(substr($line, 4));
-
- /* Check the syntax of the response code. */
- if (is_numeric($code)) {
- $this->_code = (int)$code;
- } else {
- $this->_code = -1;
- break;
- }
-
- /* If this is not a multiline response, we're done. */
- if (substr($line, 3, 1) != '-') {
- break;
- }
- }
- }
-
- $this->_pipelined_commands = 0;
-
- /* Compare the server's response code with the valid code/codes. */
- if (is_int($valid) && ($this->_code === $valid)) {
- return true;
- } elseif (is_array($valid)) {
- return in_array($this->_code, $valid, true);
- }
-
- return PEAR::raiseError('Invalid response code received from server',
- $this->_code);
- }
-
- /**
- * Return a 2-tuple containing the last response from the SMTP server.
- *
- * @return array A two-element array: the first element contains the
- * response code as an integer and the second element
- * contains the response's arguments as a string.
- *
- * @access public
- * @since 1.1.0
- */
- function getResponse()
- {
- return array($this->_code, join("\n", $this->_arguments));
- }
-
- /**
- * Attempt to connect to the SMTP server.
- *
- * @param int $timeout The timeout value (in seconds) for the
- * socket connection.
- * @param bool $persistent Should a persistent socket connection
- * be used?
- *
- * @return mixed Returns a PEAR_Error with an error message on any
- * kind of failure, or true on success.
- * @access public
- * @since 1.0
- */
- function connect($timeout = null, $persistent = false)
- {
- $result = $this->_socket->connect($this->host, $this->port,
- $persistent, $timeout);
- if (PEAR::isError($result)) {
- return PEAR::raiseError('Failed to connect socket: ' .
- $result->getMessage());
- }
-
- if (PEAR::isError($error = $this->_parseResponse(220))) {
- return $error;
- }
- if (PEAR::isError($error = $this->_negotiate())) {
- return $error;
- }
-
- return true;
- }
-
- /**
- * Attempt to disconnect from the SMTP server.
- *
- * @return mixed Returns a PEAR_Error with an error message on any
- * kind of failure, or true on success.
- * @access public
- * @since 1.0
- */
- function disconnect()
- {
- if (PEAR::isError($error = $this->_put('QUIT'))) {
- return $error;
- }
- if (PEAR::isError($error = $this->_parseResponse(221))) {
- return $error;
- }
- if (PEAR::isError($error = $this->_socket->disconnect())) {
- return PEAR::raiseError('Failed to disconnect socket: ' .
- $error->getMessage());
- }
-
- return true;
- }
-
- /**
- * Attempt to send the EHLO command and obtain a list of ESMTP
- * extensions available, and failing that just send HELO.
- *
- * @return mixed Returns a PEAR_Error with an error message on any
- * kind of failure, or true on success.
- *
- * @access private
- * @since 1.1.0
- */
- function _negotiate()
- {
- if (PEAR::isError($error = $this->_put('EHLO', $this->localhost))) {
- return $error;
- }
-
- if (PEAR::isError($this->_parseResponse(250))) {
- /* If we receive a 503 response, we're already authenticated. */
- if ($this->_code === 503) {
- return true;
- }
-
- /* If the EHLO failed, try the simpler HELO command. */
- if (PEAR::isError($error = $this->_put('HELO', $this->localhost))) {
- return $error;
- }
- if (PEAR::isError($this->_parseResponse(250))) {
- return PEAR::raiseError('HELO was not accepted: ', $this->_code);
- }
-
- return true;
- }
-
- foreach ($this->_arguments as $argument) {
- $verb = strtok($argument, ' ');
- $arguments = substr($argument, strlen($verb) + 1,
- strlen($argument) - strlen($verb) - 1);
- $this->_esmtp[$verb] = $arguments;
- }
-
- if (!isset($this->_esmtp['PIPELINING'])) {
- $this->pipelining = false;
- }
-
- return true;
- }
-
- /**
- * Returns the name of the best authentication method that the server
- * has advertised.
- *
- * @return mixed Returns a string containing the name of the best
- * supported authentication method or a PEAR_Error object
- * if a failure condition is encountered.
- * @access private
- * @since 1.1.0
- */
- function _getBestAuthMethod()
- {
- $available_methods = explode(' ', $this->_esmtp['AUTH']);
-
- foreach ($this->auth_methods as $method) {
- if (in_array($method, $available_methods)) {
- return $method;
- }
- }
-
- return PEAR::raiseError('No supported authentication methods');
- }
-
- /**
- * Attempt to do SMTP authentication.
- *
- * @param string The userid to authenticate as.
- * @param string The password to authenticate with.
- * @param string The requested authentication method. If none is
- * specified, the best supported method will be used.
- *
- * @return mixed Returns a PEAR_Error with an error message on any
- * kind of failure, or true on success.
- * @access public
- * @since 1.0
- */
- function auth($uid, $pwd , $method = '')
- {
- if (empty($this->_esmtp['AUTH'])) {
- if (version_compare(PHP_VERSION, '5.1.0', '>=')) {
- if (!isset($this->_esmtp['STARTTLS'])) {
- return PEAR::raiseError('SMTP server does not support authentication');
- }
- if (PEAR::isError($result = $this->_put('STARTTLS'))) {
- return $result;
- }
- if (PEAR::isError($result = $this->_parseResponse(220))) {
- return $result;
- }
- if (PEAR::isError($result = $this->_socket->enableCrypto(true, STREAM_CRYPTO_METHOD_TLS_CLIENT))) {
- return $result;
- } elseif ($result !== true) {
- return PEAR::raiseError('STARTTLS failed');
- }
-
- /* Send EHLO again to recieve the AUTH string from the
- * SMTP server. */
- $this->_negotiate();
- if (empty($this->_esmtp['AUTH'])) {
- return PEAR::raiseError('SMTP server does not support authentication');
- }
- } else {
- return PEAR::raiseError('SMTP server does not support authentication');
- }
- }
-
- /* If no method has been specified, get the name of the best
- * supported method advertised by the SMTP server. */
- if (empty($method)) {
- if (PEAR::isError($method = $this->_getBestAuthMethod())) {
- /* Return the PEAR_Error object from _getBestAuthMethod(). */
- return $method;
- }
- } else {
- $method = strtoupper($method);
- if (!in_array($method, $this->auth_methods)) {
- return PEAR::raiseError("$method is not a supported authentication method");
- }
- }
-
- switch ($method) {
- case 'DIGEST-MD5':
- $result = $this->_authDigest_MD5($uid, $pwd);
- break;
-
- case 'CRAM-MD5':
- $result = $this->_authCRAM_MD5($uid, $pwd);
- break;
-
- case 'LOGIN':
- $result = $this->_authLogin($uid, $pwd);
- break;
-
- case 'PLAIN':
- $result = $this->_authPlain($uid, $pwd);
- break;
-
- default:
- $result = PEAR::raiseError("$method is not a supported authentication method");
- break;
- }
-
- /* If an error was encountered, return the PEAR_Error object. */
- if (PEAR::isError($result)) {
- return $result;
- }
-
- return true;
- }
-
- /**
- * Authenticates the user using the DIGEST-MD5 method.
- *
- * @param string The userid to authenticate as.
- * @param string The password to authenticate with.
- *
- * @return mixed Returns a PEAR_Error with an error message on any
- * kind of failure, or true on success.
- * @access private
- * @since 1.1.0
- */
- function _authDigest_MD5($uid, $pwd)
- {
- if (PEAR::isError($error = $this->_put('AUTH', 'DIGEST-MD5'))) {
- return $error;
- }
- /* 334: Continue authentication request */
- if (PEAR::isError($error = $this->_parseResponse(334))) {
- /* 503: Error: already authenticated */
- if ($this->_code === 503) {
- return true;
- }
- return $error;
- }
-
- $challenge = base64_decode($this->_arguments[0]);
- $digest = &Auth_SASL::factory('digestmd5');
- $auth_str = base64_encode($digest->getResponse($uid, $pwd, $challenge,
- $this->host, "smtp"));
-
- if (PEAR::isError($error = $this->_put($auth_str))) {
- return $error;
- }
- /* 334: Continue authentication request */
- if (PEAR::isError($error = $this->_parseResponse(334))) {
- return $error;
- }
-
- /* We don't use the protocol's third step because SMTP doesn't
- * allow subsequent authentication, so we just silently ignore
- * it. */
- if (PEAR::isError($error = $this->_put(''))) {
- return $error;
- }
- /* 235: Authentication successful */
- if (PEAR::isError($error = $this->_parseResponse(235))) {
- return $error;
- }
- }
-
- /**
- * Authenticates the user using the CRAM-MD5 method.
- *
- * @param string The userid to authenticate as.
- * @param string The password to authenticate with.
- *
- * @return mixed Returns a PEAR_Error with an error message on any
- * kind of failure, or true on success.
- * @access private
- * @since 1.1.0
- */
- function _authCRAM_MD5($uid, $pwd)
- {
- if (PEAR::isError($error = $this->_put('AUTH', 'CRAM-MD5'))) {
- return $error;
- }
- /* 334: Continue authentication request */
- if (PEAR::isError($error = $this->_parseResponse(334))) {
- /* 503: Error: already authenticated */
- if ($this->_code === 503) {
- return true;
- }
- return $error;
- }
-
- $challenge = base64_decode($this->_arguments[0]);
- $cram = &Auth_SASL::factory('crammd5');
- $auth_str = base64_encode($cram->getResponse($uid, $pwd, $challenge));
-
- if (PEAR::isError($error = $this->_put($auth_str))) {
- return $error;
- }
-
- /* 235: Authentication successful */
- if (PEAR::isError($error = $this->_parseResponse(235))) {
- return $error;
- }
- }
-
- /**
- * Authenticates the user using the LOGIN method.
- *
- * @param string The userid to authenticate as.
- * @param string The password to authenticate with.
- *
- * @return mixed Returns a PEAR_Error with an error message on any
- * kind of failure, or true on success.
- * @access private
- * @since 1.1.0
- */
- function _authLogin($uid, $pwd)
- {
- if (PEAR::isError($error = $this->_put('AUTH', 'LOGIN'))) {
- return $error;
- }
- /* 334: Continue authentication request */
- if (PEAR::isError($error = $this->_parseResponse(334))) {
- /* 503: Error: already authenticated */
- if ($this->_code === 503) {
- return true;
- }
- return $error;
- }
-
- if (PEAR::isError($error = $this->_put(base64_encode($uid)))) {
- return $error;
- }
- /* 334: Continue authentication request */
- if (PEAR::isError($error = $this->_parseResponse(334))) {
- return $error;
- }
-
- if (PEAR::isError($error = $this->_put(base64_encode($pwd)))) {
- return $error;
- }
-
- /* 235: Authentication successful */
- if (PEAR::isError($error = $this->_parseResponse(235))) {
- return $error;
- }
-
- return true;
- }
-
- /**
- * Authenticates the user using the PLAIN method.
- *
- * @param string The userid to authenticate as.
- * @param string The password to authenticate with.
- *
- * @return mixed Returns a PEAR_Error with an error message on any
- * kind of failure, or true on success.
- * @access private
- * @since 1.1.0
- */
- function _authPlain($uid, $pwd)
- {
- if (PEAR::isError($error = $this->_put('AUTH', 'PLAIN'))) {
- return $error;
- }
- /* 334: Continue authentication request */
- if (PEAR::isError($error = $this->_parseResponse(334))) {
- /* 503: Error: already authenticated */
- if ($this->_code === 503) {
- return true;
- }
- return $error;
- }
-
- $auth_str = base64_encode(chr(0) . $uid . chr(0) . $pwd);
-
- if (PEAR::isError($error = $this->_put($auth_str))) {
- return $error;
- }
-
- /* 235: Authentication successful */
- if (PEAR::isError($error = $this->_parseResponse(235))) {
- return $error;
- }
-
- return true;
- }
-
- /**
- * Send the HELO command.
- *
- * @param string The domain name to say we are.
- *
- * @return mixed Returns a PEAR_Error with an error message on any
- * kind of failure, or true on success.
- * @access public
- * @since 1.0
- */
- function helo($domain)
- {
- if (PEAR::isError($error = $this->_put('HELO', $domain))) {
- return $error;
- }
- if (PEAR::isError($error = $this->_parseResponse(250))) {
- return $error;
- }
-
- return true;
- }
-
- /**
- * Send the MAIL FROM: command.
- *
- * @param string $sender The sender (reverse path) to set.
- * @param string $params String containing additional MAIL parameters,
- * such as the NOTIFY flags defined by RFC 1891
- * or the VERP protocol.
- *
- * If $params is an array, only the 'verp' option
- * is supported. If 'verp' is true, the XVERP
- * parameter is appended to the MAIL command. If
- * the 'verp' value is a string, the full
- * XVERP=value parameter is appended.
- *
- * @return mixed Returns a PEAR_Error with an error message on any
- * kind of failure, or true on success.
- * @access public
- * @since 1.0
- */
- function mailFrom($sender, $params = null)
- {
- $args = "FROM:<$sender>";
-
- /* Support the deprecated array form of $params. */
- if (is_array($params) && isset($params['verp'])) {
- /* XVERP */
- if ($params['verp'] === true) {
- $args .= ' XVERP';
-
- /* XVERP=something */
- } elseif (trim($params['verp'])) {
- $args .= ' XVERP=' . $params['verp'];
- }
- } elseif (is_string($params)) {
- $args .= ' ' . $params;
- }
-
- if (PEAR::isError($error = $this->_put('MAIL', $args))) {
- return $error;
- }
- if (PEAR::isError($error = $this->_parseResponse(250, $this->pipelining))) {
- return $error;
- }
-
- return true;
- }
-
- /**
- * Send the RCPT TO: command.
- *
- * @param string $recipient The recipient (forward path) to add.
- * @param string $params String containing additional RCPT parameters,
- * such as the NOTIFY flags defined by RFC 1891.
- *
- * @return mixed Returns a PEAR_Error with an error message on any
- * kind of failure, or true on success.
- *
- * @access public
- * @since 1.0
- */
- function rcptTo($recipient, $params = null)
- {
- $args = "TO:<$recipient>";
- if (is_string($params)) {
- $args .= ' ' . $params;
- }
-
- if (PEAR::isError($error = $this->_put('RCPT', $args))) {
- return $error;
- }
- if (PEAR::isError($error = $this->_parseResponse(array(250, 251), $this->pipelining))) {
- return $error;
- }
-
- return true;
- }
-
- /**
- * Quote the data so that it meets SMTP standards.
- *
- * This is provided as a separate public function to facilitate
- * easier overloading for the cases where it is desirable to
- * customize the quoting behavior.
- *
- * @param string $data The message text to quote. The string must be passed
- * by reference, and the text will be modified in place.
- *
- * @access public
- * @since 1.2
- */
- function quotedata(&$data)
- {
- /* Change Unix (\n) and Mac (\r) linefeeds into
- * Internet-standard CRLF (\r\n) linefeeds. */
- $data = preg_replace(array('/(?<!\r)\n/','/\r(?!\n)/'), "\r\n", $data);
-
- /* Because a single leading period (.) signifies an end to the
- * data, legitimate leading periods need to be "doubled"
- * (e.g. '..'). */
- $data = str_replace("\n.", "\n..", $data);
- }
-
- /**
- * Send the DATA command.
- *
- * @param string $data The message body to send.
- *
- * @return mixed Returns a PEAR_Error with an error message on any
- * kind of failure, or true on success.
- * @access public
- * @since 1.0
- */
- function data($data)
- {
- /* RFC 1870, section 3, subsection 3 states "a value of zero
- * indicates that no fixed maximum message size is in force".
- * Furthermore, it says that if "the parameter is omitted no
- * information is conveyed about the server's fixed maximum
- * message size". */
- if (isset($this->_esmtp['SIZE']) && ($this->_esmtp['SIZE'] > 0)) {
- if (strlen($data) >= $this->_esmtp['SIZE']) {
- $this->disconnect();
- return PEAR::raiseError('Message size excedes the server limit');
- }
- }
-
- /* Quote the data based on the SMTP standards. */
- $this->quotedata($data);
-
- if (PEAR::isError($error = $this->_put('DATA'))) {
- return $error;
- }
- if (PEAR::isError($error = $this->_parseResponse(354))) {
- return $error;
- }
-
- if (PEAR::isError($result = $this->_send($data . "\r\n.\r\n"))) {
- return $result;
- }
- if (PEAR::isError($error = $this->_parseResponse(250, $this->pipelining))) {
- return $error;
- }
-
- return true;
- }
-
- /**
- * Send the SEND FROM: command.
- *
- * @param string The reverse path to send.
- *
- * @return mixed Returns a PEAR_Error with an error message on any
- * kind of failure, or true on success.
- * @access public
- * @since 1.2.6
- */
- function sendFrom($path)
- {
- if (PEAR::isError($error = $this->_put('SEND', "FROM:<$path>"))) {
- return $error;
- }
- if (PEAR::isError($error = $this->_parseResponse(250, $this->pipelining))) {
- return $error;
- }
-
- return true;
- }
-
- /**
- * Backwards-compatibility wrapper for sendFrom().
- *
- * @param string The reverse path to send.
- *
- * @return mixed Returns a PEAR_Error with an error message on any
- * kind of failure, or true on success.
- *
- * @access public
- * @since 1.0
- * @deprecated 1.2.6
- */
- function send_from($path)
- {
- return sendFrom($path);
- }
-
- /**
- * Send the SOML FROM: command.
- *
- * @param string The reverse path to send.
- *
- * @return mixed Returns a PEAR_Error with an error message on any
- * kind of failure, or true on success.
- * @access public
- * @since 1.2.6
- */
- function somlFrom($path)
- {
- if (PEAR::isError($error = $this->_put('SOML', "FROM:<$path>"))) {
- return $error;
- }
- if (PEAR::isError($error = $this->_parseResponse(250, $this->pipelining))) {
- return $error;
- }
-
- return true;
- }
-
- /**
- * Backwards-compatibility wrapper for somlFrom().
- *
- * @param string The reverse path to send.
- *
- * @return mixed Returns a PEAR_Error with an error message on any
- * kind of failure, or true on success.
- *
- * @access public
- * @since 1.0
- * @deprecated 1.2.6
- */
- function soml_from($path)
- {
- return somlFrom($path);
- }
-
- /**
- * Send the SAML FROM: command.
- *
- * @param string The reverse path to send.
- *
- * @return mixed Returns a PEAR_Error with an error message on any
- * kind of failure, or true on success.
- * @access public
- * @since 1.2.6
- */
- function samlFrom($path)
- {
- if (PEAR::isError($error = $this->_put('SAML', "FROM:<$path>"))) {
- return $error;
- }
- if (PEAR::isError($error = $this->_parseResponse(250, $this->pipelining))) {
- return $error;
- }
-
- return true;
- }
-
- /**
- * Backwards-compatibility wrapper for samlFrom().
- *
- * @param string The reverse path to send.
- *
- * @return mixed Returns a PEAR_Error with an error message on any
- * kind of failure, or true on success.
- *
- * @access public
- * @since 1.0
- * @deprecated 1.2.6
- */
- function saml_from($path)
- {
- return samlFrom($path);
- }
-
- /**
- * Send the RSET command.
- *
- * @return mixed Returns a PEAR_Error with an error message on any
- * kind of failure, or true on success.
- * @access public
- * @since 1.0
- */
- function rset()
- {
- if (PEAR::isError($error = $this->_put('RSET'))) {
- return $error;
- }
- if (PEAR::isError($error = $this->_parseResponse(250, $this->pipelining))) {
- return $error;
- }
-
- return true;
- }
-
- /**
- * Send the VRFY command.
- *
- * @param string The string to verify
- *
- * @return mixed Returns a PEAR_Error with an error message on any
- * kind of failure, or true on success.
- * @access public
- * @since 1.0
- */
- function vrfy($string)
- {
- /* Note: 251 is also a valid response code */
- if (PEAR::isError($error = $this->_put('VRFY', $string))) {
- return $error;
- }
- if (PEAR::isError($error = $this->_parseResponse(array(250, 252)))) {
- return $error;
- }
-
- return true;
- }
-
- /**
- * Send the NOOP command.
- *
- * @return mixed Returns a PEAR_Error with an error message on any
- * kind of failure, or true on success.
- * @access public
- * @since 1.0
- */
- function noop()
- {
- if (PEAR::isError($error = $this->_put('NOOP'))) {
- return $error;
- }
- if (PEAR::isError($error = $this->_parseResponse(250))) {
- return $error;
- }
-
- return true;
- }
-
- /**
- * Backwards-compatibility method. identifySender()'s functionality is
- * now handled internally.
- *
- * @return boolean This method always return true.
- *
- * @access public
- * @since 1.0
- */
- function identifySender()
- {
- return true;
- }
-
-}
+++ /dev/null
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Stig Bakken <ssb@php.net> |
-// | Chuck Hagenbuch <chuck@horde.org> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Socket.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
-
-require_once 'PEAR.php';
-
-define('NET_SOCKET_READ', 1);
-define('NET_SOCKET_WRITE', 2);
-define('NET_SOCKET_ERROR', 4);
-
-/**
- * Generalized Socket class.
- *
- * @version 1.1
- * @author Stig Bakken <ssb@php.net>
- * @author Chuck Hagenbuch <chuck@horde.org>
- */
-class Net_Socket extends PEAR {
-
- /**
- * Socket file pointer.
- * @var resource $fp
- */
- var $fp = null;
-
- /**
- * Whether the socket is blocking. Defaults to true.
- * @var boolean $blocking
- */
- var $blocking = true;
-
- /**
- * Whether the socket is persistent. Defaults to false.
- * @var boolean $persistent
- */
- var $persistent = false;
-
- /**
- * The IP address to connect to.
- * @var string $addr
- */
- var $addr = '';
-
- /**
- * The port number to connect to.
- * @var integer $port
- */
- var $port = 0;
-
- /**
- * Number of seconds to wait on socket connections before assuming
- * there's no more data. Defaults to no timeout.
- * @var integer $timeout
- */
- var $timeout = false;
-
- /**
- * Number of bytes to read at a time in readLine() and
- * readAll(). Defaults to 2048.
- * @var integer $lineLength
- */
- var $lineLength = 2048;
-
- /**
- * Connect to the specified port. If called when the socket is
- * already connected, it disconnects and connects again.
- *
- * @param string $addr IP address or host name.
- * @param integer $port TCP port number.
- * @param boolean $persistent (optional) Whether the connection is
- * persistent (kept open between requests
- * by the web server).
- * @param integer $timeout (optional) How long to wait for data.
- * @param array $options See options for stream_context_create.
- *
- * @access public
- *
- * @return boolean | PEAR_Error True on success or a PEAR_Error on failure.
- */
- function connect($addr, $port = 0, $persistent = null, $timeout = null, $options = null)
- {
- if (is_resource($this->fp)) {
- @fclose($this->fp);
- $this->fp = null;
- }
-
- if (!$addr) {
- return $this->raiseError('$addr cannot be empty');
- } elseif (strspn($addr, '.0123456789') == strlen($addr) ||
- strstr($addr, '/') !== false) {
- $this->addr = $addr;
- } else {
- $this->addr = @gethostbyname($addr);
- }
-
- $this->port = $port % 65536;
-
- if ($persistent !== null) {
- $this->persistent = $persistent;
- }
-
- if ($timeout !== null) {
- $this->timeout = $timeout;
- }
-
- $openfunc = $this->persistent ? 'pfsockopen' : 'fsockopen';
- $errno = 0;
- $errstr = '';
- if ($options && function_exists('stream_context_create')) {
- if ($this->timeout) {
- $timeout = $this->timeout;
- } else {
- $timeout = 0;
- }
- $context = stream_context_create($options);
- $fp = @$openfunc($this->addr, $this->port, $errno, $errstr, $timeout, $context);
- } else {
- if ($this->timeout) {
- $fp = @$openfunc($this->addr, $this->port, $errno, $errstr, $this->timeout);
- } else {
- $fp = @$openfunc($this->addr, $this->port, $errno, $errstr);
- }
- }
-
- if (!$fp) {
- return $this->raiseError($errstr, $errno);
- }
-
- $this->fp = $fp;
-
- return $this->setBlocking($this->blocking);
- }
-
- /**
- * Disconnects from the peer, closes the socket.
- *
- * @access public
- * @return mixed true on success or an error object otherwise
- */
- function disconnect()
- {
- if (!is_resource($this->fp)) {
- return $this->raiseError('not connected');
- }
-
- @fclose($this->fp);
- $this->fp = null;
- return true;
- }
-
- /**
- * Find out if the socket is in blocking mode.
- *
- * @access public
- * @return boolean The current blocking mode.
- */
- function isBlocking()
- {
- return $this->blocking;
- }
-
- /**
- * Sets whether the socket connection should be blocking or
- * not. A read call to a non-blocking socket will return immediately
- * if there is no data available, whereas it will block until there
- * is data for blocking sockets.
- *
- * @param boolean $mode True for blocking sockets, false for nonblocking.
- * @access public
- * @return mixed true on success or an error object otherwise
- */
- function setBlocking($mode)
- {
- if (!is_resource($this->fp)) {
- return $this->raiseError('not connected');
- }
-
- $this->blocking = $mode;
- socket_set_blocking($this->fp, $this->blocking);
- return true;
- }
-
- /**
- * Sets the timeout value on socket descriptor,
- * expressed in the sum of seconds and microseconds
- *
- * @param integer $seconds Seconds.
- * @param integer $microseconds Microseconds.
- * @access public
- * @return mixed true on success or an error object otherwise
- */
- function setTimeout($seconds, $microseconds)
- {
- if (!is_resource($this->fp)) {
- return $this->raiseError('not connected');
- }
-
- return socket_set_timeout($this->fp, $seconds, $microseconds);
- }
-
- /**
- * Sets the file buffering size on the stream.
- * See php's stream_set_write_buffer for more information.
- *
- * @param integer $size Write buffer size.
- * @access public
- * @return mixed on success or an PEAR_Error object otherwise
- */
- function setWriteBuffer($size)
- {
- if (!is_resource($this->fp)) {
- return $this->raiseError('not connected');
- }
-
- $returned = stream_set_write_buffer($this->fp, $code);
- if ($returned == 0) {
- return true;
- }
- return $this->raiseError('Cannot set write buffer.');
- }
-
- /**
- * Returns information about an existing socket resource.
- * Currently returns four entries in the result array:
- *
- * <p>
- * timed_out (bool) - The socket timed out waiting for data<br>
- * blocked (bool) - The socket was blocked<br>
- * eof (bool) - Indicates EOF event<br>
- * unread_bytes (int) - Number of bytes left in the socket buffer<br>
- * </p>
- *
- * @access public
- * @return mixed Array containing information about existing socket resource or an error object otherwise
- */
- function getStatus()
- {
- if (!is_resource($this->fp)) {
- return $this->raiseError('not connected');
- }
-
- return socket_get_status($this->fp);
- }
-
- /**
- * Get a specified line of data
- *
- * @access public
- * @return $size bytes of data from the socket, or a PEAR_Error if
- * not connected.
- */
- function gets($size)
- {
- if (!is_resource($this->fp)) {
- return $this->raiseError('not connected');
- }
-
- return @fgets($this->fp, $size);
- }
-
- /**
- * Read a specified amount of data. This is guaranteed to return,
- * and has the added benefit of getting everything in one fread()
- * chunk; if you know the size of the data you're getting
- * beforehand, this is definitely the way to go.
- *
- * @param integer $size The number of bytes to read from the socket.
- * @access public
- * @return $size bytes of data from the socket, or a PEAR_Error if
- * not connected.
- */
- function read($size)
- {
- if (!is_resource($this->fp)) {
- return $this->raiseError('not connected');
- }
-
- return @fread($this->fp, $size);
- }
-
- /**
- * Write a specified amount of data.
- *
- * @param string $data Data to write.
- * @param integer $blocksize Amount of data to write at once.
- * NULL means all at once.
- *
- * @access public
- * @return mixed true on success or an error object otherwise
- */
- function write($data, $blocksize = null)
- {
- if (!is_resource($this->fp)) {
- return $this->raiseError('not connected');
- }
-
- if (is_null($blocksize) && !OS_WINDOWS) {
- return fwrite($this->fp, $data);
- } else {
- if (is_null($blocksize)) {
- $blocksize = 1024;
- }
-
- $pos = 0;
- $size = strlen($data);
- while ($pos < $size) {
- $written = @fwrite($this->fp, substr($data, $pos, $blocksize));
- if ($written === false) {
- return false;
- }
- $pos += $written;
- }
-
- return $pos;
- }
- }
-
- /**
- * Write a line of data to the socket, followed by a trailing "\r\n".
- *
- * @access public
- * @return mixed fputs result, or an error
- */
- function writeLine($data)
- {
- if (!is_resource($this->fp)) {
- return $this->raiseError('not connected');
- }
-
- return fwrite($this->fp, $data . "\r\n");
- }
-
- /**
- * Tests for end-of-file on a socket descriptor.
- *
- * Also returns true if the socket is disconnected.
- *
- * @access public
- * @return bool
- */
- function eof()
- {
- return (!is_resource($this->fp) || feof($this->fp));
- }
-
- /**
- * Reads a byte of data
- *
- * @access public
- * @return 1 byte of data from the socket, or a PEAR_Error if
- * not connected.
- */
- function readByte()
- {
- if (!is_resource($this->fp)) {
- return $this->raiseError('not connected');
- }
-
- return ord(@fread($this->fp, 1));
- }
-
- /**
- * Reads a word of data
- *
- * @access public
- * @return 1 word of data from the socket, or a PEAR_Error if
- * not connected.
- */
- function readWord()
- {
- if (!is_resource($this->fp)) {
- return $this->raiseError('not connected');
- }
-
- $buf = @fread($this->fp, 2);
- return (ord($buf[0]) + (ord($buf[1]) << 8));
- }
-
- /**
- * Reads an int of data
- *
- * @access public
- * @return integer 1 int of data from the socket, or a PEAR_Error if
- * not connected.
- */
- function readInt()
- {
- if (!is_resource($this->fp)) {
- return $this->raiseError('not connected');
- }
-
- $buf = @fread($this->fp, 4);
- return (ord($buf[0]) + (ord($buf[1]) << 8) +
- (ord($buf[2]) << 16) + (ord($buf[3]) << 24));
- }
-
- /**
- * Reads a zero-terminated string of data
- *
- * @access public
- * @return string, or a PEAR_Error if
- * not connected.
- */
- function readString()
- {
- if (!is_resource($this->fp)) {
- return $this->raiseError('not connected');
- }
-
- $string = '';
- while (($char = @fread($this->fp, 1)) != "\x00") {
- $string .= $char;
- }
- return $string;
- }
-
- /**
- * Reads an IP Address and returns it in a dot formated string
- *
- * @access public
- * @return Dot formated string, or a PEAR_Error if
- * not connected.
- */
- function readIPAddress()
- {
- if (!is_resource($this->fp)) {
- return $this->raiseError('not connected');
- }
-
- $buf = @fread($this->fp, 4);
- return sprintf("%s.%s.%s.%s", ord($buf[0]), ord($buf[1]),
- ord($buf[2]), ord($buf[3]));
- }
-
- /**
- * Read until either the end of the socket or a newline, whichever
- * comes first. Strips the trailing newline from the returned data.
- *
- * @access public
- * @return All available data up to a newline, without that
- * newline, or until the end of the socket, or a PEAR_Error if
- * not connected.
- */
- function readLine()
- {
- if (!is_resource($this->fp)) {
- return $this->raiseError('not connected');
- }
-
- $line = '';
- $timeout = time() + $this->timeout;
- while (!feof($this->fp) && (!$this->timeout || time() < $timeout)) {
- $line .= @fgets($this->fp, $this->lineLength);
- if (substr($line, -1) == "\n") {
- return rtrim($line, "\r\n");
- }
- }
- return $line;
- }
-
- /**
- * Read until the socket closes, or until there is no more data in
- * the inner PHP buffer. If the inner buffer is empty, in blocking
- * mode we wait for at least 1 byte of data. Therefore, in
- * blocking mode, if there is no data at all to be read, this
- * function will never exit (unless the socket is closed on the
- * remote end).
- *
- * @access public
- *
- * @return string All data until the socket closes, or a PEAR_Error if
- * not connected.
- */
- function readAll()
- {
- if (!is_resource($this->fp)) {
- return $this->raiseError('not connected');
- }
-
- $data = '';
- while (!feof($this->fp)) {
- $data .= @fread($this->fp, $this->lineLength);
- }
- return $data;
- }
-
- /**
- * Runs the equivalent of the select() system call on the socket
- * with a timeout specified by tv_sec and tv_usec.
- *
- * @param integer $state Which of read/write/error to check for.
- * @param integer $tv_sec Number of seconds for timeout.
- * @param integer $tv_usec Number of microseconds for timeout.
- *
- * @access public
- * @return False if select fails, integer describing which of read/write/error
- * are ready, or PEAR_Error if not connected.
- */
- function select($state, $tv_sec, $tv_usec = 0)
- {
- if (!is_resource($this->fp)) {
- return $this->raiseError('not connected');
- }
-
- $read = null;
- $write = null;
- $except = null;
- if ($state & NET_SOCKET_READ) {
- $read[] = $this->fp;
- }
- if ($state & NET_SOCKET_WRITE) {
- $write[] = $this->fp;
- }
- if ($state & NET_SOCKET_ERROR) {
- $except[] = $this->fp;
- }
- if (false === ($sr = stream_select($read, $write, $except, $tv_sec, $tv_usec))) {
- return false;
- }
-
- $result = 0;
- if (count($read)) {
- $result |= NET_SOCKET_READ;
- }
- if (count($write)) {
- $result |= NET_SOCKET_WRITE;
- }
- if (count($except)) {
- $result |= NET_SOCKET_ERROR;
- }
- return $result;
- }
-
- /**
- * Turns encryption on/off on a connected socket.
- *
- * @param bool $enabled Set this parameter to true to enable encryption
- * and false to disable encryption.
- * @param integer $type Type of encryption. See
- * http://se.php.net/manual/en/function.stream-socket-enable-crypto.php for values.
- *
- * @access public
- * @return false on error, true on success and 0 if there isn't enough data and the
- * user should try again (non-blocking sockets only). A PEAR_Error object
- * is returned if the socket is not connected
- */
- function enableCrypto($enabled, $type)
- {
- if (version_compare(phpversion(), "5.1.0", ">=")) {
- if (!is_resource($this->fp)) {
- return $this->raiseError('not connected');
- }
- return @stream_socket_enable_crypto($this->fp, $enabled, $type);
- } else {
- return $this->raiseError('Net_Socket::enableCrypto() requires php version >= 5.1.0');
- }
- }
-
-}
+++ /dev/null
-<?php
-// +-----------------------------------------------------------------------+
-// | Copyright (c) 2002-2004, Richard Heyes |
-// | All rights reserved. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | o Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | o Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution.|
-// | o The names of the authors may not be used to endorse or promote |
-// | products derived from this software without specific prior written |
-// | permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
-// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT |
-// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
-// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
-// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
-// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
-// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
-// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
-// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
-// | |
-// +-----------------------------------------------------------------------+
-// | Author: Richard Heyes <richard at php net> |
-// +-----------------------------------------------------------------------+
-//
-// $Id: URL2.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
-//
-// Net_URL2 Class (PHP5 Only)
-
-class Net_URL2
-{
- /**
- * Options
- *
- * This is the options available for the neturl
- * options.
- *
- * @var array $options The options of Net_URL2
- */
- public static $options = array(
- 'encode_query_keys' => false,
- );
-
- /**
- * Full url
- * @var string
- */
- public $url;
-
- /**
- * Protocol
- * @var string
- */
- public $protocol;
-
- /**
- * Username
- * @var string
- */
- public $user;
-
- /**
- * Password
- * @var string
- */
- public $pass;
-
- /**
- * Host
- * @var string
- */
- public $host;
-
- /**
- * Port
- * @var integer
- */
- public $port;
-
- /**
- * Path
- * @var string
- */
- public $path;
-
- /**
- * Query string
- * @var array
- */
- public $querystring;
-
- /**
- * Anchor
- * @var string
- */
- public $anchor;
-
- /**
- * Whether to use [] in querystrings
- * @var boolean
- */
- public $useBrackets;
-
- /**
- * Constructor
- *
- * Parses the given url and stores the various parts
- * Defaults are used in certain cases
- *
- * @param string $url Optional URL
- * @param bool $useBrackets Whether to use square brackets when
- * multiple querystrings with the same name
- * exist
- */
- public function __construct($url = null, $useBrackets = true)
- {
- $this->useBrackets = $useBrackets;
- $this->url = $url;
- $this->user = '';
- $this->pass = '';
- $this->host = '';
- $this->port = 80;
- $this->path = '';
- $this->querystring = array();
- $this->anchor = '';
-
- // Only use defaults if not an absolute URL given
- if (!preg_match('/^[a-z0-9]+:\/\//i', $url)) {
-
- $this->protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? 'https' : 'http');
-
- /**
- * Figure out host/port
- */
- if (!empty($_SERVER['HTTP_HOST']) AND preg_match('/^(.*)(:([0-9]+))?$/U', $_SERVER['HTTP_HOST'], $matches)) {
- $host = $matches[1];
- if (!empty($matches[3])) {
- $port = $matches[3];
- } else {
- $port = $this->getStandardPort($this->protocol);
- }
- }
-
- $this->user = '';
- $this->pass = '';
- $this->host = !empty($host) ? $host : (isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : 'localhost');
- $this->port = !empty($port) ? $port : (isset($_SERVER['SERVER_PORT']) ? $_SERVER['SERVER_PORT'] : $this->getStandardPort($this->protocol));
- $this->path = !empty($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : '/';
- $this->querystring = isset($_SERVER['QUERY_STRING']) ? $this->_parseRawQuerystring($_SERVER['QUERY_STRING']) : null;
- $this->anchor = '';
- }
-
- // Parse the url and store the various parts
- if (!empty($url)) {
- $urlinfo = parse_url($url);
-
- // Default querystring
- $this->querystring = array();
-
- foreach ($urlinfo as $key => $value) {
- switch ($key) {
- case 'scheme':
- $this->protocol = $value;
- $this->port = $this->getStandardPort($value);
- break;
-
- case 'user':
- case 'pass':
- case 'host':
- case 'port':
- $this->$key = $value;
- break;
-
- case 'path':
- if ($value{0} == '/') {
- $this->path = $value;
- } else {
- $path = dirname($this->path) == DIRECTORY_SEPARATOR ? '' : dirname($this->path);
- $this->path = sprintf('%s/%s', $path, $value);
- }
- break;
-
- case 'query':
- $this->querystring = $this->_parseRawQueryString($value);
- break;
-
- case 'fragment':
- $this->anchor = $value;
- break;
- }
- }
- }
- }
-
- /**
- * Returns full url
- *
- * @return string Full url
- */
- public function getURL()
- {
- $querystring = $this->getQueryString();
-
- $this->url = $this->protocol . '://'
- . $this->user . (!empty($this->pass) ? ':' : '')
- . $this->pass . (!empty($this->user) ? '@' : '')
- . $this->host . ($this->port == $this->getStandardPort($this->protocol) ? '' : ':' . $this->port)
- . $this->path
- . (!empty($querystring) ? '?' . $querystring : '')
- . (!empty($this->anchor) ? '#' . $this->anchor : '');
-
- return $this->url;
- }
-
- /**
- * Adds a querystring item
- *
- * @param string $name Name of item
- * @param string $value Value of item
- * @param bool $preencoded Whether value is rawurlencoded or not, default = not
- */
- public function addQueryString($name, $value, $preencoded = false)
- {
- if ($this->getOption('encode_query_keys')) {
- $name = rawurlencode($name);
- }
-
-
- if ($preencoded) {
- $this->querystring[$name] = $value;
- } else {
- $this->querystring[$name] = is_array($value) ? array_map('rawurlencode', $value): rawurlencode($value);
- }
- }
-
- /**
- * Removes a querystring item
- *
- * @param string $name Name of item
- */
- public function removeQueryString($name)
- {
- if ($this->getOption('encode_query_keys')) {
- $name = rawurlencode($name);
- }
-
- if (isset($this->querystring[$name])) {
- unset($this->querystring[$name]);
- }
- }
-
- /**
- * Sets the querystring to literally what you supply
- *
- * @param string $querystring The querystring data. Should be of the format foo=bar&x=y etc
- */
- public function addRawQueryString($querystring)
- {
- $this->querystring = $this->_parseRawQueryString($querystring);
- }
-
- /**
- * Returns flat querystring
- *
- * @return string Querystring
- */
- public function getQueryString()
- {
- if (!empty($this->querystring)) {
- foreach ($this->querystring as $name => $value) {
-
- // Encode var name
- $name = rawurlencode($name);
-
- if (is_array($value)) {
- foreach ($value as $k => $v) {
- $querystring[] = $this->useBrackets ? sprintf('%s[%s]=%s', $name, $k, $v) : ($name . '=' . $v);
- }
- } elseif (!is_null($value)) {
- $querystring[] = $name . '=' . $value;
- } else {
- $querystring[] = $name;
- }
- }
- $querystring = implode(ini_get('arg_separator.output'), $querystring);
- } else {
- $querystring = '';
- }
-
- return $querystring;
- }
-
- /**
- * Forces the URL to a particular protocol
- *
- * @param string $protocol Protocol to force the URL to
- * @param integer $port Optional port (standard port is used by default)
- */
- public function setProtocol($protocol, $port = null)
- {
- $this->protocol = $protocol;
- $this->port = is_null($port) ? $this->getStandardPort($protocol) : $port;
- }
-
- /**
- * Resolves //, ../ and ./ from a path and returns
- * the result. Eg:
- *
- * /foo/bar/../boo.php => /foo/boo.php
- * /foo/bar/../../boo.php => /boo.php
- * /foo/bar/.././/boo.php => /foo/boo.php
- *
- * @param string $url URL path to resolve
- * @return string The result
- */
- public static function resolvePath($path)
- {
- $path = explode('/', str_replace('//', '/', $path));
-
- for ($i=0; $i<count($path); $i++) {
- if ($path[$i] == '.') {
- unset($path[$i]);
- $path = array_values($path);
- $i--;
-
- } elseif ($path[$i] == '..' AND ($i > 1 OR ($i == 1 AND $path[0] != '') ) ) {
- unset($path[$i]);
- unset($path[$i-1]);
- $path = array_values($path);
- $i -= 2;
-
- } elseif ($path[$i] == '..' AND $i == 1 AND $path[0] == '') {
- unset($path[$i]);
- $path = array_values($path);
- $i--;
-
- } else {
- continue;
- }
- }
-
- return implode('/', $path);
- }
-
- /**
- * Returns the standard port number for a protocol
- *
- * @param string $scheme The protocol to lookup
- * @return integer Port number or NULL if no scheme matches
- *
- * @author Philippe Jausions <Philippe.Jausions@11abacus.com>
- */
- public static function getStandardPort($scheme)
- {
- switch (strtolower($scheme)) {
- case 'http': return 80;
- case 'https': return 443;
- case 'ftp': return 21;
- case 'imap': return 143;
- case 'imaps': return 993;
- case 'pop3': return 110;
- case 'pop3s': return 995;
- default: return null;
- }
- }
-
- /**
- * Parses raw querystring and returns an array of it
- *
- * @param string $querystring The querystring to parse
- * @return array An array of the querystring data
- */
- private function _parseRawQuerystring($querystring)
- {
- $parts = preg_split('/[' . preg_quote(ini_get('arg_separator.input'), '/') . ']/', $querystring, -1, PREG_SPLIT_NO_EMPTY);
- $return = array();
-
- foreach ($parts as $part) {
- if (strpos($part, '=') !== false) {
-
- $value = substr($part, strpos($part, '=') + 1);
- $key = substr($part, 0, strpos($part, '='));
- } else {
- $value = null;
- $key = $part;
- }
-
- if (!$this->getOption('encode_query_keys')) {
- $key = urldecode($key);
- }
-
- if (preg_match('#^(.*)\[([0-9a-z_-]*)\]#i', $key, $matches)) {
- $key = $matches[1];
- $idx = $matches[2];
-
- // Ensure is an array
- if (empty($return[$key]) || !is_array($return[$key])) {
- $return[$key] = array();
- }
-
- // Add data
- if ($idx === '') {
- $return[$key][] = $value;
-
- } else {
- $return[$key][$idx] = $value;
- }
-
- } elseif (!$this->useBrackets AND !empty($return[$key])) {
- $return[$key] = (array)$return[$key];
- $return[$key][] = $value;
- } else {
- $return[$key] = $value;
- }
- }
-
- return $return;
- }
-
- /**
- * Set a private option
- *
- * This function sets a private option
- *
- * @param string $optionName The option name
- * @param string $value The value of this option
- */
- public static function setOption($optionName, $value)
- {
- self::$options[$optionName] = $value;
- }
-
- /**
- * Get an option
- *
- * This function will get an option
- * from the options private variable.
- *
- * @see $this->options
- * @return mixed Bool false if the key doesn't exist and the value
- * of the option if it exists.
- */
- public function getOption($optionName)
- {
- if (!isset(self::$options[$optionName])) {
- return false;
- }
-
- return self::$options[$optionName];
- }
-}
-?>
+++ /dev/null
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PEAR, the PHP Extension and Application Repository |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available through the world-wide-web at the following url: |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Sterling Hughes <sterling@php.net> |
-// | Stig Bakken <ssb@php.net> |
-// | Tomas V.V.Cox <cox@idecnet.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: PEAR.php,v 1.1.1.1 2008/04/28 15:20:46 jamie Exp $
-//
-
-define('PEAR_ERROR_RETURN', 1);
-define('PEAR_ERROR_PRINT', 2);
-define('PEAR_ERROR_TRIGGER', 4);
-define('PEAR_ERROR_DIE', 8);
-define('PEAR_ERROR_CALLBACK', 16);
-/**
- * WARNING: obsolete
- * @deprecated
- */
-define('PEAR_ERROR_EXCEPTION', 32);
-define('PEAR_ZE2', (function_exists('version_compare') &&
- version_compare(zend_version(), "2-dev", "ge")));
-
-if (substr(PHP_OS, 0, 3) == 'WIN') {
- define('OS_WINDOWS', true);
- define('OS_UNIX', false);
- define('PEAR_OS', 'Windows');
-} else {
- define('OS_WINDOWS', false);
- define('OS_UNIX', true);
- define('PEAR_OS', 'Unix'); // blatant assumption
-}
-
-// instant backwards compatibility
-if (!defined('PATH_SEPARATOR')) {
- if (OS_WINDOWS) {
- define('PATH_SEPARATOR', ';');
- } else {
- define('PATH_SEPARATOR', ':');
- }
-}
-
-$GLOBALS['_PEAR_default_error_mode'] = PEAR_ERROR_RETURN;
-$GLOBALS['_PEAR_default_error_options'] = E_USER_NOTICE;
-$GLOBALS['_PEAR_destructor_object_list'] = array();
-$GLOBALS['_PEAR_shutdown_funcs'] = array();
-$GLOBALS['_PEAR_error_handler_stack'] = array();
-
-ini_set('track_errors', true);
-
-/**
- * Base class for other PEAR classes. Provides rudimentary
- * emulation of destructors.
- *
- * If you want a destructor in your class, inherit PEAR and make a
- * destructor method called _yourclassname (same name as the
- * constructor, but with a "_" prefix). Also, in your constructor you
- * have to call the PEAR constructor: $this->PEAR();.
- * The destructor method will be called without parameters. Note that
- * at in some SAPI implementations (such as Apache), any output during
- * the request shutdown (in which destructors are called) seems to be
- * discarded. If you need to get any debug information from your
- * destructor, use error_log(), syslog() or something similar.
- *
- * IMPORTANT! To use the emulated destructors you need to create the
- * objects by reference: $obj =& new PEAR_child;
- *
- * @since PHP 4.0.2
- * @author Stig Bakken <ssb@php.net>
- * @see http://pear.php.net/manual/
- */
-class PEAR
-{
- // {{{ properties
-
- /**
- * Whether to enable internal debug messages.
- *
- * @var bool
- * @access private
- */
- var $_debug = false;
-
- /**
- * Default error mode for this object.
- *
- * @var int
- * @access private
- */
- var $_default_error_mode = null;
-
- /**
- * Default error options used for this object when error mode
- * is PEAR_ERROR_TRIGGER.
- *
- * @var int
- * @access private
- */
- var $_default_error_options = null;
-
- /**
- * Default error handler (callback) for this object, if error mode is
- * PEAR_ERROR_CALLBACK.
- *
- * @var string
- * @access private
- */
- var $_default_error_handler = '';
-
- /**
- * Which class to use for error objects.
- *
- * @var string
- * @access private
- */
- var $_error_class = 'PEAR_Error';
-
- /**
- * An array of expected errors.
- *
- * @var array
- * @access private
- */
- var $_expected_errors = array();
-
- // }}}
-
- // {{{ constructor
-
- /**
- * Constructor. Registers this object in
- * $_PEAR_destructor_object_list for destructor emulation if a
- * destructor object exists.
- *
- * @param string $error_class (optional) which class to use for
- * error objects, defaults to PEAR_Error.
- * @access public
- * @return void
- */
- function PEAR($error_class = null)
- {
- $classname = get_class($this);
- if ($this->_debug) {
- print "PEAR constructor called, class=$classname\n";
- }
- if ($error_class !== null) {
- $this->_error_class = $error_class;
- }
- while ($classname) {
- $destructor = "_$classname";
- if (method_exists($this, $destructor)) {
- global $_PEAR_destructor_object_list;
- $_PEAR_destructor_object_list[] = &$this;
- break;
- } else {
- $classname = get_parent_class($classname);
- }
- }
- }
-
- // }}}
- // {{{ destructor
-
- /**
- * Destructor (the emulated type of...). Does nothing right now,
- * but is included for forward compatibility, so subclass
- * destructors should always call it.
- *
- * See the note in the class desciption about output from
- * destructors.
- *
- * @access public
- * @return void
- */
- function _PEAR() {
- if ($this->_debug) {
- printf("PEAR destructor called, class=%s\n", get_class($this));
- }
- }
-
- // }}}
- // {{{ getStaticProperty()
-
- /**
- * If you have a class that's mostly/entirely static, and you need static
- * properties, you can use this method to simulate them. Eg. in your method(s)
- * do this: $myVar = &PEAR::getStaticProperty('myclass', 'myVar');
- * You MUST use a reference, or they will not persist!
- *
- * @access public
- * @param string $class The calling classname, to prevent clashes
- * @param string $var The variable to retrieve.
- * @return mixed A reference to the variable. If not set it will be
- * auto initialised to NULL.
- */
- function &getStaticProperty($class, $var)
- {
- static $properties;
- return $properties[$class][$var];
- }
-
- // }}}
- // {{{ registerShutdownFunc()
-
- /**
- * Use this function to register a shutdown method for static
- * classes.
- *
- * @access public
- * @param mixed $func The function name (or array of class/method) to call
- * @param mixed $args The arguments to pass to the function
- * @return void
- */
- function registerShutdownFunc($func, $args = array())
- {
- $GLOBALS['_PEAR_shutdown_funcs'][] = array($func, $args);
- }
-
- // }}}
- // {{{ isError()
-
- /**
- * Tell whether a value is a PEAR error.
- *
- * @param mixed $data the value to test
- * @param int $code if $data is an error object, return true
- * only if $code is a string and
- * $obj->getMessage() == $code or
- * $code is an integer and $obj->getCode() == $code
- * @access public
- * @return bool true if parameter is an error
- */
- function isError($data, $code = null)
- {
- if (is_a($data, 'PEAR_Error')) {
- if (is_null($code)) {
- return true;
- } elseif (is_string($code)) {
- return $data->getMessage() == $code;
- } else {
- return $data->getCode() == $code;
- }
- }
- return false;
- }
-
- // }}}
- // {{{ setErrorHandling()
-
- /**
- * Sets how errors generated by this object should be handled.
- * Can be invoked both in objects and statically. If called
- * statically, setErrorHandling sets the default behaviour for all
- * PEAR objects. If called in an object, setErrorHandling sets
- * the default behaviour for that object.
- *
- * @param int $mode
- * One of PEAR_ERROR_RETURN, PEAR_ERROR_PRINT,
- * PEAR_ERROR_TRIGGER, PEAR_ERROR_DIE,
- * PEAR_ERROR_CALLBACK or PEAR_ERROR_EXCEPTION.
- *
- * @param mixed $options
- * When $mode is PEAR_ERROR_TRIGGER, this is the error level (one
- * of E_USER_NOTICE, E_USER_WARNING or E_USER_ERROR).
- *
- * When $mode is PEAR_ERROR_CALLBACK, this parameter is expected
- * to be the callback function or method. A callback
- * function is a string with the name of the function, a
- * callback method is an array of two elements: the element
- * at index 0 is the object, and the element at index 1 is
- * the name of the method to call in the object.
- *
- * When $mode is PEAR_ERROR_PRINT or PEAR_ERROR_DIE, this is
- * a printf format string used when printing the error
- * message.
- *
- * @access public
- * @return void
- * @see PEAR_ERROR_RETURN
- * @see PEAR_ERROR_PRINT
- * @see PEAR_ERROR_TRIGGER
- * @see PEAR_ERROR_DIE
- * @see PEAR_ERROR_CALLBACK
- * @see PEAR_ERROR_EXCEPTION
- *
- * @since PHP 4.0.5
- */
-
- function setErrorHandling($mode = null, $options = null)
- {
- if (isset($this) && is_a($this, 'PEAR')) {
- $setmode = &$this->_default_error_mode;
- $setoptions = &$this->_default_error_options;
- } else {
- $setmode = &$GLOBALS['_PEAR_default_error_mode'];
- $setoptions = &$GLOBALS['_PEAR_default_error_options'];
- }
-
- switch ($mode) {
- case PEAR_ERROR_EXCEPTION:
- case PEAR_ERROR_RETURN:
- case PEAR_ERROR_PRINT:
- case PEAR_ERROR_TRIGGER:
- case PEAR_ERROR_DIE:
- case null:
- $setmode = $mode;
- $setoptions = $options;
- break;
-
- case PEAR_ERROR_CALLBACK:
- $setmode = $mode;
- // class/object method callback
- if (is_callable($options)) {
- $setoptions = $options;
- } else {
- trigger_error("invalid error callback", E_USER_WARNING);
- }
- break;
-
- default:
- trigger_error("invalid error mode", E_USER_WARNING);
- break;
- }
- }
-
- // }}}
- // {{{ expectError()
-
- /**
- * This method is used to tell which errors you expect to get.
- * Expected errors are always returned with error mode
- * PEAR_ERROR_RETURN. Expected error codes are stored in a stack,
- * and this method pushes a new element onto it. The list of
- * expected errors are in effect until they are popped off the
- * stack with the popExpect() method.
- *
- * Note that this method can not be called statically
- *
- * @param mixed $code a single error code or an array of error codes to expect
- *
- * @return int the new depth of the "expected errors" stack
- * @access public
- */
- function expectError($code = '*')
- {
- if (is_array($code)) {
- array_push($this->_expected_errors, $code);
- } else {
- array_push($this->_expected_errors, array($code));
- }
- return sizeof($this->_expected_errors);
- }
-
- // }}}
- // {{{ popExpect()
-
- /**
- * This method pops one element off the expected error codes
- * stack.
- *
- * @return array the list of error codes that were popped
- */
- function popExpect()
- {
- return array_pop($this->_expected_errors);
- }
-
- // }}}
- // {{{ _checkDelExpect()
-
- /**
- * This method checks unsets an error code if available
- *
- * @param mixed error code
- * @return bool true if the error code was unset, false otherwise
- * @access private
- * @since PHP 4.3.0
- */
- function _checkDelExpect($error_code)
- {
- $deleted = false;
-
- foreach ($this->_expected_errors AS $key => $error_array) {
- if (in_array($error_code, $error_array)) {
- unset($this->_expected_errors[$key][array_search($error_code, $error_array)]);
- $deleted = true;
- }
-
- // clean up empty arrays
- if (0 == count($this->_expected_errors[$key])) {
- unset($this->_expected_errors[$key]);
- }
- }
- return $deleted;
- }
-
- // }}}
- // {{{ delExpect()
-
- /**
- * This method deletes all occurences of the specified element from
- * the expected error codes stack.
- *
- * @param mixed $error_code error code that should be deleted
- * @return mixed list of error codes that were deleted or error
- * @access public
- * @since PHP 4.3.0
- */
- function delExpect($error_code)
- {
- $deleted = false;
-
- if ((is_array($error_code) && (0 != count($error_code)))) {
- // $error_code is a non-empty array here;
- // we walk through it trying to unset all
- // values
- foreach($error_code as $key => $error) {
- if ($this->_checkDelExpect($error)) {
- $deleted = true;
- } else {
- $deleted = false;
- }
- }
- return $deleted ? true : PEAR::raiseError("The expected error you submitted does not exist"); // IMPROVE ME
- } elseif (!empty($error_code)) {
- // $error_code comes alone, trying to unset it
- if ($this->_checkDelExpect($error_code)) {
- return true;
- } else {
- return PEAR::raiseError("The expected error you submitted does not exist"); // IMPROVE ME
- }
- } else {
- // $error_code is empty
- return PEAR::raiseError("The expected error you submitted is empty"); // IMPROVE ME
- }
- }
-
- // }}}
- // {{{ raiseError()
-
- /**
- * This method is a wrapper that returns an instance of the
- * configured error class with this object's default error
- * handling applied. If the $mode and $options parameters are not
- * specified, the object's defaults are used.
- *
- * @param mixed $message a text error message or a PEAR error object
- *
- * @param int $code a numeric error code (it is up to your class
- * to define these if you want to use codes)
- *
- * @param int $mode One of PEAR_ERROR_RETURN, PEAR_ERROR_PRINT,
- * PEAR_ERROR_TRIGGER, PEAR_ERROR_DIE,
- * PEAR_ERROR_CALLBACK, PEAR_ERROR_EXCEPTION.
- *
- * @param mixed $options If $mode is PEAR_ERROR_TRIGGER, this parameter
- * specifies the PHP-internal error level (one of
- * E_USER_NOTICE, E_USER_WARNING or E_USER_ERROR).
- * If $mode is PEAR_ERROR_CALLBACK, this
- * parameter specifies the callback function or
- * method. In other error modes this parameter
- * is ignored.
- *
- * @param string $userinfo If you need to pass along for example debug
- * information, this parameter is meant for that.
- *
- * @param string $error_class The returned error object will be
- * instantiated from this class, if specified.
- *
- * @param bool $skipmsg If true, raiseError will only pass error codes,
- * the error message parameter will be dropped.
- *
- * @access public
- * @return object a PEAR error object
- * @see PEAR::setErrorHandling
- * @since PHP 4.0.5
- */
- function raiseError($message = null,
- $code = null,
- $mode = null,
- $options = null,
- $userinfo = null,
- $error_class = null,
- $skipmsg = false)
- {
- // The error is yet a PEAR error object
- if (is_object($message)) {
- $code = $message->getCode();
- $userinfo = $message->getUserInfo();
- $error_class = $message->getType();
- $message->error_message_prefix = '';
- $message = $message->getMessage();
- }
-
- if (isset($this) && isset($this->_expected_errors) && sizeof($this->_expected_errors) > 0 && sizeof($exp = end($this->_expected_errors))) {
- if ($exp[0] == "*" ||
- (is_int(reset($exp)) && in_array($code, $exp)) ||
- (is_string(reset($exp)) && in_array($message, $exp))) {
- $mode = PEAR_ERROR_RETURN;
- }
- }
- // No mode given, try global ones
- if ($mode === null) {
- // Class error handler
- if (isset($this) && isset($this->_default_error_mode)) {
- $mode = $this->_default_error_mode;
- $options = $this->_default_error_options;
- // Global error handler
- } elseif (isset($GLOBALS['_PEAR_default_error_mode'])) {
- $mode = $GLOBALS['_PEAR_default_error_mode'];
- $options = $GLOBALS['_PEAR_default_error_options'];
- }
- }
-
- if ($error_class !== null) {
- $ec = $error_class;
- } elseif (isset($this) && isset($this->_error_class)) {
- $ec = $this->_error_class;
- } else {
- $ec = 'PEAR_Error';
- }
- if ($skipmsg) {
- return new $ec($code, $mode, $options, $userinfo);
- } else {
- return new $ec($message, $code, $mode, $options, $userinfo);
- }
- }
-
- // }}}
- // {{{ throwError()
-
- /**
- * Simpler form of raiseError with fewer options. In most cases
- * message, code and userinfo are enough.
- *
- * @param string $message
- *
- */
- function throwError($message = null,
- $code = null,
- $userinfo = null)
- {
- if (isset($this) && is_a($this, 'PEAR')) {
- return $this->raiseError($message, $code, null, null, $userinfo);
- } else {
- return PEAR::raiseError($message, $code, null, null, $userinfo);
- }
- }
-
- // }}}
- // {{{ pushErrorHandling()
-
- /**
- * Push a new error handler on top of the error handler options stack. With this
- * you can easily override the actual error handler for some code and restore
- * it later with popErrorHandling.
- *
- * @param mixed $mode (same as setErrorHandling)
- * @param mixed $options (same as setErrorHandling)
- *
- * @return bool Always true
- *
- * @see PEAR::setErrorHandling
- */
- function pushErrorHandling($mode, $options = null)
- {
- $stack = &$GLOBALS['_PEAR_error_handler_stack'];
- if (isset($this) && is_a($this, 'PEAR')) {
- $def_mode = &$this->_default_error_mode;
- $def_options = &$this->_default_error_options;
- } else {
- $def_mode = &$GLOBALS['_PEAR_default_error_mode'];
- $def_options = &$GLOBALS['_PEAR_default_error_options'];
- }
- $stack[] = array($def_mode, $def_options);
-
- if (isset($this) && is_a($this, 'PEAR')) {
- $this->setErrorHandling($mode, $options);
- } else {
- PEAR::setErrorHandling($mode, $options);
- }
- $stack[] = array($mode, $options);
- return true;
- }
-
- // }}}
- // {{{ popErrorHandling()
-
- /**
- * Pop the last error handler used
- *
- * @return bool Always true
- *
- * @see PEAR::pushErrorHandling
- */
- function popErrorHandling()
- {
- $stack = &$GLOBALS['_PEAR_error_handler_stack'];
- array_pop($stack);
- list($mode, $options) = $stack[sizeof($stack) - 1];
- array_pop($stack);
- if (isset($this) && is_a($this, 'PEAR')) {
- $this->setErrorHandling($mode, $options);
- } else {
- PEAR::setErrorHandling($mode, $options);
- }
- return true;
- }
-
- // }}}
- // {{{ loadExtension()
-
- /**
- * OS independant PHP extension load. Remember to take care
- * on the correct extension name for case sensitive OSes.
- *
- * @param string $ext The extension name
- * @return bool Success or not on the dl() call
- */
- function loadExtension($ext)
- {
- if (!extension_loaded($ext)) {
- // if either returns true dl() will produce a FATAL error, stop that
- if ((ini_get('enable_dl') != 1) || (ini_get('safe_mode') == 1)) {
- return false;
- }
- if (OS_WINDOWS) {
- $suffix = '.dll';
- } elseif (PHP_OS == 'HP-UX') {
- $suffix = '.sl';
- } elseif (PHP_OS == 'AIX') {
- $suffix = '.a';
- } elseif (PHP_OS == 'OSX') {
- $suffix = '.bundle';
- } else {
- $suffix = '.so';
- }
- return @dl('php_'.$ext.$suffix) || @dl($ext.$suffix);
- }
- return true;
- }
-
- // }}}
-}
-
-// {{{ _PEAR_call_destructors()
-
-function _PEAR_call_destructors()
-{
- global $_PEAR_destructor_object_list;
- if (is_array($_PEAR_destructor_object_list) &&
- sizeof($_PEAR_destructor_object_list))
- {
- reset($_PEAR_destructor_object_list);
- while (list($k, $objref) = each($_PEAR_destructor_object_list)) {
- $classname = get_class($objref);
- while ($classname) {
- $destructor = "_$classname";
- if (method_exists($objref, $destructor)) {
- $objref->$destructor();
- break;
- } else {
- $classname = get_parent_class($classname);
- }
- }
- }
- // Empty the object list to ensure that destructors are
- // not called more than once.
- $_PEAR_destructor_object_list = array();
- }
-
- // Now call the shutdown functions
- if (is_array($GLOBALS['_PEAR_shutdown_funcs']) AND !empty($GLOBALS['_PEAR_shutdown_funcs'])) {
- foreach ($GLOBALS['_PEAR_shutdown_funcs'] as $value) {
- call_user_func_array($value[0], $value[1]);
- }
- }
-}
-
-// }}}
-
-class PEAR_Error
-{
- // {{{ properties
-
- var $error_message_prefix = '';
- var $mode = PEAR_ERROR_RETURN;
- var $level = E_USER_NOTICE;
- var $code = -1;
- var $message = '';
- var $userinfo = '';
- var $backtrace = null;
-
- // }}}
- // {{{ constructor
-
- /**
- * PEAR_Error constructor
- *
- * @param string $message message
- *
- * @param int $code (optional) error code
- *
- * @param int $mode (optional) error mode, one of: PEAR_ERROR_RETURN,
- * PEAR_ERROR_PRINT, PEAR_ERROR_DIE, PEAR_ERROR_TRIGGER,
- * PEAR_ERROR_CALLBACK or PEAR_ERROR_EXCEPTION
- *
- * @param mixed $options (optional) error level, _OR_ in the case of
- * PEAR_ERROR_CALLBACK, the callback function or object/method
- * tuple.
- *
- * @param string $userinfo (optional) additional user/debug info
- *
- * @access public
- *
- */
- function PEAR_Error($message = 'unknown error', $code = null,
- $mode = null, $options = null, $userinfo = null)
- {
- if ($mode === null) {
- $mode = PEAR_ERROR_RETURN;
- }
- $this->message = $message;
- $this->code = $code;
- $this->mode = $mode;
- $this->userinfo = $userinfo;
- if (function_exists("debug_backtrace")) {
- $this->backtrace = debug_backtrace();
- }
- if ($mode & PEAR_ERROR_CALLBACK) {
- $this->level = E_USER_NOTICE;
- $this->callback = $options;
- } else {
- if ($options === null) {
- $options = E_USER_NOTICE;
- }
- $this->level = $options;
- $this->callback = null;
- }
- if ($this->mode & PEAR_ERROR_PRINT) {
- if (is_null($options) || is_int($options)) {
- $format = "%s";
- } else {
- $format = $options;
- }
- printf($format, $this->getMessage());
- }
- if ($this->mode & PEAR_ERROR_TRIGGER) {
- trigger_error($this->getMessage(), $this->level);
- }
- if ($this->mode & PEAR_ERROR_DIE) {
- $msg = $this->getMessage();
- if (is_null($options) || is_int($options)) {
- $format = "%s";
- if (substr($msg, -1) != "\n") {
- $msg .= "\n";
- }
- } else {
- $format = $options;
- }
- die(sprintf($format, $msg));
- }
- if ($this->mode & PEAR_ERROR_CALLBACK) {
- if (is_callable($this->callback)) {
- call_user_func($this->callback, $this);
- }
- }
- if ($this->mode & PEAR_ERROR_EXCEPTION) {
- trigger_error("PEAR_ERROR_EXCEPTION is obsolete, use class PEAR_ErrorStack for exceptions", E_USER_WARNING);
- eval('$e = new Exception($this->message, $this->code);$e->PEAR_Error = $this;throw($e);');
- }
- }
-
- // }}}
- // {{{ getMode()
-
- /**
- * Get the error mode from an error object.
- *
- * @return int error mode
- * @access public
- */
- function getMode() {
- return $this->mode;
- }
-
- // }}}
- // {{{ getCallback()
-
- /**
- * Get the callback function/method from an error object.
- *
- * @return mixed callback function or object/method array
- * @access public
- */
- function getCallback() {
- return $this->callback;
- }
-
- // }}}
- // {{{ getMessage()
-
-
- /**
- * Get the error message from an error object.
- *
- * @return string full error message
- * @access public
- */
- function getMessage()
- {
- return ($this->error_message_prefix . $this->message);
- }
-
-
- // }}}
- // {{{ getCode()
-
- /**
- * Get error code from an error object
- *
- * @return int error code
- * @access public
- */
- function getCode()
- {
- return $this->code;
- }
-
- // }}}
- // {{{ getType()
-
- /**
- * Get the name of this error/exception.
- *
- * @return string error/exception name (type)
- * @access public
- */
- function getType()
- {
- return get_class($this);
- }
-
- // }}}
- // {{{ getUserInfo()
-
- /**
- * Get additional user-supplied information.
- *
- * @return string user-supplied information
- * @access public
- */
- function getUserInfo()
- {
- return $this->userinfo;
- }
-
- // }}}
- // {{{ getDebugInfo()
-
- /**
- * Get additional debug information supplied by the application.
- *
- * @return string debug information
- * @access public
- */
- function getDebugInfo()
- {
- return $this->getUserInfo();
- }
-
- // }}}
- // {{{ getBacktrace()
-
- /**
- * Get the call backtrace from where the error was generated.
- * Supported with PHP 4.3.0 or newer.
- *
- * @param int $frame (optional) what frame to fetch
- * @return array Backtrace, or NULL if not available.
- * @access public
- */
- function getBacktrace($frame = null)
- {
- if ($frame === null) {
- return $this->backtrace;
- }
- return $this->backtrace[$frame];
- }
-
- // }}}
- // {{{ addUserInfo()
-
- function addUserInfo($info)
- {
- if (empty($this->userinfo)) {
- $this->userinfo = $info;
- } else {
- $this->userinfo .= " ** $info";
- }
- }
-
- // }}}
- // {{{ toString()
-
- /**
- * Make a string representation of this object.
- *
- * @return string a string with an object summary
- * @access public
- */
- function toString() {
- $modes = array();
- $levels = array(E_USER_NOTICE => 'notice',
- E_USER_WARNING => 'warning',
- E_USER_ERROR => 'error');
- if ($this->mode & PEAR_ERROR_CALLBACK) {
- if (is_array($this->callback)) {
- $callback = get_class($this->callback[0]) . '::' .
- $this->callback[1];
- } else {
- $callback = $this->callback;
- }
- return sprintf('[%s: message="%s" code=%d mode=callback '.
- 'callback=%s prefix="%s" info="%s"]',
- get_class($this), $this->message, $this->code,
- $callback, $this->error_message_prefix,
- $this->userinfo);
- }
- if ($this->mode & PEAR_ERROR_PRINT) {
- $modes[] = 'print';
- }
- if ($this->mode & PEAR_ERROR_TRIGGER) {
- $modes[] = 'trigger';
- }
- if ($this->mode & PEAR_ERROR_DIE) {
- $modes[] = 'die';
- }
- if ($this->mode & PEAR_ERROR_RETURN) {
- $modes[] = 'return';
- }
- return sprintf('[%s: message="%s" code=%d mode=%s level=%s '.
- 'prefix="%s" info="%s"]',
- get_class($this), $this->message, $this->code,
- implode("|", $modes), $levels[$this->level],
- $this->error_message_prefix,
- $this->userinfo);
- }
-
- // }}}
-}
-
-register_shutdown_function("_PEAR_call_destructors");
-
-/*
- * Local Variables:
- * mode: php
- * tab-width: 4
- * c-basic-offset: 4
- * End:
- */
-?>
+++ /dev/null
-<?php
-
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * PHP_Debug : A simple and fast way to debug your PHP code
- *
- * The basic purpose of PHP_Debug is to provide assistance in debugging PHP
- * code, by 'debug' i don't mean 'step by step debug' but program trace,
- * variables display, process time, included files, queries executed, watch
- * variables... These informations are gathered through the script execution and
- * therefore are displayed at the end of the script (in a nice floating div or a
- * html table) so that it can be read and used at any moment. (especially
- * usefull during the development phase of a project or in production with a
- * secure key/ip)
- *
- * PHP version 5 only
- *
- * Copyright (c) 2007 - Vernet Loïc
-
- * 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.
- *
- * @category PHP
- * @package PHP_Debug
- * @author Vernet Loïc <qrf_coil[at]yahoo.fr>
- * @copyright 1997-2007 The PHP Group
- * @license http://www.opensource.org/licenses/mit-license.php MIT
- * @link http://pear.php.net/package/PHP_Debug
- * @link http://phpdebug.sourceforge.net
- * @link http://www.php-debug.com
- * @see Text_Highlighter, Services_W3C_HTMLValidator
- * @see Var_Dump, SQL_Parser
- * @since 1.0.0RC1
- * @version CVS: $Id: Debug.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
- */
-
-/**
- * Factory class for renderer of Debug class
- *
- * @see Debug/Renderer/*.php
- */
-require_once 'PHP/DebugLine.php';
-require_once 'PHP/Debug/Renderer.php';
-
-/**
- * External constants
- *
- * @filesource
- * @package PHP_Debug
- */
-if (!defined('CR')) {
- define('CR', "\n");
-}
-
-class PHP_Debug
-{
-
- /**
- * Possible version of class Debug
- */
- const VERSION_STANDALONE = 0;
- const VERSION_PEAR = 1;
- const VERSION_DEFAULT = self::VERSION_STANDALONE;
- const VERSION = self::VERSION_STANDALONE;
- const RELEASE = 'V2.1.2';
- const PEAR_RELEASE = 'V1.0.0';
-
- /**
- * These are constant for dump() and DumpObj() functions.
- *
- * - DUMP_DISP : Tell the function to display the debug info.
- * - DUMP_STR : Tell the fonction to return the debug info as a string
- * - DUMP_VARNAME : Default name of Array - DBG_ARR_OBJNAME : Default name
- * of Object
- */
- const DUMP_DISP = 1;
- const DUMP_STR = 2;
- const DUMP_VARNAME = 'Variable';
-
- /**
- * These are constant for addDebug functions, they set the behaviour where
- * the function should add the debug information in first or in last
- * position
- */
- const POSITIONLAST = 0;
- const POSITIONFIRST = 1;
-
- /**
- * These are constants to define Super array environment variables
- */
- const GLOBAL_GET = 0;
- const GLOBAL_POST = 1;
- const GLOBAL_FILES = 2;
- const GLOBAL_COOKIE = 3;
- const GLOBAL_REQUEST = 4;
- const GLOBAL_SESSION = 5;
- const GLOBAL_GLOBALS = 6;
-
- /**
- * Default configuration options
- *
- * @since V2.0.0 - 16 apr 2006
- * @see setOptions()
- * @var array
- */
- protected $defaultOptions = array(
- 'render_mode' => 'Div', // Renderer mode
- 'render_type' => 'HTML', // Renderer type
- 'restrict_access' => false, // Restrict or not the access
- 'allowed_ip' => array('127.0.0.1'), // Authorized IP to view the debug when restrict_access is true
- 'allow_url_access' => false, // Allow to access the debug with a special parameter in the url
- 'url_key' => 'debug', // Key for url instant access
- 'url_pass' => 'true', // Password for url instant access
- 'enable_watch' => false, // Enable the watch function
- 'replace_errorhandler' => true, // Replace or no the PHP errorhandler
- 'lang' => 'EN', // Language
- 'enable_w3c_validator' => false, // Validate the output
- );
-
- /**
- * Default static options for static functions
- *
- * @since V2.0.0 - 16 apr 2006
- * @see dump()
- * @var array
- */
- protected static $staticOptions = array(
- 'dump_method' => 'print_r', // print_r or var_dump
- 'pear_var_dump_method' => 'Var_Dump::display' // Var_Dump display funtion (not used for now)
- );
-
- /**
- * Functions from this class that must be excluded in order to have the
- * correct backtrace information
- *
- * @see PHP_DebugLine::setTraceback()
- * @since V2.0.0 - 13 apr 2006
- * @var array
- */
- public static $excludedBackTraceFunctions = array(
- 'add',
- 'dump',
- 'error',
- 'query',
- 'addDebug',
- 'setAction',
- 'addDebugFirst',
- 'watchesCallback',
- 'errorHandlerCallback'
- );
-
- /**
- * Correspondance between super array constant and variable name
- * Used by renderers
- *
- * @since V2.0.0 - 18 apr 2006
- * @var array
- */
- public static $globalEnvConstantsCorresp = array(
- self::GLOBAL_GET => '_GET',
- self::GLOBAL_POST => '_POST',
- self::GLOBAL_FILES => '_FILES',
- self::GLOBAL_COOKIE => '_COOKIE',
- self::GLOBAL_REQUEST=> '_REQUEST',
- self::GLOBAL_SESSION=> '_SESSION',
- self::GLOBAL_GLOBALS=> 'GLOBALS'
- );
-
- /**
- * Default configuration options
- *
- * @since V2.0.0 - 13 apr 2006
- * @see setOptions()
- * @var array
- */
- protected $options = array();
-
- /**
- * This is the array where the debug lines are collected.
- *
- * @since V2.0.0 - 11 apr 2006
- * @see DebugLine
- * @var array
- */
- protected $debugLineBuffer = array();
-
- /**
- * This is the array containing all the required/included files of the
- * script
- *
- * @since V2.0.0 - 17 apr 2006
- * @see render(), PHP_DebugLine::TYPE_TEMPLATES
- * @var array
- */
- protected $requiredFiles = array();
-
- /**
- * This is the array containing all the watched variables
- *
- * @since V2.0.0 - 16 apr 2006
- * @see watch()
- * @var array
- */
- protected $watches = array();
-
- /**
- * Execution start time
- *
- * @since V2.0.0 - 11 apr 2006
- * @see __construct()
- * @var float
- */
- protected $startTime;
-
- /**
- * Exection end time
- *
- * @since V2.0.0 - 11 apr 2006
- * @see render()
- * @var float
- */
- protected $endTime;
-
- /**
- * Number of queries executed during script
- *
- * @since V2.0.0 - 19 apr 2006
- * @var integer
- */
- protected $queryCount = 0;
-
- /**
- * PHP_Debug class constructor
- *
- * Here we set :
- * - the execution start time
- * - the options
- * - the error and watch call back functions
- *
- * @param array $options Array containing options to affect to Debug
- * object and his childs
- *
- * @since V2.0.0 - 11 apr 2006
- */
- function __construct($options = array())
- {
- $this->startTime = PHP_Debug::getMicroTimeNow();
- $this->options = array_merge($this->defaultOptions, $options);
- $this->setWatchCallback();
- $this->setErrorHandler();
- }
-
- /**
- * Add a debug information
- *
- * @param string $info The main debug information
- * (may be empty for some debug line types)
- * @param integer $type Type of the DebugLine
- *
- * @see Debug constants
- * @since V1.0.0 - 07 Apr 2006
- */
- public function addDebug($info, $type = PHP_DebugLine::TYPE_STD,
- $position = self::POSITIONLAST)
- {
- // Add info
- $debugLine = new PHP_DebugLine($info, $type);
- if ($position == self::POSITIONLAST) {
- $this->debugLineBuffer[] = $debugLine;
- } else {
- array_unshift($this->debugLineBuffer, $debugLine);
- }
-
- // Additional process for some types
- switch ($type) {
- case PHP_DebugLine::TYPE_QUERY:
- $this->queryCount++;
- break;
-
- default:
- break;
- }
-
- // Return debugline
- return $debugLine;
- }
-
- /**
- * Add a debug info before all the existing other debug lines
- * It is an alias for addDebug($info, self::POSITIONLAST)
- *
- * @see addDebug
- * @since V1.0.0 - 13 Apr 2006
- */
- public function addDebugFirst($info, $type = PHP_DebugLine::TYPE_STD)
- {
- return $this->addDebug($info, $type, self::POSITIONFIRST);
- }
-
- /**
- * This is an alias for the addDebug function
- *
- * @see addDebug()
- * @since V2.0.0 - 20 apr 2006
- */
- public function add($info, $type = PHP_DebugLine::TYPE_STD)
- {
- return $this->addDebug($info, $type);
- }
-
- /**
- * This is an alias for the addDebug function when wanting to add a query
- * debug information
- *
- * @see addDebug(), PHP_DebugLine::TYPE_QUERY
- * @since V2.0.0 - 21 Apr 2006
- */
- public function query($qry)
- {
- return $this->addDebug($qry, PHP_DebugLine::TYPE_QUERY);
- }
-
- /**
- * This is an alias for the addDebug function when wanting to add a
- * database related debug info
- *
- * @see addDebug(), PHP_DebugLine::TYPE_QUERYREL
- * @since V2.1.0 - 3 apr 2007
- */
- public function queryRel($info)
- {
- return $this->addDebug($info, PHP_DebugLine::TYPE_QUERYREL);
- }
-
- /**
- * This is an alias for the addDebug function when wanting to add an
- * application error
- *
- * @see addDebug(), PHP_DebugLine::TYPE_APPERROR
- * @since V2.0.0 - 21 Apr 2006
- */
- public function error($info)
- {
- return $this->addDebug($info, PHP_DebugLine::TYPE_APPERROR);
- }
-
- /**
- * This is an alias for adding the monitoring of processtime
- *
- * @see addDebug(), PHP_DebugLine::TYPE_PROCESSPERF
- * @since V2.1.0 - 21 Apr 2006
- */
- public function addProcessPerf()
- {
- return $this->addDebug('', PHP_DebugLine::TYPE_PROCESSPERF);
- }
-
- /**
- * This a method to dump the content of any variable and add the result in
- * the debug information
- *
- * @param mixed $var Variable to dump
- * @param string $varname Name of the variable
- *
- * @since V2.0.0 - 25 Apr 2006
- */
- public function dump($obj, $varName = '')
- {
- $info[] = $varName;
- $info[] = $obj;
- return $this->addDebug($info, PHP_DebugLine::TYPE_DUMP);
- }
-
- /**
- * Set the main action of PHP script
- *
- * @param string $action Name of the main action of the file
- *
- * @since V2.0.0 - 25 Apr 2006
- * @see PHP_DebugLine::TYPE_CURRENTFILE
- */
- public function setAction($action)
- {
- $this->add($action, PHP_DebugLine::TYPE_PAGEACTION);
- }
-
- /**
- * Add an application setting
- *
- * @param string $action Name of the main action of the file
- *
- * @since V2.1.0 - 02 Apr 2007
- * @see PHP_DebugLine::TYPE_ENV
- */
- public function addSetting($value, $name)
- {
- $this->add($name. ': '. $value, PHP_DebugLine::TYPE_ENV);
- }
-
- /**
- * Add a group of settings
- *
- * @param string $action Name of the main action of the file
- *
- * @since V2.1.0 - 2 Apr 2007
- * @see PHP_DebugLine::TYPE_ENV
- */
- public function addSettings($values, $name)
- {
- $this->add($name. ': '.
- PHP_Debug::dumpVar(
- $values,
- $name,
- false,
- PHP_Debug::DUMP_STR
- ),
- PHP_DebugLine::TYPE_ENV
- );
- }
-
- /**
- * Set the callback fucntion to process the watches, enabled depending of
- * the options flag 'enable_watch'
- *
- * @since V2.0.0 - 16 apr 2006
- * @see options, watches, watchesCallback()
- */
- protected function setWatchCallback()
- {
- if ($this->options['enable_watch'] == true) {
- if (count($this->watches) === 0) {
- $watchMethod = array($this, 'watchesCallback');
- register_tick_function($watchMethod);
- }
- }
- }
-
- /**
- * Set the callback function to process replace the php error handler,
- * enabled depending of the options flag 'replace_errorhandler'
- *
- * @since V2.0.0 - 16 apr 2006
- * @see options, errorHandlerCallback()
- */
- protected function setErrorHandler()
- {
- if ($this->options['replace_errorhandler'] == true) {
-
- $errorhandler = array(
- $this,
- 'errorHandlerCallback'
- );
- set_error_handler($errorhandler);
- }
- }
-
- /**
- * Callback function for php error handling
- *
- * Warning : the only PHP error codes that are processed by this user
- * handler are : E_WARNING, E_NOTICE, E_USER_ERROR
- * For the other error codes the standart php handler will be used
- *
- * @since V2.0.0 - 17 apr 2006
- * @see options, setErrorHandler()
- */
- public function errorHandlerCallback()
- {
- $details = func_get_args();
- $popNumber = 3;
-
- // We already have line & file with setBackTrace function
- for ($index = 0; $index < $popNumber; $index++) {
- array_pop($details);
- }
-
- if ($details[0] != E_STRICT)
- $this->addDebug($details, PHP_DebugLine::TYPE_PHPERROR);
- }
-
- /**
- * Add a variable to the watchlist. Watched variables must be in a declare
- * (ticks=n) block so that every n ticks the watched variables are checked
- * for changes. If any changes were made, the new value of the variable is
- * recorded
- *
- * @param string $variableName Variable to watch
- * @since V2.0.0 - 17 apr 2006
- * @see watchesCallback()
- */
- public function watch($variableName)
- {
- if ($this->options['enable_watch'] == true) {
- if (isset($GLOBALS[$variableName])) {
- $this->watches[$variableName] = $GLOBALS[$variableName];
- } else {
- $this->watches[$variableName] = null;
- }
- } else {
- throw new Exception('The Watch function is disabled please set the option \'enable_watch\' to \'true\' to be able to use this feature, it\'s stable with a Unix server');
- }
- }
-
- /**
- * Watch callback function, process watches and add changes to the debug
- * information
- *
- * @since V2.0.0 - 17 apr 2006
- * @see watch()
- */
- public function watchesCallback()
- {
- // Check if there are variables to watch
- if (count($this->watches)) {
- foreach ($this->watches as $variableName => $variableValue) {
- if ($GLOBALS[$variableName] !== $this->watches[$variableName]) {
-
- $info = array(
- $variableName,
- $this->watches[$variableName],
- $GLOBALS[$variableName]
- );
-
- $this->watches[$variableName] = $GLOBALS[$variableName];
- $this->addDebug($info, PHP_DebugLine::TYPE_WATCH);
- }
- }
- }
- }
-
- /**
- * Get global process time
- *
- * @return float Execution process time of the script
- *
- * @see getElapsedTime()
- * @since V2.0.0 - 21 Apr 2006
- */
- public function getProcessTime()
- {
- return $this->getElapsedTime($this->startTime, $this->endTime);
- }
-
- /**
- * Get database related process time
- *
- * @return float Execection process time of the script for all
- * database specific tasks
- *
- * @see PHP_DebugLine::TYPE_QUERY, PHP_DebugLine::TYPE_QUERYREL
- * @since V2.0.0 - 21 Apr 2006
- */
- public function getQueryTime()
- {
- $queryTime = 0;
-
- foreach($this->debugLineBuffer as $lkey => $lvalue) {
- $properties = $lvalue->getProperties();
- if ($properties['type'] == PHP_DebugLine::TYPE_QUERY
- || $properties['type'] == PHP_DebugLine::TYPE_QUERYREL) {
- if (!empty($properties['endTime'])) {
- $queryTime = $queryTime +
- $this->getElapsedTime(
- $properties['startTime'],
- $properties['endTime']);
- }
- }
- }
- return $queryTime;
- }
-
- /**
- * PHP_Debug default output function, first we finish the processes and
- * then a render object is created and its render method is invoked
- *
- * The renderer used is set with the options, all the possible renderer
- * are in the directory Debug/Renderer/*.php
- * (not the files ending by '_Config.php')
- *
- * @since V2.0.0 - 13 apr 2006
- * @see Debug_Renderer
- */
- public function render()
- {
- // Finish process
- $this->endTime = PHP_Debug::getMicroTimeNow();
-
- // Render output if we are allowed to
- if ($this->isAllowed()) {
-
- // Create render object and invoke its render function
- $renderer = PHP_Debug_Renderer::factory($this, $this->options);
-
- // Get required files here to have event all Debug classes
- $this->requiredFiles = get_required_files();
-
- // Call rendering
- return$renderer->render();
- }
- }
-
- /**
- * Alias for the render function
- *
- * @since V2.0.0 - 17 apr 2006
- * @see render()
- */
- public function display()
- {
- echo $this->render();
- }
-
- /**
- * Return the output without displaying it
- *
- * @since V2.0.1 - 17 apr 2006
- * @see render()
- */
- public function getOutput()
- {
- return $this->render();
- }
-
- /**
- * Restrict access to a list of IP
- *
- * @param array $ip Array with IP to allow access
- * @since V2.0.0 - 11 Apr 2006
- * @see $options, isAllowed()
- */
- function restrictAccess($ip)
- {
- $this->options['allowed_ip'] = $ip;
- }
-
- /**
- * Test if the client is allowed to access the debug information
- * There are several possibilities :
- * - 'restrict_access' flag is set to false
- * - 'restrict_access' flag is set to true and client IP is the
- * allowed ip in the options 'allowed_ip'
- * - Access by url is allowed with flag 'allow_url_access' then
- * the client must enter the good key and password in the url
- *
- * @since V2.0.0 - 20 apr 2006
- * @see $options, restrictAcess()
- */
- protected function isAllowed()
- {
- if ($this->options['restrict_access'] == true) {
-
- // Check if client IP is among the allowed ones
- if (in_array(
- $_SERVER['REMOTE_ADDR'],
- $this->options['allowed_ip']
- )) {
- return true;
- }
- // Check if instant access is allowed and test key and password
- elseif ($this->options['allow_url_access'] == true) {
-
- $key = $this->options['url_key'];
-
- if (!empty($_GET[$key])) {
- if ($_GET[$key] == $this->options['url_pass']) {
- return true;
- } else {
- return false;
- }
- }
- else {
- return false;
- }
- } else {
- return false;
- }
- } else {
- // Access is not restricted
- return true;
- }
- }
-
- /**
- * Return microtime from a timestamp
- *
- * @param $time Timestamp to retrieve micro time
- * @return numeric Microtime of timestamp param
- *
- * @since V1.1.0 - 14 Nov 2003
- * @see $DebugMode
- */
- public static function getMicroTime($time)
- {
- list($usec, $sec) = explode(' ', $time);
- return (float)$usec + (float)$sec;
- }
-
- /**
- * Alias for getMicroTime(microtime()
- *
- * @see getMicroTime()
- * @since V2.0.0 - 19 apr 2006
- */
- public static function getMicroTimeNow()
- {
- return PHP_Debug::getMicroTime(microtime());
- }
-
- /**
- * Get elapsed time between 2 timestamp
- *
- * @param float $timeStart Start time
- * @param float $timeEnd End time
- * @return float Numeric difference between the two times
- * ref in format 00.0000 sec
- *
- * @see getMicroTime()
- * @since V1.0.0 - 20 Oct 2003
- */
- public static function getElapsedTime($timeStart, $timeEnd)
- {
- return round($timeEnd - $timeStart, 4);
- }
-
- /**
- * Returns Uri prefix, including protocol, hostname and server port.
- *
- * @return string Uniform resource identifier prefix
- */
- public static function getUriPrefix()
- {
- $pathArray = $_SERVER;
-
- if (PHP_Debug::isSecure()) {
- $standardPort = '443';
- $proto = 'https';
- } else {
- $standardPort = '80';
- $proto = 'http';
- }
-
- $port = $pathArray['SERVER_PORT'] == $standardPort || !$pathArray['SERVER_PORT'] ? '' : ':'.$pathArray['SERVER_PORT'];
- return $proto.'://'. $pathArray['SERVER_NAME']. $port;
- }
-
- /**
- * Test if url is secured
- *
- * @since V2.1.1 - 23 avr. 2007
- */
- public static function isSecure()
- {
- return $_SERVER['SERVER_PORT'] != 80;
- }
-
- /**
- * Returns current host name.
- *
- * @since V2.1.1 - 23 avr. 2007
- */
- public static function getHost()
- {
- $pathArray = $_SERVER;
- return isset($pathArray['HTTP_X_FORWARDED_HOST']) ? $pathArray['HTTP_X_FORWARDED_HOST'] : (isset($pathArray['HTTP_HOST']) ? $pathArray['HTTP_HOST'] : '');
- }
-
- /**
- * Returns current script name.
- *
- * @return string
- * @since V2.1.1 - 23 avr. 2007
- */
- public static function getScriptName()
- {
- $pathArray = $_SERVER;
- return isset($pathArray['SCRIPT_NAME']) ? $pathArray['SCRIPT_NAME'] : (isset($pathArray['ORIG_SCRIPT_NAME']) ? $pathArray['ORIG_SCRIPT_NAME'] : '');
- }
-
- /**
- * Return the query string
- *
- * @author Vernet Loic
- * @since 2.1.1 - 23 avr. 2007
- */
- public static function getQueryString()
- {
- return $_SERVER['QUERY_STRING'] ? '?'. $_SERVER['QUERY_STRING'] : '';
- }
-
- /**
- * Return the full url
- *
- * @author Vernet Loi
- * @since 2.1.1 - 23 avr. 2007
- */
- public static function getUrl()
- {
- return self::getUriPrefix(). self::getScriptName(). self::getQueryString();
- }
-
- /**
- * Set the endtime for a DebugLine in order to monitor the performance
- * of a part of script
- *
- * @see PHP_DebugLine::endTime
- * @since V2.0.0 - 19 apr 2006
- */
- public function stopTimer()
- {
- $this->debugLineBuffer[count($this->debugLineBuffer)-1]->setEndTime();
- }
-
- /**
- * Display the content of any kind of variable
- *
- * - Mode PHP_DEBUG_DUMP_ARR_DISP display the array
- * - Mode PHP_DEBUG_DUMP_ARR_STR return the infos as a string
- *
- * @param mixed $var Variable to dump
- * @param string $varname Name of the variable
- * @param integer $mode Mode of function
- * @param boolean $stopExec Stop the process after display of debug
- * @return mixed Nothing or string depending on the mode
- *
- * @since V2.0.0 - 25 Apr 2006
- */
- public static function dumpVar(
- $var,
- $varName = self::DUMP_VARNAME,
- $stopExec = false,
- $mode = self::DUMP_DISP) {
- $dumpMethod = self::$staticOptions['dump_method'];
- ob_start();
- $dumpMethod($var);
-
- $dbgBuffer = htmlentities(ob_get_contents());
- ob_end_clean();
-
- switch ($mode) {
- default:
- case self::DUMP_DISP:
-
- if (empty($varName)) {
- if (is_array($var)) {
- $varName = 'Array';
- } elseif (is_object($var)) {
- $varName = get_class($var);
- } else {
- $varName = 'Variable';
- }
- }
-
- $dbgBuffer = '<pre><b>dump of \''. $varName. '\'</b> :'.
- CR. $dbgBuffer. '</pre>';
- echo $dbgBuffer;
- break;
-
- case PHP_Debug::DUMP_STR:
- return($dbgBuffer);
- }
-
- // Check process stop
- if ($stopExec) {
- $backtrace = debug_backtrace();
- $dieMsg = '<pre><b>Process stopped by PHP_Debug</b>'. CR;
- $dieMsg .= $backtrace[0]['file'] ? '» file : <b>'.
- $backtrace[0]['file'] .'</b>'. CR : '';
- $dieMsg .= $backtrace[0]['line'] ? '» line : <b>'.
- $backtrace[0]['line'] .'</b>'. CR : '';
- $dieMsg .= $backtrace[1]['class'] ? '» class : <b>'.
- $backtrace[1]['class'] .'</b>'. CR : '';
- $dieMsg .= $backtrace[1]['function'] ? '» function : <b>'.
- $backtrace[1]['function'] .'</b>'. CR : '';
- $dieMsg .= '</pre>';
- die($dieMsg);
- }
- }
-
- /**
- * Get one option
- *
- * @param string $optionsIdx Name of the option to get
- * @since V2.0.0 - 13 apr 2006
- */
- public function getOption($optionIdx)
- {
- return $this->options[$optionIdx];
- }
-
- /**
- * Getter of requiredFiles property
- *
- * @return array Array with the included/required files
- * @since V2.0.0 - 13 apr 2006
- * @see requiredFiles
- */
- public function getRequiredFiles()
- {
- return $this->requiredFiles;
- }
-
- /**
- * Getter of debugString property
- *
- * @since V2.0.0 - 13 apr 2006
- * @see debugLineBuffer
- */
- public function getDebugBuffer()
- {
- return $this->debugLineBuffer;
- }
-
- /**
- * Getter of queryCount property
- *
- * @since V2.0.0 - 21 Apr 2006
- * @see queryCount
- */
- public function getQueryCount()
- {
- return $this->queryCount;
- }
-
- /**
- * Debug default output function, simply uses the static dump fonction
- * of this class
- *
- * @since V2.0.0 - 11 apr 2006
- * @see dump
- */
- public function __toString()
- {
- return '<pre>'. PHP_Debug::dumpVar(
- $this,
- __CLASS__. ' class instance',
- false,
- PHP_Debug::DUMP_STR
- ). '</pre>';
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-require_once 'PHP/Debug/Renderer/Common.php';
-
-/**
- * A loader class for the renderers.
- *
- * @package PHP_Debug
- * @category PHP
- * @author Loic Vernet <qrf_coil at yahoo dot fr>
- * @since V2.0.0 - 10 Apr 2006
- *
- * @package PHP_Debug
- * @filesource
- */
-
-class PHP_Debug_Renderer
-{
-
- /**
- * Attempt to return a concrete Debug_Renderer instance.
- *
- * @param string $mode Name of the renderer.
- * @param array $options Parameters for the rendering.
- * @access public
- */
- public static function factory($debugObject, $options)
- {
- $className = 'PHP_Debug_Renderer_'. $options['render_type'].
- '_'. $options['render_mode'];
- $classPath = 'PHP/Debug/Renderer/'. $options['render_type'].
- '/'. $options['render_mode']. '.php';
-
- include_once $classPath;
-
- if (class_exists($className)) {
- $obj = new $className($debugObject, $options);
- } else {
- include_once 'PEAR.php';
- PEAR::raiseError('PHP_Debug: renderer >' .
- $options['DEBUG_render_mode'] . '< not found', true);
- return NULL;
- }
- return $obj;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/**
- * A base class for Debug renderers, must be inherited by all such.
- *
- * @package PHP_Debug
- * @category PHP
- * @author Loic Vernet <qrf_coil at yahoo dot fr>
- * @since V2.0.0 - 10 Apr 2006
- *
- * @package PHP_Debug
- * @filesource
- */
-
-class PHP_Debug_Renderer_Common
-{
- /**
- *
- * @var Debug object
- * This is the debug object to render
- */
- protected $DebugObject = null;
-
- /**
- * Run-time configuration options.
- *
- * @var array
- * @access public
- */
- protected $options = array();
-
- /**
- * Default configuration options.
- *
- * @See Debug/Renderer/*.php for the complete list of options
- * @var array
- * @access public
- */
- protected $defaultOptions = array();
-
- /**
- * Set run-time configuration options for the renderer
- *
- * @param array $options Run-time configuration options.
- * @access public
- */
- public function setOptions($options = array())
- {
- $this->options = array_merge($this->defaultOptions, $options);
- }
-
- /**
- * Default output function
- */
- public function __toString()
- {
- return '<pre>'.
- PHP_Debug::dumpVar(
- $this,
- __CLASS__,
- PHP_DEBUG_DUMP_ARR_STR
- ) . '<pre>';
- }
-
- /**
- * PHP_DebugOutput class destructor
- */
- function __destruct()
- {
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/**
- * Class of the HTML_Div renderer
- *
- * Idea from the debug system of the symfony PHP framework
- * @see http://www.symfony-project.com
- * @author Fabien Potencier
- * @author François Zaninotto
- *
- * @author Vernet Loïc
- *
- */
-require_once 'PHP/Debug/Renderer/HTML/DivConfig.php';
-
-
-/**
- * A floating div renderer for PHP_Debug
- *
- * Returns a floating based representation of the debug infos in XHTML sctrict
- * format
- *
- * @package PHP_Debug
- * @category PHP
- * @author Loïc Vernet <qrf_coil at yahoo dot fr>
- * @since V2.1.0 - 30 march 2007
- *
- * @package PHP_Debug
- * @filesource
- */
-
-class PHP_Debug_Renderer_HTML_Div extends PHP_Debug_Renderer_Common
-{
- // debug types for Vars & Config
- protected static $settingsType = array(
- PHP_DebugLine::TYPE_ENV,
- );
-
- // debug types for Log & Message tab
- protected static $msgTypes = array(
- PHP_DebugLine::TYPE_STD,
- PHP_DebugLine::TYPE_PAGEACTION,
- PHP_DebugLine::TYPE_APPERROR,
- PHP_DebugLine::TYPE_CREDITS,
- PHP_DebugLine::TYPE_DUMP,
- PHP_DebugLine::TYPE_WATCH,
- PHP_DebugLine::TYPE_PHPERROR
- );
-
- // debug types for Database tab
- protected static $databaseTypes = array(
- PHP_DebugLine::TYPE_QUERY,
- PHP_DebugLine::TYPE_QUERYREL,
- PHP_DebugLine::TYPE_SQLPARSE,
- );
-
- /**
- * Debug_Renderer_HTML_Div class constructor
- *
- * @since V2.1.0 - 3 apr 2007
- */
- function __construct($DebugObject, $options)
- {
- $this->DebugObject = $DebugObject;
- $this->defaultOptions = PHP_Debug_Renderer_HTML_DivConfig::singleton()->getConfig();
- $this->setOptions($options);
-
- if ($this->options['HTML_DIV_disable_credits'] == false) {
- $this->DebugObject->addDebugFirst($this->options['HTML_DIV_credits'],
- PHP_DebugLine::TYPE_CREDITS);
- }
-
- // Add execution time
- $this->DebugObject->addProcessPerf();
- }
-
- /**
- * This is the function to display the debug informations
- *
- * @since V2.0.0 - 07 Apr 2006
- * @see PHP_Debug::Render()
- */
- public function display()
- {
- $buffer = '';
-
- // Header
- $buffer .= $this->displayHeader();
-
- // Infos
- $debugInfos = $this->DebugObject->getDebugBuffer();
-
- // Vars & config
- $buffer .= $this->showVarsAndConfig($debugInfos);
-
- // Logs & msg
- $buffer .= $this->showLogsAndMsg($debugInfos);
-
- // Database
- $buffer .= $this->showDatabaseInfos($debugInfos);
-
- // W3C Validation
- $buffer .= $this->showW3cValidation($debugInfos);
-
- // Process time
- $buffer .= $this->showProcessTime($debugInfos);
-
- // Footer
- $buffer .= $this->displayFooter();
-
- return $buffer;
- }
-
- /**
- * Show result of the W3C validator
- *
- * @author COil
- * @since V2.1.1 - 23 apr 2007
- *
- * @see $options['enable_w3c_validator']
- * @see Services_W3C_HTMLValidator
- */
- protected function showW3cValidation()
- {
- // Service validation is enabled
- if ($this->options['enable_w3c_validator']) {
-
- // Validator
- require_once 'Services/W3C/HTMLValidator.php';
-
- $url = PHP_Debug::getUrl();
- $v = new Services_W3C_HTMLValidator();
- $res = $v->validate($url);
-
- if ($res) {
- if ($res->isValid()) {
- $results = '<h2><img src="{$imagesPath}/info.png" alt="Valid"/> The output is valid</h2>';
- } else {
- $results = '<h2><img src="{$imagesPath}/error.png" alt="Not valid" /> The output is <b>NOT</b> valid</h2>';
-
- if ($res->errors || $res->warnings) {
-
- // Validation errors
- if ($res->errors) {
- $key = 'errors';
- $results.= $this->addW3CErrorInfos($res, $key);
- }
-
- // Validation warnings
- if ($res->warnings) {
- $key = 'warnings';
- $results.= $this->addW3CErrorInfos($res, $key);
- }
- } else {
- $results = '<h2><img src="{$imagesPath}/warning.png" alt="warning" /> Validation results can\'t be retrieved (localhost source ?)</h2>
- ';
- }
- }
- } else {
- throw new exception('Services_W3C_HTMLValidator : Unable to parse '.
- $url);
- }
- } else {
- $results = '';
- }
-
- return str_replace(
- array(
- '{$results}',
- '{$imagesPath}',
- ),
- array(
- $results,
- $this->options['HTML_DIV_images_path']
- ),
- $this->options['HTML_DIV_sfWebDebugW3CDetails']
- );
- }
-
- /**
- * Add the debug informations of the W3C validation process
- *
- * @author Vernet Loïc
- * @since 2.1.0 - 23 avr. 2007
- */
- protected function addW3CErrorInfos($res, $key)
- {
- $title = ucwords($key);
- $type = 'sfW3C'. $title;
- $errorCpt = 1;
- $results = str_replace(
- '{$title}',
- $title,
- $this->options['HTML_DIV_sfWebDebugW3CTableHeader']
- );
-
- foreach ($res->$key as $error) {
- $id = $errorCpt. ($error->messageid ? ' ('. $error->messageid. ')' : '');
- $results .= str_replace(
- array(
- '{$type}',
- '{$cpt}',
- '{$line}',
- '{$col}',
- '{$message}',
- '{$source}',
- ),
- array(
- $type,
- $id,
- $error->line,
- $error->col,
- $error->message,
- ' ',
- ),
- $this->options['HTML_DIV_sfWebDebugW3CErrorRow']
- );
- $errorCpt++;
- }
- $results .= '</table>';
-
- return $results;
- }
-
- /**
- * Shows vars & config
- *
- * @param array debug row
- *
- * @author COil
- * @since V2.1.0 - 30 march 2007
- */
- protected function showDatabaseInfos($debugInfos)
- {
- $idx = 1;
- $buffer = '';
-
- foreach ($debugInfos as $debugInfo) {
- $properties = $debugInfo->getProperties();
- if (in_array($properties['type'], self::$databaseTypes)) {
- $buffer.= '<li>['. $this->processExecTime($properties). '] '.
- $this->processDebugInfo($properties) .'</li>'. CR;
- }
- }
-
- return str_replace(
- array('{$buffer}'),
- array($buffer ? $buffer : '<li>No database debug available</li>'),
- $this->options['HTML_DIV_sfWebDebugDatabaseDetails']
- );
- }
-
- /**
- * Shows vars & config
- *
- * @author COil
- * @since V2.1.0 - 30 march 2007
- */
- protected function showLogsAndMsg($debugInfos)
- {
- $idx = 1;
- $buffer = '';
-
- foreach($debugInfos as $debugInfo) {
- $properties = $debugInfo->getProperties();
- if (in_array($properties['type'], self::$msgTypes)) {
-
- // Error level of debug information
- $level = $this->getLogInfoLevel($properties);
- $infoImg = $this->getImageInfo($level);
-
- $buffer .= '<tr class=\'sfWebDebugLogLine '. $this->getDebugLevelClass($level). '\'>
- <td class="sfWebDebugLogNumber"># '. $idx. '</td>
- <td class="sfWebDebugLogType">
- <img src="'. $this->options['HTML_DIV_images_path']. '/'. $infoImg .'" alt="" /> '. $this->processType($properties).
- '</td>
- <td class="sfWebDebugLogFile">'. $this->processFile($properties). '</td>
- <td class="sfWebDebugLogLine">'. $this->processLine($properties). '</td>
- <td class="sfWebDebugLogClass">'. $this->processClass($properties). '</td>
- <td class="sfWebDebugLogFunction">'. $this->processFunction($properties). '</td>
- <td class="sfWebDebugLogTime">'. $this->processExecTime($properties). '</td>
- <td class="sfWebDebugLogMessage">'. $this->processDebugInfo($properties). '</td>
- </tr>'. CR;
- $idx++;
- }
- }
-
- return str_replace(
- array(
- '{$buffer}',
- '{$imagesPath}',
- ),
- array(
- $buffer,
- $this->options['HTML_DIV_images_path']
- ),
- $this->options['HTML_DIV_sfWebDebugLog']
- );
- }
-
- /**
- * Get the log level of the debug info
- *
- * @author COil
- * @since V2.1.0 - 2 avr. 2007
- *
- * @param array debug row
- */
- protected function getLogInfoLevel($properties)
- {
- $level = PHP_DebugLine::INFO_LEVEL;
-
- switch ($properties['type']) {
- case PHP_DebugLine::TYPE_PAGEACTION:
- case PHP_DebugLine::TYPE_CREDITS:
- case PHP_DebugLine::TYPE_DUMP:
- case PHP_DebugLine::TYPE_WATCH:
- break;
-
- case PHP_DebugLine::TYPE_APPERROR:
- $level = PHP_DebugLine::ERROR_LEVEL;
- break;
-
- case PHP_DebugLine::TYPE_PHPERROR:
- $level = $this->getPhpErrorLevel($properties);
- break;
- }
-
- return $level;
- }
-
- /**
- * Return the global error level corresponding to the related php error
- * level
- *
- * @param array debug row
- *
- * @author COil
- * @since 2.1.0 - 3 apr 2007
- */
- protected function getPhpErrorLevel($properties)
- {
- $infos = $properties['info'];
-
- switch ($infos[0]) {
- case E_ERROR:
- case E_PARSE:
- case E_CORE_ERROR:
- case E_COMPILE_ERROR:
- case E_USER_ERROR:
- return PHP_DebugLine::ERROR_LEVEL;
- break;
-
- case E_WARNING:
- case E_CORE_WARNING:
- case E_NOTICE:
- case E_COMPILE_WARNING:
- case E_USER_WARNING:
- case E_USER_NOTICE:
- case E_ALL:
- case E_STRICT:
- case E_RECOVERABLE_ERROR:
- return PHP_DebugLine::WARNING_LEVEL;
- break;
-
- default:
- return PHP_DebugLine::ERROR_LEVEL;
- break;
- }
- }
-
- /**
- * Get the image info for the current debug type
- *
- * @author COil
- * @since V2.1.0 - 2 avp 2007
- */
- protected function getDebugLevelClass($debug_level)
- {
- return $this->options['HTML_DIV_debug_level_classes'][$debug_level];
- }
-
- /**
- * Get the image info for the current debug type
- *
- * @author COil
- * @since V2.1.0 - 2 avp 2007
- */
- protected function getImageInfo($debug_level)
- {
- $info = $this->options['HTML_DIV_image_info'];
- $warning = $this->options['HTML_DIV_image_warning'];
- $error = $this->options['HTML_DIV_image_error'];
-
- switch ($debug_level) {
- case PHP_DebugLine::INFO_LEVEL:
- $level = $info;
- break;
-
- case PHP_DebugLine::WARNING_LEVEL:
- $level = $warning;
- break;
-
- case PHP_DebugLine::ERROR_LEVEL:
- $level = $error;
- break;
- }
-
- return $level;
- }
-
- /**
- * Shows vars & config
- *
- * @author COil
- * @since V2.1.0 - 30 march 2007
- */
- protected function showVarsAndConfig($debugInfos)
- {
- return str_replace(
- array(
- '{$sfWebDebugRequest}',
- '{$sfWebDebugResponse}',
- '{$sfWebDebugSettings}',
- '{$sfWebDebugGlobals}',
- '{$sfWebDebugPhp}',
- '{$sfWebDebugFiles}',
- '{$imagesPath}',
- ),
- array(
- $this->showSuperArray(PHP_Debug::GLOBAL_REQUEST),
- $this->showSuperArray(PHP_Debug::GLOBAL_COOKIE),
- $this->showArray($this->settingsAsArray($debugInfos), 'Settings'),
- $this->showArray($this->globalsAsArray(), 'Globals'),
- $this->showArray($this->phpInfoAsArray(), 'PHP Infos'),
- $this->showTemplates(),
- $this->options['HTML_DIV_images_path'],
- ),
- $this->options['HTML_DIV_sfWebDebugConfig']
- );
- }
-
- /**
- * Return all settings of application
- *
- * @author COil
- * @since V2.1.0 - 2 apr 2007
- */
- public function settingsAsArray($debugInfos)
- {
- $settings = array();
- foreach($debugInfos as $debugInfo) {
- $infos = $debugInfo->getProperties();
- if (in_array($infos['type'], self::$settingsType)) {
- $settings[] = $infos['info'];
- }
- }
-
- return $settings;
- }
-
- /**
- * Returns PHP globals variables as a sorted array.
- *
- * @return array PHP globals
- * @since V2.1.0 - 2 apr 2007
- */
- public static function globalsAsArray()
- {
- $values = array();
- foreach (array('cookie', 'server', 'get', 'post', 'files', 'env', 'session') as $name) {
-
- if (!isset($GLOBALS['_'.strtoupper($name)])) {
- continue;
- }
-
- $values[$name] = array();
- foreach ($GLOBALS['_'. strtoupper($name)] as $key => $value) {
- $values[$name][$key] = $value;
- }
- ksort($values[$name]);
- }
-
- ksort($values);
-
- return $values;
- }
-
- /**
- * Returns PHP information as an array.
- *
- * @return array An array of php information
- * @since V2.1.0 - 2 apr 2007
- */
- public static function phpInfoAsArray()
- {
- $values = array(
- 'php' => phpversion(),
- 'os' => php_uname(),
- 'extensions' => get_loaded_extensions(),
- );
-
- // assign extension version if available
- if ($values['extensions']) {
- foreach ($values['extensions'] as $lkey => $extension) {
- $values['extensions'][$lkey] = phpversion($extension) ? $extension.
- ' ('. phpversion($extension). ')' : $extension;
- }
- }
-
- return $values;
- }
-
- /**
- * Add the process time information to the debug information
- *
- * @since V2.0.0 - 18 Apr 2006
- */
- protected function showProcessTime($debugInfos)
- {
- // Lang
- $txtExecutionTime = 'Global execution time ';
- $txtPHP = 'PHP';
- $txtSQL = 'SQL';
- $txtSECOND = 's';
- $txtOneQry = ' query';
- $txtMultQry = ' queries';
- $queryCount = $this->DebugObject->getQueryCount();
- $txtQuery = $queryCount > 1 ? $txtMultQry : $txtOneQry;
- $buffer = '';
-
- // Performance Debug
- $processTime = $this->DebugObject->getProcessTime();
- $sqlTime = $this->DebugObject->getQueryTime();
- $phpTime = $processTime - $sqlTime;
-
- $sqlPercent = round(($sqlTime / $processTime) * 100, 2);
- $phpPercent = round(($phpTime / $processTime) * 100, 2);
-
- $processTime = $processTime*1000;
- $sqlTime = $sqlTime*1000;
- $phpTime = $phpTime*1000;
-
- if ($debugInfos) {
- $buffer .= '
- <tr>
- <th>message</th>
- <th>time (ms)</th>
- <th>percent</th>
- </tr>'. CR;
-
- foreach($debugInfos as $debugInfo) {
- $properties = $debugInfo->getProperties();
- if ($properties['startTime'] && $properties['endTime']) {
-
- $localPercent = round((($properties['endTime'] -
- $properties['startTime'])*1000 / $processTime) * 100, 2);
- $buffer .= '
- <tr>
- <td class="sfWebDebugLogMessagePerf">'. $this->ProcessDebugInfo($properties). '</td>
- <td style="text-align: right">'. $this->ProcessExecTime($properties). '</td>
- <td style="text-align: right">'. $localPercent. '%</td>
- </tr>'. CR;
- }
- }
- }
-
- return str_replace(
- array(
- '{$txtExecutionTime}',
- '{$processTime}',
- '{$txtPHP}',
- '{$phpTime}',
- '{$phpPercent}',
- '{$txtSQL}',
- '{$sqlTime}',
- '{$sqlPercent}',
- '{$queryCount}',
- '{$txtQuery}',
- '{$buffer}'
-
- ),
- array(
- $txtExecutionTime,
- $processTime,
- $txtPHP,
- $phpTime,
- $phpPercent,
- $txtSQL,
- $sqlTime,
- $sqlPercent,
- $queryCount,
- $txtQuery,
- $buffer
- ),
- $this->options['HTML_DIV_sfWebDebugTimeDetails']
- );
- }
-
- /**
- * Default render function for HTML_Div renderer
- *
- * @since V2.0.0 - 11 Apr 2006
- * @see Renderer
- */
- public function render()
- {
- return $this->display();
- }
-
- /**
- * Displays the header of the PHP_Debug object
- *
- * @since V2.0.0 - 08 Apr 2006
- * @see PHP_Debug
- */
- protected function displayHeader()
- {
- return str_replace(
- array(
- '{$nb_queries}',
- '{$exec_time}',
- '{$imagesPath}',
- '{$phpDebugVersion}'
- ),
- array(
- $this->DebugObject->getQueryCount(),
- $this->DebugObject->getProcessTime() * 1000,
- $this->options['HTML_DIV_images_path'],
- PHP_Debug::PEAR_RELEASE
- ),
- $this->options['HTML_DIV_header']);
- }
-
- /**
- * Diplays the footer of the PHP_Debug object
- *
- * @since V2.0.0 - 08 Apr 2006
- * @see PHP_Debug
- */
- protected function displayFooter()
- {
- return $this->options['HTML_DIV_footer'];
- }
-
- /**
- * process display of the execution time of debug information
- *
- * @param array $properties Properties of the debug line
- * @return string Formatted string containing the main debug info
- * @since V2.0.0 - 28 Apr 2006
- */
- protected function processExecTime($properties)
- {
- // Lang
- $txtPHP = 'PHP';
- $txtSQL = 'SQL';
- $txtSECOND = 's';
-
- if (!empty($properties['endTime'])) {
-
- $time = round(PHP_Debug::getElapsedTime(
- $properties['startTime'],
- $properties['endTime']
- ) * 1000);
-
- $buffer = $this->span($time > 1 ? $time. ' ms' : '< 1 ms', 'time');
-
- } else {
- $buffer = ' ';
- }
-
- return $buffer;
- }
-
- /**
- * process display of the main information of debug
- *
- * @param array $properties Properties of the debug line
- * @return string Formatted string containing the main debug info
- * @since V2.0.0 - 28 Apr 2006
- */
- protected function processDebugInfo($properties)
- {
- $buffer = '';
-
- switch($properties['type']) {
-
- // Case for each of the debug lines types
- // 1 : Standard
- case PHP_DebugLine::TYPE_STD:
- $buffer .= $this->span($properties['info'], 'std');
- break;
-
- // 2 : Query
- case PHP_DebugLine::TYPE_QUERY:
- $buffer .= preg_replace('/\b(SELECT|FROM|AS|LIMIT|ASC|COUNT|DESC|WHERE|LEFT JOIN|INNER JOIN|RIGHT JOIN|ORDER BY|GROUP BY|IN|LIKE|DISTINCT|DELETE|INSERT|INTO|VALUES)\b/',
- '<span class="sfWebDebugLogInfo">\\1</span>',
- $properties['info']);
- break;
-
- // 3 : Query related
- case PHP_DebugLine::TYPE_QUERYREL:
- $buffer .= $this->span($properties['info'], 'query');
- break;
-
- // 4 : Environment
- case PHP_DebugLine::TYPE_ENV:
- $buffer .= $this->showSuperArray($properties['info']);
- break;
-
- // 6 : User app error
- case PHP_DebugLine::TYPE_APPERROR:
- $buffer .= $this->span('/!\\ User error : '.
- $properties['info']. ' /!\\', 'app-error');
- break;
-
- // 7
- case PHP_DebugLine::TYPE_CREDITS:
- $buffer .= $this->span($properties['info'], 'credits');
- break;
-
- // 9
- case PHP_DebugLine::TYPE_DUMP:
- $buffer .= $this->showDump($properties);
- break;
-
- // 10
- case PHP_DebugLine::TYPE_PROCESSPERF:
- $buffer .= $this->showProcessTime();
- break;
-
- // 12 : Main Page Action
- case PHP_DebugLine::TYPE_PAGEACTION;
- $buffer .= $this->span('[Action : '.
- $properties['info']. ']', 'pageaction');
- break;
-
- // 14 : SQL parse
- case PHP_DebugLine::TYPE_SQLPARSE:
- $buffer .= $properties['info'];
- break;
-
- // 15 : Watches
- case PHP_DebugLine::TYPE_WATCH:
- $infos = $properties['info'];
- $buffer .= 'Variable '. $this->span($infos[0], 'watch').
- ' changed from value '.
- $this->span($infos[1], 'watch-val'). ' ('. gettype($infos[1]).
- ') to value '. $this->span($infos[2], 'watch-val').
- ' ('. gettype($infos[2]). ')';
- break;
-
- // 16 : PHP errors
- case PHP_DebugLine::TYPE_PHPERROR:
- $buffer .= $this->showError($properties['info']);
- break;
-
- default:
- $buffer .= '<b>Default('. $properties['type'].
- ')</b>: TO IMPLEMENT OR TO CORRECT : >'.
- $properties['info']. '<';
- break;
- }
-
- return $buffer;
- }
-
- /**
- * Return a string with applying a span style on it
- *
- * @param string $info String to apply the style
- * @param string $class CSS style to apply to the string
- * @return string Formatted string with style applied
- * @since V2.0.0 - 05 May 2006
- */
- protected function span($info, $class)
- {
- return '<span class="'. $class .'">'. $info .'</span>';
- }
-
- /**
- * process display of the type of the debug information
- *
- * @param array $properties Properties of the debug line
- * @return string Formatted string containing the debug type
- * @since V2.0.0 - 26 Apr 2006
- */
- protected function processType($properties)
- {
- $buffer = PHP_DebugLine::$debugLineLabels[$properties['type']];
- return $buffer;
- }
-
- /**
- * process display of Class
- *
- * @param array $properties Properties of the debug line
- * @return string Formatted string containing the class
- * @since V2.0.0 - 26 Apr 2006
- */
- protected function processClass($properties)
- {
- $buffer = '';
-
- switch ($properties['type'])
- {
- case PHP_DebugLine::TYPE_STD:
- case PHP_DebugLine::TYPE_QUERY:
- case PHP_DebugLine::TYPE_QUERYREL:
- case PHP_DebugLine::TYPE_APPERROR:
- case PHP_DebugLine::TYPE_PAGEACTION:
- case PHP_DebugLine::TYPE_PHPERROR:
- case PHP_DebugLine::TYPE_SQLPARSE:
- case PHP_DebugLine::TYPE_WATCH:
- case PHP_DebugLine::TYPE_DUMP:
-
- if (!empty($properties['class'])) {
- $buffer .= $properties['class'];
- } else {
- $buffer .= ' ';
- }
-
- break;
-
- case PHP_DebugLine::TYPE_CREDITS:
- case PHP_DebugLine::TYPE_SEARCH:
- case PHP_DebugLine::TYPE_PROCESSPERF:
- case PHP_DebugLine::TYPE_TEMPLATES:
- case PHP_DebugLine::TYPE_ENV:
-
- $buffer .= ' ';
-
- break;
-
- default:
- break;
- }
-
- return $buffer;
- }
-
- /**
- * process display of function
- *
- * @param array $properties Properties of the debug line
- * @return string Formatted string containing the function
- * @since V2.0.0 - 26 Apr 2006
- */
- protected function processFunction($properties)
- {
- $buffer = '';
-
- switch ($properties['type'])
- {
- case PHP_DebugLine::TYPE_STD:
- case PHP_DebugLine::TYPE_QUERY:
- case PHP_DebugLine::TYPE_QUERYREL:
- case PHP_DebugLine::TYPE_APPERROR:
- case PHP_DebugLine::TYPE_PAGEACTION:
- case PHP_DebugLine::TYPE_PHPERROR:
- case PHP_DebugLine::TYPE_SQLPARSE:
- case PHP_DebugLine::TYPE_WATCH:
- case PHP_DebugLine::TYPE_DUMP:
-
- if (!empty($properties['function'])) {
- if ($properties['function'] != 'unknown') {
- $buffer .= $properties['function']. '()';
- } else {
- $buffer .= ' ';
- }
- } else {
- $buffer .= ' ';
- }
-
- break;
-
- case PHP_DebugLine::TYPE_CREDITS:
- case PHP_DebugLine::TYPE_SEARCH:
- case PHP_DebugLine::TYPE_PROCESSPERF:
- case PHP_DebugLine::TYPE_TEMPLATES:
- case PHP_DebugLine::TYPE_ENV:
-
- $buffer .= ' ';
- break;
-
- default:
- break;
- }
-
- return $buffer;
- }
-
-
- /**
- * process display of line number
- *
- * @param array $properties Properties of the debug line
- * @return string Formatted string containing the line number
- * @since V2.0.0 - 26 Apr 2006
- */
- protected function processLine($properties)
- {
- $buffer = '';
-
- switch ($properties['type'])
- {
- case PHP_DebugLine::TYPE_STD:
- case PHP_DebugLine::TYPE_QUERY:
- case PHP_DebugLine::TYPE_QUERYREL:
- case PHP_DebugLine::TYPE_APPERROR:
- case PHP_DebugLine::TYPE_PAGEACTION:
- case PHP_DebugLine::TYPE_PHPERROR:
- case PHP_DebugLine::TYPE_SQLPARSE:
- case PHP_DebugLine::TYPE_WATCH:
- case PHP_DebugLine::TYPE_DUMP:
-
- if (!empty($properties['line'])) {
- $buffer.= '<span class="line">'.
- $properties['line']. '</span>';
- } else {
- $buffer.= ' ';
- }
-
- break;
-
- case PHP_DebugLine::TYPE_CREDITS:
- case PHP_DebugLine::TYPE_SEARCH:
- case PHP_DebugLine::TYPE_PROCESSPERF:
- case PHP_DebugLine::TYPE_TEMPLATES:
- case PHP_DebugLine::TYPE_ENV:
-
- $buffer.= ' ';
-
- break;
-
- default:
- break;
- }
-
- return $buffer;
- }
-
- /**
- * process display of file name
- *
- * @param array $properties Properties of the debug line
- * @return string Formatted string containing the file
- * @since V2.0.0 - 26 Apr 2006
- */
- protected function processFile($properties)
- {
- $buffer = '';
-
- switch ($properties['type'])
- {
- case PHP_DebugLine::TYPE_STD:
- case PHP_DebugLine::TYPE_QUERY:
- case PHP_DebugLine::TYPE_QUERYREL:
- case PHP_DebugLine::TYPE_APPERROR:
- case PHP_DebugLine::TYPE_PAGEACTION:
- case PHP_DebugLine::TYPE_PHPERROR:
- case PHP_DebugLine::TYPE_SQLPARSE:
- case PHP_DebugLine::TYPE_WATCH:
- case PHP_DebugLine::TYPE_DUMP:
-
- if (!empty($properties['file'])) {
- if (!empty($this->options['HTML_DIV_view_source_script_path']) &&
- !empty($this->options['HTML_DIV_view_source_script_name'])) {
- $buffer .= '<a href="'.
- $this->options['HTML_DIV_view_source_script_path'].
- '/'.
- $this->options['HTML_DIV_view_source_script_name'].
- '?file='. urlencode($properties['file']);
-
- $buffer .= '">'. basename($properties['file']). '</a>';
-
- } else {
- $buffer .= basename($properties['file']);
- }
- } else {
- $buffer .= ' ';
- }
-
- break;
-
- case PHP_DebugLine::TYPE_CREDITS:
- case PHP_DebugLine::TYPE_SEARCH:
- case PHP_DebugLine::TYPE_PROCESSPERF:
- case PHP_DebugLine::TYPE_TEMPLATES:
- case PHP_DebugLine::TYPE_ENV:
-
- $buffer .= ' ';
-
- break;
-
- default:
- break;
- }
-
- return $buffer;
- }
-
- /**
- * Dump of a variable
- *
- * @since V2.0.0 - 26 Apr 2006
- */
- protected function showDump($properties)
- {
- $buffer = '';
-
- // Check display with a <pre> design
- if (is_array($properties['info'][1])) {
- $preDisplay = true;
- } elseif (is_object($properties['info'][1])) {
- $preDisplay = true;
- } else {
- $preDisplay = false;
- }
-
- // Check var name
- if (empty($properties['info'][0])) {
- if (is_array($properties['info'][1])) {
- $varName = 'Array';
- } elseif (is_object($properties['info'][1])) {
- $varName = get_class($properties['info'][1]);
- } else {
- $varName = 'Variable';
- }
- } else {
- $varName = $properties['info'][0];
- }
-
- // Output
- if ($properties['type'] != PHP_DebugLine::TYPE_ENV) {
- $title = 'dump of \'';
- }
-
- $title .= $varName. '\' ('. gettype($properties['info'][1]) .') : ';
-
- $buffer .= $this->span($title , 'dump-title');
-
- if ($preDisplay == true){
- $buffer .= '<pre>';
- $buffer .= PHP_Debug::dumpVar(
- $properties['info'][1],
- '',
- false,
- PHP_Debug::DUMP_STR);
- } else {
- $buffer .= $this->span(
- PHP_Debug::dumpVar(
- $properties['info'][1],
- '',
- false,
- PHP_Debug::DUMP_STR
- ), 'dump-val');
- }
-
- if ($preDisplay == true) {
- $buffer .= '</pre>';
- }
-
- return $buffer;
- }
-
- /**
- * Get the templates info
- *
- * @since V2.0.0 - 26 Apr 2006
- */
- protected function showTemplates()
- {
- $txtMainFile = 'MAIN File';
- $idx = 1;
- $buffer = '<br />';
-
- foreach($this->DebugObject->getRequiredFiles() as $lvalue) {
-
- $isToDisplay = true;
-
- if ($this->options['HTML_DIV_view_source_excluded_template']) {
- foreach ($this->options['HTML_DIV_view_source_excluded_template'] as $template) {
- if (stristr($lvalue, $template)) {
- $isToDisplay = false;
- }
- }
- }
-
- if ($isToDisplay == true) {
-
- $buffer .= '<div class="source">';
- $buffer .= $this->span($this->truncate($lvalue), 'files');
- $buffer .= ' <a href="'.
- $this->options['HTML_DIV_view_source_script_path'].
- '/'. $this->options['HTML_DIV_view_source_script_name'].
- '?file='. urlencode($lvalue). '">View source</a> ';
-
- // main file
- if ($idx == 1) {
- $buffer .= $this->span('« '. $txtMainFile, 'main-file');
- }
- $idx++;
- $buffer .= '</div><br />'. CR;
- }
- }
-
- $buffer .= '<br />'. CR;
- return $buffer;
- }
-
-
- /**
- * Truncate/replace a pattern from the file path
- *
- * @param string full file path
- *
- * @author COil
- * @since V2.1.0 - 3 apr 2007
- *
- * @see
- * - HTML_DIV_remove_templates_pattern
- * - HTML_DIV_templates_pattern
- */
- protected function truncate($file)
- {
- if ($this->options['HTML_DIV_remove_templates_pattern'] &&
- $this->options['HTML_DIV_templates_pattern']) {
- return strtr($file, $this->options['HTML_DIV_templates_pattern']);
- }
-
- return $file;
- }
-
- /**
- * Process an error info
- *
- * @param array $info Array containing information about the error
- *
- * @since V2.0.0 - 25 Apr 2006
- * @see PHP_DebugLine::TYPE_PHPERROR
- */
- protected function showError($infos)
- {
- $buffer = '';
- $infos[1] = str_replace("'", '"', $infos[1]);
- $infos[1] = str_replace(
- 'href="function.',
- ' href="http://www.php.net/'.
- $this->options['lang']. '/', $infos[1]);
-
- switch ($infos[0])
- {
- case E_WARNING:
- $errorlevel = 'PHP WARNING : ';
- $buffer .= '<span class="pd-php-warning"> /!\\ '.
- $errorlevel. $infos[1] . ' /!\\ </span>';
- break;
-
- case E_NOTICE:
- $errorlevel = 'PHP notice : ';
- $buffer .= '<span class="pd-php-notice">'.
- $errorlevel. $infos[1] . '</span>';
- break;
-
- case E_USER_ERROR:
- $errorlevel = 'PHP User error : ';
- $buffer .= '<span class="pd-php-user-error"> /!\\ '.
- $errorlevel. $infos[1] . ' /!\\ </span>';
- break;
-
- case E_STRICT:
-
- $errorlevel = 'PHP STRICT error : ';
- $buffer .= '<span class="pd-php-user-error"> /!\\ '.
- $errorlevel. $infos[1] . ' /!\\ </span>';
- break;
-
- default:
- $errorlevel = 'PHP errorlevel = '. $infos[0]. ' : ';
- $buffer .= $errorlevel.
- ' is not implemented in PHP_Debug ('. __FILE__. ','. __LINE__. ')';
- break;
- }
-
- return $buffer;
- }
-
- /**
- * Show a super array
- *
- * @param string $SuperArrayType Type of super en array to add
- * @since V2.0.0 - 07 Apr 2006
- */
- protected function showSuperArray($SuperArrayType)
- {
- // Lang
- $txtVariable = 'Var';
- $txtNoVariable = 'NO VARIABLE';
- $NoVariable = ' -- '. $txtNoVariable. ' -- ';
- $SuperArray = null;
- $buffer = '';
-
- $ArrayTitle = PHP_Debug::$globalEnvConstantsCorresp[$SuperArrayType];
- $SuperArray = $GLOBALS[$ArrayTitle];
- $Title = $ArrayTitle. ' '. $txtVariable;
- $SectionBasetitle = '<b>'. $Title. '('. count($SuperArray). ') :';
-
- if (count($SuperArray)) {
- $buffer .= $SectionBasetitle. '</b>';
- $buffer .= '<pre>'.
- PHP_Debug::dumpVar(
- $SuperArray,
- $ArrayTitle,
- false,
- PHP_Debug::DUMP_STR
- ). '</pre>';
- } else {
- $buffer .= $SectionBasetitle. $NoVariable. '</b>';
- }
-
- return $buffer;
- }
-
- /**
- * Show a super array
- *
- * @param string $SuperArrayType Type of super en array to add
- * @since V2.0.0 - 07 Apr 2006
- */
- protected function showArray($array, $name)
- {
- // Lang
- $txtNoVariable = 'NO VARIABLE';
- $NoVariable = ' -- '. $txtNoVariable. ' -- ';
- $buffer = '';
- $SectionBasetitle = '<b>'. $name. '('. count($array). ') :';
-
- if (count($array)) {
- $buffer .= $SectionBasetitle. '</b>';
- $buffer .= '<pre>'. PHP_Debug::dumpVar(
- $array,
- $name,
- false,
- PHP_Debug::DUMP_STR). '</pre>';
- } else {
- $buffer .= $SectionBasetitle. $NoVariable. '</b>';
- }
-
- return $buffer;
- }
-
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/**
- * Configuration file for HTML_Div renderer
- *
- * @package PHP_Debug
- * @category PHP
- * @author Loïc Vernet <qrf_coil at yahoo dot fr>
- * @since V2.1.0 - 29 march 2007
- *
- * @package PHP_Debug
- * @filesource
- */
-
-class PHP_Debug_Renderer_HTML_DivConfig
-{
- /**
- * Config container for Debug_Renderer_HTML_Div
- *
- * @var array
- * @since V2.0.0 - 11 apr 2006
- */
- protected static $options = array();
-
- /**
- * Static Instance of class
- *
- * @var array
- * @since V2.0.0 - 11 apr 2006
- */
- protected static $instance = null;
-
- /**
- * Debug_Renderer_HTML_DIV_Config class constructor
- *
- * @since V2.0.0 - 11 apr 2006
- */
- protected function __construct()
- {
- /**
- * Enable or disable Credits in debug infos
- */
- self::$options['HTML_DIV_disable_credits'] = false;
-
- /**
- * Enable or disable pattern removing in included files
- */
- self::$options['HTML_DIV_remove_templates_pattern'] = false;
-
- /**
- * Pattern list to remove in the display of included files
- * if HTML_DIV_remove_templates_pattern is set to true
- */
- self::$options['HTML_DIV_templates_pattern'] = array();
-
- /**
- * View Source script path
- */
- self::$options['HTML_DIV_view_source_script_path'] = '.';
-
- /**
- * View source script file name
- */
- self::$options['HTML_DIV_view_source_script_name'] = 'PHP_Debug_ShowSource.php';
-
- /**
- * Tabsize for view source script
- */
- self::$options['HTML_DIV_view_source_tabsize'] = 4;
-
- /**
- * Tabsize for view source script
- */
- self::$options['HTML_DIV_view_source_numbers'] = 2; //HL_NUMBERS_TABLE
-
- /**
- * images
- */
- self::$options['HTML_DIV_images_path'] = 'images';
- self::$options['HTML_DIV_image_info'] = 'info.png';
- self::$options['HTML_DIV_image_warning'] = 'warning.png';
- self::$options['HTML_DIV_image_error'] = 'error.png';
-
- /**
- * css path
- */
- self::$options['HTML_DIV_css_path'] = 'css';
-
- /**
- * js path
- */
- self::$options['HTML_DIV_js_path'] = 'js';
-
- /**
- * Class name of the debug info levels
- */
- self::$options['HTML_DIV_debug_level_classes'] = array(
- PHP_DebugLine::INFO_LEVEL => 'sfWebDebugInfo',
- PHP_DebugLine::WARNING_LEVEL => 'sfWebDebugWarning',
- PHP_DebugLine::ERROR_LEVEL => 'sfWebDebugError',
- );
-
- /**
- * After this goes all HTML related variables
- *
- * HTML code for header
- */
- self::$options['HTML_DIV_header'] = '
-<div id="sfWebDebug">
-
- <div id="sfWebDebugBar" class="sfWebDebugInfo">
- <div id="title">
- <a href="#" onclick="sfWebDebugToggleMenu(); return false;"><b>» PHP_Debug</b></a>
- </div>
- <ul id="sfWebDebugDetails" class="menu">
- <li>{$phpDebugVersion}</li>
- <li><a href="#" onclick="sfWebDebugShowDetailsFor(\'sfWebDebugConfig\'); return false;"><img src="{$imagesPath}/config.png" alt="Config" /> vars & config</a></li>
- <li><a href="#" onclick="sfWebDebugShowDetailsFor(\'sfWebDebugLog\'); return false;"><img src="{$imagesPath}/comment.png" alt="Comment" /> logs & msgs</a></li>
- <li><a href="#" onclick="sfWebDebugShowDetailsFor(\'sfWebDebugDatabaseDetails\'); return false;"><img src="{$imagesPath}/database.png" alt="Database" /> {$nb_queries}</a></li>
- <li><a href="#" onclick="sfWebDebugShowDetailsFor(\'sfWebDebugW3CDetails\'); return false;">W3C</a></li>
- <li class="last"><a href="#" onclick="sfWebDebugShowDetailsFor(\'sfWebDebugTimeDetails\'); return false;"><img src="{$imagesPath}/time.png" alt="Time" /> {$exec_time} ms</a></li>
- </ul>
- <a href="#" onclick="document.getElementById(\'sfWebDebug\').style.display=\'none\'; return false;"><img src="{$imagesPath}/close.png" alt="Close" /></a>
- </div> <!-- End sfWebDebugBar -->
-
-';
-
- /**
- * HTML code for validation debug tab
- */
- self::$options['HTML_DIV_sfWebDebugW3CDetails'] = '
-
- <div id="sfWebDebugW3CDetails" class="top" style="display:none">
- <h1>W3C validation</h1>
- <p>Click on the WC3 logo to verify the validation or to check the errors</p>
- <p>
- <a href="http://validator.w3.org/check?uri=referer"><img
- src="{$imagesPath}/w3c_home_nb.png"
- alt="W3C Validator" /></a>
- </p>
- {$results}
- or copy paste the source here <a href="http://validator.w3.org/#validate_by_input">http://validator.w3.org/#validate_by_input</a>
-
- </div> <!-- End sfWebDebugW3CDetails -->
-
-';
-
- /**
- * HTML code for a row of a validation error
- */
- self::$options['HTML_DIV_sfWebDebugW3CTableHeader'] = '
- <h2>{$title}</h2>
- <table class="sfWebDebugLogs" style="width:600px">
- <tr>
- <th>n°</th>
- <th>Line</th>
- <th>Col</th>
- <th>Message</th>
- </tr>
-';
-
- /**
- * HTML code for a row of a validation error
- */
- self::$options['HTML_DIV_sfWebDebugW3CErrorRow'] = '
- <tr class="sfWebDebugLogLine {$type}">
- <td class="sfWebDebugLogNumber">{$cpt}</td>
- <td class="sfWebDebugLogLine">{$line}</td>
- <td class="sfWebDebugLogCol">{$col}</td>
- <td class="sfWebDebugLogMessage">
- {$message}
- </td>
- </tr>
-';
-
- /**
- * HTML code for debug time tab
- */
- self::$options['HTML_DIV_sfWebDebugTimeDetails'] = '
-
- <div id="sfWebDebugTimeDetails" class="top" style="display: none">
- <h1>Timers</h1>
- <table class="sfWebDebugLogs" style="width: 300px">
- <tr>
- <th>type</th>
- <th>time (ms)</th>
- <th>percent</th>
- </tr>
- <tr>
- <td class="sfWebDebugLogTypePerf">{$txtExecutionTime}</td>
- <td style="text-align: right">{$processTime}</td>
- <td style="text-align: right">100%</td>
- </tr>
- <tr>
- <td class="sfWebDebugLogTypePerf">{$txtPHP}</td>
- <td style="text-align: right">{$phpTime}</td>
- <td style="text-align: right">{$phpPercent}%</td>
- </tr>
- <tr>
- <td class="sfWebDebugLogTypePerf">{$txtSQL}</td>
- <td style="text-align: right">{$sqlTime}</td>
- <td style="text-align: right">{$sqlPercent}% : {$queryCount} {$txtQuery}</td>
- </tr>
- {$buffer}
- </table>
- </div> <!-- End sfWebDebugTimeDetails -->
-
-';
-
- /**
- * HTML code for database tab
- */
- self::$options['HTML_DIV_sfWebDebugDatabaseDetails'] = '
-
- <div id="sfWebDebugDatabaseDetails" class="top" style="display: none">
- <h1>Database / SQL queries</h1>
-
- <div id="sfWebDebugDatabaseLogs">
- <ol>
- {$buffer}
- </ol>
- </div>
-
- </div> <!-- End sfWebDebugDatabaseDetails -->
-
-';
-
- /**
- * HTML code for Log & msg tab
- */
- self::$options['HTML_DIV_sfWebDebugLog'] = '
-
- <div id="sfWebDebugLog" class="top" style="display: none"><h1>Log and debug messages</h1>
- <ul id="sfWebDebugLogMenu">
- <li><a href="#" onclick="sfWebDebugToggleAllLogLines(true, \'sfWebDebugLogLine\'); return false;">[all]</a></li>
- <li><a href="#" onclick="sfWebDebugToggleAllLogLines(false, \'sfWebDebugLogLine\'); return false;">[none]</a></li>
- <li><a href="#" onclick="sfWebDebugShowOnlyLogLines(\'info\'); return false;"><img src="{$imagesPath}/info.png" alt="Info" /></a></li>
- <li><a href="#" onclick="sfWebDebugShowOnlyLogLines(\'warning\'); return false;"><img src="{$imagesPath}/warning.png" alt="Warning" /></a></li>
- <li><a href="#" onclick="sfWebDebugShowOnlyLogLines(\'error\'); return false;"><img src="{$imagesPath}/error.png" alt="Error" /></a></li>
- </ul>
-
- <div id="sfWebDebugLogLines">
- <table class="sfWebDebugLogs">
- <tr>
- <th>#</th>
- <th>type</th>
- <th>file</th>
- <th>line</th>
- <th>class</th>
- <th>function</th>
- <th>time</th>
- <th>message</th>
- </tr>
- {$buffer}
- </table>
- </div>
- </div> <!-- End sfWebDebugLog -->
-
-';
-
- /**
- * HTML code for Vars & config tab
- */
- self::$options['HTML_DIV_sfWebDebugConfig'] = '
-
- <div id="sfWebDebugConfig" class="top" style="display: none">
- <h1>Configuration and request variables</h1>
-
- <h2>Request <a href="#" onclick="sfWebDebugToggle(\'sfWebDebugRequest\'); return false;"><img src="{$imagesPath}/toggle.gif" alt="Toggle" /></a></h2>
-
- <div id="sfWebDebugRequest" style="display: none">
-{$sfWebDebugRequest}
- </div>
-
- <h2>Response <a href="#" onclick="sfWebDebugToggle(\'sfWebDebugResponse\'); return false;"><img src="{$imagesPath}/toggle.gif" alt="Toggle" /></a></h2>
- <div id="sfWebDebugResponse" style="display: none">
-{$sfWebDebugResponse}
- </div>
-
- <h2>Settings <a href="#" onclick="sfWebDebugToggle(\'sfWebDebugSettings\'); return false;"><img src="{$imagesPath}/toggle.gif" alt="Toggle" /></a></h2>
- <div id="sfWebDebugSettings" style="display: none">
-{$sfWebDebugSettings}
- </div>
-
- <h2>Globals <a href="#" onclick="sfWebDebugToggle(\'sfWebDebugGlobals\'); return false;"><img src="{$imagesPath}/toggle.gif" alt="Toggle" /></a></h2>
- <div id="sfWebDebugGlobals" style="display: none">
-{$sfWebDebugGlobals}
- </div>
-
- <h2>Php <a href="#" onclick="sfWebDebugToggle(\'sfWebDebugPhp\'); return false;"><img src="{$imagesPath}/toggle.gif" alt="Toggle" /></a></h2>
- <div id="sfWebDebugPhp" style="display: none">
-{$sfWebDebugPhp}
- </div>
-
- <h2>Files <a href="#" onclick="sfWebDebugToggle(\'sfWebDebugFiles\'); return false;"><img src="{$imagesPath}/toggle.gif" alt="Toggle" /></a></h2>
- <div id="sfWebDebugFiles" style="display: none">
-{$sfWebDebugFiles}
- </div>
-
- </div> <!-- End sfWebDebugConfig -->
-
-';
-
- /**
- * HTML code for credits
- */
- self::$options['HTML_DIV_credits'] = '
- PHP_Debug ['. PHP_Debug::PEAR_RELEASE .'] | By COil (2008) |
- <a href="http://www.coilblog.com">http://www.coilblog.com</a> |
- <a href="http://phpdebug.sourceforge.net/">PHP_Debug Project Home</a> |
- Idea from <a href="http://www.symfony-framework.com/">symfony framework</a>
- ';
-
- /**
- * HTML code for a basic header
- */
- self::$options['HTML_DIV_simple_header'] = '<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE html
- PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
- <head>
- <title>Pear::PHP_Debug</title>
-
-';
-
- /**
- * HTML code for a basic footer
- */
- self::$options['HTML_DIV_simple_footer'] = '
-</body>
-</html>
-
-';
-
- /**
- * HTML code for footer
- */
- self::$options['HTML_DIV_footer'] = '
-
-</div> <!-- End div sfWebDebug -->
-
-';
-
- }
-
- /**
- * returns the static instance of the class
- *
- * @since V2.0.0 - 11 apr 2006
- * @see PHP_Debug
- */
- public static function singleton()
- {
- if (!isset(self::$instance)) {
- $class = __CLASS__;
- self::$instance = new $class;
- }
- return self::$instance;
- }
-
- /**
- * returns the configuration
- *
- * @since V2.0.0 - 07 apr 2006
- * @see PHP_Debug
- */
- public static function getConfig()
- {
- return self::$options;
- }
-
- /**
- * HTML_DIV_Config
- *
- * @since V2.0.0 - 26 Apr 2006
- */
- public function __toString()
- {
- return '<pre>'. PHP_Debug::dumpVar(
- $this->singleton()->getConfig(),
- __CLASS__,
- false,
- PHP_DEBUG_DUMP_ARR_STR). '</pre>';
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/**
- * Class of the HTML_Table renderer
- */
-require_once 'PHP/Debug/Renderer/HTML/TableConfig.php';
-
-/**
- * A concrete renderer for Debug
- *
- * Returns a table-based representation of the debug infos in HTML 4
- *
- * @package PHP_Debug
- * @category PHP
- * @author Loic Vernet <qrf_coil at yahoo dot fr>
- * @since V2.0.0 - 10 Apr 2006
- *
- * @package PHP_Debug
- * @filesource
- */
-
-class PHP_Debug_Renderer_HTML_Table extends PHP_Debug_Renderer_Common
-{
- /**
- * Debug_Renderer_HTML_Table class constructor
- *
- * @since V2.0.0 - 13 apr 2006
- */
- function __construct($DebugObject, $options)
- {
- $this->DebugObject = $DebugObject;
- $this->defaultOptions = PHP_Debug_Renderer_HTML_TableConfig::singleton()->getConfig();
- $this->setOptions($options);
-
- // Now add in first the predefined debugline depending on the configuration
- if ($this->options['HTML_TABLE_enable_search'] == true)
- $this->DebugObject->addDebugFirst('', PHP_DebugLine::TYPE_SEARCH);
-
- if ($this->options['HTML_TABLE_disable_credits'] == false)
- $this->DebugObject->addDebugFirst(
- $this->options['HTML_TABLE_credits'],
- PHP_DebugLine::TYPE_CREDITS);
-
- // Now add in last positions the others predefined debuglines
-
- // Add execution time
- $this->DebugObject->addDebug('', PHP_DebugLine::TYPE_PROCESSPERF);
-
- // Add templates
- if ($this->options['HTML_TABLE_show_templates'] == true)
- $this->DebugObject->addDebug(STR_N, PHP_DebugLine::TYPE_TEMPLATES);
-
- // Add env variables
- $this->addSuperArray();
-
- }
-
- /**
- * This is the function to display the debug information
- *
- * @since V2.0.0 - 07 Apr 2006
- * @see PHP_Debug::Render()
- */
- public function display()
- {
- $buffer = '';
-
- // Header
- $buffer .= $this->displayHeader();
-
- // Body
- foreach ($this->DebugObject->getDebugBuffer() as $lvalue) {
-
- // Check if the debug must be displayed
- if ($this->checkType($lvalue) == true) {
-
- $tmpBuff = $this->displayDebugLine($lvalue);
-
- // Check if we have a search criteria
- if ($this->checkSearch($tmpBuff)) {
-
- // Pre-row
- $buffer .= $this->options['HTML_TABLE_prerow'];
-
- // Row body
- $buffer .= $this->highlight($tmpBuff);
-
- // Post-row
- $buffer .= $this->options['HTML_TABLE_postrow'];
-
- }
- }
- }
-
- // Footer
- $buffer .= $this->displayFooter();
-
- // Output Buffer
- echo $buffer;
- }
-
- /**
- * This function highligth the searched keyword
- *
- * @param string $debugLineStr The formatted debug line object to check
- * @return string Formatted string with keyword highligthed
- *
- * @since V2.0.0 - 2 May 2006
- */
- protected function highlight($debugLineStr)
- {
- // Check if search is activated
- if (!empty($_GET['PHPDEBUG_SEARCH']) &&
- trim($_GET['PHPDEBUG_SEARCH']) != '') {
- if (!empty($_GET['PHPDEBUG_SEARCH_CS'])) {
- $replaceFunction = 'str_replace';
- } else {
- $replaceFunction = 'str_ireplace';
- }
- return $replaceFunction($_GET['PHPDEBUG_SEARCH'],
- '<span class="pd-search-hl">'. $_GET['PHPDEBUG_SEARCH'].
- '</span>' , $debugLineStr);
- } else {
- return $debugLineStr;
- }
- }
-
- /**
- * This function check if the user has chosen a search criteria and
- * make the search on the formatted debug info
- *
- * @param string $debugLineStr The formatted debug line object to check
- * @return boolean Search criteria has been found of search is disabled
- *
- * @since V2.0.0 - 2 May 2006
- */
- protected function checkSearch($debugLineStr)
- {
- // Check if search is activated
- if (!empty($_GET['PHPDEBUG_SEARCH']) &&
- trim($_GET['PHPDEBUG_SEARCH']) != '') {
-
- if (!empty($_GET['PHPDEBUG_SEARCH_CS'])) {
- $searchFunction = 'strstr';
- } else {
- $searchFunction = 'stristr';
- }
- return $searchFunction($debugLineStr, trim($_GET['PHPDEBUG_SEARCH']));
- } else {
- return true;
- }
- }
-
- /**
- * This function check if the user has chosen a filter in the debug type
- * combobox and it returns of the debug line is allowed to be output or no
- *
- * @param DebugLine $debugLine The debug line object to check
- * @return boolean true type is allowed to be
- *
- * @since V2.0.0 - 26 Apr 2006
- */
- protected function checkType($debugLine)
- {
- $properties = $debugLine->getProperties();
-
- // Check if we must only show debug information of a kind
- if ($this->options['HTML_TABLE_search_forced_type'][$properties['type']] == false) {
- if (!empty($_GET['PHPDEBUG_SEARCH_TYPE'])) {
- if ($properties['type'] == $_GET['PHPDEBUG_SEARCH_TYPE']) {
- return true;
- } else {
- return false;
- }
- } else {
- return true;
- }
- } else {
- return true;
- }
- }
-
- /**
- * Default render function for HTML_Table renderer
- *
- * @since V2.0.0 - 11 Apr 2006
- * @see Renderer
- */
- public function render()
- {
- $this->display();
- }
-
- /**
- * Displays the header of the PHP_Debug object
- *
- * @since V2.0.0 - 08 Apr 2006
- * @see PHP_Debug
- */
- protected function displayHeader()
- {
- return $this->options['HTML_TABLE_header'];
- }
-
- /**
- * Diplays the footer of the PHP_Debug object
- *
- * @since V2.0.0 - 08 Apr 2006
- * @see PHP_Debug
- */
- protected function displayFooter()
- {
- return $this->options['HTML_TABLE_footer'];
- }
-
- /**
- * This is the function that displays a debug line, each step correspond
- * to a new cell, actully there are 6 types :
- * - File
- * - Line
- * - Function
- * - Class
- * - Debug main information
- * - Execution time
- *
- * @param DebugLine DebugLine, the debug line to process
- *
- * @since V2.0.0 - 07 Apr 2006
- */
- protected function displayDebugLine($DebugLine)
- {
- // DebugLine properties
- $properties = $DebugLine->getProperties();
-
- // 1 - File
- $buffer = $this->processFile($properties);
-
- // 2 - Line
- $buffer .= $this->processLine($properties);
-
- // 3 - Function
- $buffer .= $this->processFunction($properties);
-
- // 4 - Class
- $buffer .= $this->processClass($properties);
-
- // 5 - Type
- $buffer .= $this->processType($properties);
-
- // 6 - Debug info
- $buffer .= $this->processDebugInfo($properties);
-
- // 7 - Execution time
- $buffer .= $this->processExecTime($properties);
-
- // Output display buffer
- return $buffer;
-
- }
-
- /**
- * process display of the execution time of debug information
- *
- * @param array $properties Properties of the debug line
- * @return string Formatted string containing the main debug info
- * @since V2.0.0 - 28 Apr 2006
- */
- protected function processExecTime($properties)
- {
- // Lang
- $txtPHP = 'PHP';
- $txtSQL = 'SQL';
- $txtSECOND = 's';
- $buffer = $this->options['HTML_TABLE_interrow_time'];
-
- if (!empty($properties['endTime'])) {
- $buffer .= $this->span(PHP_Debug::getElapsedTime(
- $properties['startTime'],
- $properties['endTime']),
- 'time');
- } else {
- $buffer .= ' ';
- }
-
- return $buffer;
- }
-
- /**
- * process display of the main information of debug
- *
- * @param array $properties Properties of the debug line
- * @return string Formatted string containing the main debug info
- * @since V2.0.0 - 28 Apr 2006
- */
- protected function processDebugInfo($properties)
- {
-
- switch($properties['type'])
- {
- // Case for each of the debug lines types
- // 1 : Standard
- case PHP_DebugLine::TYPE_STD:
- $buffer = $this->options['HTML_TABLE_interrow_info'];
- $buffer .= $this->span($properties['info'], 'std');
- break;
-
- // 2 : Query
- case PHP_DebugLine::TYPE_QUERY:
- $buffer = $this->options['HTML_TABLE_interrow_info'];
- $buffer .= $this->span($properties['info'], 'query');
- break;
-
- // 3 : Query related
- case PHP_DebugLine::TYPE_QUERYREL:
- $buffer = $this->options['HTML_TABLE_interrow_info'];
- $buffer .= $this->span($properties['info'], 'query');
- break;
-
- // 4 : Environment
- case PHP_DebugLine::TYPE_ENV:
- $buffer = $this->options['HTML_TABLE_interrow_info'];
- $buffer .= $this->showSuperArray($properties['info']);
- break;
-
- // 6 : User app error
- case PHP_DebugLine::TYPE_APPERROR:
- $buffer = $this->options['HTML_TABLE_interrow_info'];
- $buffer .= $this->span('/!\\ User error : '.
- $properties['info'] . ' /!\\', 'app-error');
- break;
-
- // 7
- case PHP_DebugLine::TYPE_CREDITS:
- $buffer = $this->options['HTML_TABLE_interrow_info'];
- $buffer .= $this->span($properties['info'], 'credits');
- break;
-
- // 8
- case PHP_DebugLine::TYPE_SEARCH:
- $buffer = $this->options['HTML_TABLE_interrow_info'];
- $buffer .= $this->showSearch();
- break;
-
- // 9
- case PHP_DebugLine::TYPE_DUMP:
- $buffer = $this->options['HTML_TABLE_interrow_info'];
- $buffer .= $this->showDump($properties);
- break;
-
- // 10
- case PHP_DebugLine::TYPE_PROCESSPERF:
- $buffer = $this->options['HTML_TABLE_interrow_info'];
- $buffer .= $this->showProcessTime();
- break;
-
- // 11
- case PHP_DebugLine::TYPE_TEMPLATES:
- $buffer = $this->options['HTML_TABLE_interrow_info'];
- $buffer .= $this->showTemplates();
- break;
-
- // 12 : Main Page Action
- case PHP_DebugLine::TYPE_PAGEACTION;
- $buffer = $this->options['HTML_TABLE_interrow_info'];
- $txtPageAction = 'Page Action';
- $buffer .= $this->span("[ $txtPageAction : ".
- $properties['info']. ' ]', 'pageaction');
- break;
-
- // 14 : SQL parse
- case PHP_DebugLine::TYPE_SQLPARSE:
- $buffer = $this->options['HTML_TABLE_interrow_info'];
- $buffer .= $properties['info'];
- break;
-
- // 15 : Watches
- case PHP_DebugLine::TYPE_WATCH:
- $buffer = $this->options['HTML_TABLE_interrow_info'];
- $infos = $properties['info'];
- $buffer .= 'Variable '. $this->span($infos[0], 'watch').
- ' changed from value '. $this->span($infos[1], 'watch-val').
- ' ('. gettype($infos[1]).
- ') to value '. $this->span($infos[2], 'watch-val').
- ' ('. gettype($infos[2]). ')';
- break;
-
- // 16 : PHP errors
- case PHP_DebugLine::TYPE_PHPERROR:
- $buffer = $this->options['HTML_TABLE_interrow_info'];
- $buffer .= $this->showError($properties['info']);
- break;
-
- default:
- $buffer = $this->options['HTML_TABLE_interrow_info'];
- $buffer .= "<b>Default(". $properties['type'].
- ")</b>: TO IMPLEMENT OR TO CORRECT : >".
- $properties['info']. '<';
- break;
- }
-
- return $buffer;
- }
-
- /**
- * Return a string with applying a span style on it
- *
- * @param string $info String to apply the style
- * @param string $class CSS style to apply to the string
- * @return string Formatted string with style applied
- * @since V2.0.0 - 05 May 2006
- */
- protected function span($info, $class)
- {
- return '<span class="pd-'. $class .'">'. $info .'</span>';
- }
-
- /**
- * process display of the type of the debug information
- *
- * @param array $properties Properties of the debug line
- * @return string Formatted string containing the debug type
- * @since V2.0.0 - 26 Apr 2006
- */
- protected function processType($properties)
- {
- $buffer = $this->options['HTML_TABLE_interrow_type'];
- $buffer .= PHP_DebugLine::$debugLineLabels[$properties['type']];
- return $buffer;
- }
-
- /**
- * process display of Class
- *
- * @param array $properties Properties of the debug line
- * @return string Formatted string containing the class
- * @since V2.0.0 - 26 Apr 2006
- */
- protected function processClass($properties)
- {
- $buffer = '';
-
- switch ($properties['type'])
- {
- case PHP_DebugLine::TYPE_STD:
- case PHP_DebugLine::TYPE_QUERY:
- case PHP_DebugLine::TYPE_QUERYREL:
- case PHP_DebugLine::TYPE_APPERROR:
- case PHP_DebugLine::TYPE_PAGEACTION:
- case PHP_DebugLine::TYPE_PHPERROR:
- case PHP_DebugLine::TYPE_SQLPARSE:
- case PHP_DebugLine::TYPE_WATCH:
- case PHP_DebugLine::TYPE_DUMP:
-
- $buffer .= $this->options['HTML_TABLE_interrow_class'];
- if (!empty($properties['class'])) {
- $buffer .= $properties['class'];
- } else {
- $buffer .= ' ';
- }
-
- break;
-
- case PHP_DebugLine::TYPE_CREDITS:
- case PHP_DebugLine::TYPE_SEARCH:
- case PHP_DebugLine::TYPE_PROCESSPERF:
- case PHP_DebugLine::TYPE_TEMPLATES:
- case PHP_DebugLine::TYPE_ENV:
-
- $buffer .= $this->options['HTML_TABLE_interrow_class'];
- $buffer .= ' ';
-
- break;
-
- default:
- break;
- }
-
- return $buffer;
- }
-
- /**
- * process display of function
- *
- * @param array $properties Properties of the debug line
- * @return string Formatted string containing the function
- * @since V2.0.0 - 26 Apr 2006
- */
- protected function processFunction($properties)
- {
- $buffer = '';
-
- switch ($properties['type'])
- {
- case PHP_DebugLine::TYPE_STD:
- case PHP_DebugLine::TYPE_QUERY:
- case PHP_DebugLine::TYPE_QUERYREL:
- case PHP_DebugLine::TYPE_APPERROR:
- case PHP_DebugLine::TYPE_PAGEACTION:
- case PHP_DebugLine::TYPE_PHPERROR:
- case PHP_DebugLine::TYPE_SQLPARSE:
- case PHP_DebugLine::TYPE_WATCH:
- case PHP_DebugLine::TYPE_DUMP:
-
- $buffer .= $this->options['HTML_TABLE_interrow_function'];
- if (!empty($properties['function'])) {
- if ($properties['function'] != 'unknown') {
- $buffer .= $properties['function']. '()';
- } else {
- $buffer .= ' ';
- }
- } else {
- $buffer .= ' ';
- }
-
- break;
-
- case PHP_DebugLine::TYPE_CREDITS:
- case PHP_DebugLine::TYPE_SEARCH:
- case PHP_DebugLine::TYPE_PROCESSPERF:
- case PHP_DebugLine::TYPE_TEMPLATES:
- case PHP_DebugLine::TYPE_ENV:
-
- $buffer .= $this->options['HTML_TABLE_interrow_function'];
- $buffer .= ' ';
-
- break;
-
- default:
- break;
- }
-
- return $buffer;
- }
-
-
- /**
- * process display of line number
- *
- * @param array $properties Properties of the debug line
- * @return string Formatted string containing the line number
- * @since V2.0.0 - 26 Apr 2006
- */
- protected function processLine($properties)
- {
- $buffer = '';
-
- switch ($properties['type'])
- {
- case PHP_DebugLine::TYPE_STD:
- case PHP_DebugLine::TYPE_QUERY:
- case PHP_DebugLine::TYPE_QUERYREL:
- case PHP_DebugLine::TYPE_APPERROR:
- case PHP_DebugLine::TYPE_PAGEACTION:
- case PHP_DebugLine::TYPE_PHPERROR:
- case PHP_DebugLine::TYPE_SQLPARSE:
- case PHP_DebugLine::TYPE_WATCH:
- case PHP_DebugLine::TYPE_DUMP:
-
- $buffer.= $this->options['HTML_TABLE_interrow_line'];
- if (!empty($properties['line'])) {
- $buffer.= '<span class="pd-line">'. $properties['line']. '</span>';
- } else {
- $buffer.= ' ';
- }
-
- break;
-
- case PHP_DebugLine::TYPE_CREDITS:
- case PHP_DebugLine::TYPE_SEARCH:
- case PHP_DebugLine::TYPE_PROCESSPERF:
- case PHP_DebugLine::TYPE_TEMPLATES:
- case PHP_DebugLine::TYPE_ENV:
-
- $buffer.= $this->options['HTML_TABLE_interrow_line'];
- $buffer.= ' ';
-
- break;
-
- default:
- break;
- }
-
- return $buffer;
- }
-
- /**
- * process display of file name
- *
- * @param array $properties Properties of the debug line
- * @return string Formatted string containing the file
- * @since V2.0.0 - 26 Apr 2006
- */
- protected function processFile($properties)
- {
- $buffer = '';
-
- switch ($properties['type'])
- {
- case PHP_DebugLine::TYPE_STD:
- case PHP_DebugLine::TYPE_QUERY:
- case PHP_DebugLine::TYPE_QUERYREL:
- case PHP_DebugLine::TYPE_APPERROR:
- case PHP_DebugLine::TYPE_PAGEACTION:
- case PHP_DebugLine::TYPE_PHPERROR:
- case PHP_DebugLine::TYPE_SQLPARSE:
- case PHP_DebugLine::TYPE_WATCH:
- case PHP_DebugLine::TYPE_DUMP:
-
- $buffer .= $this->options['HTML_TABLE_interrow_file'];
-
- if (!empty($properties['file'])) {
- if (!empty($this->options['HTML_TABLE_view_source_script_path']) &&
- !empty($this->options['HTML_TABLE_view_source_script_name'])) {
- $buffer .= '<a href="'. $this->options['HTML_TABLE_view_source_script_path']
- . '/'. $this->options['HTML_TABLE_view_source_script_name']
- .'?file='. urlencode($properties['file']);
-
- $buffer .= '">'. basename($properties['file']). '</a>';
-
- } else {
- $buffer .= basename($properties['file']);
- }
- } else {
- $buffer .= ' ';
- }
-
- break;
-
- case PHP_DebugLine::TYPE_CREDITS:
- case PHP_DebugLine::TYPE_SEARCH:
- case PHP_DebugLine::TYPE_PROCESSPERF:
- case PHP_DebugLine::TYPE_TEMPLATES:
- case PHP_DebugLine::TYPE_ENV:
-
- $buffer .= $this->options['HTML_TABLE_interrow_file'];
- $buffer .= ' ';
-
- break;
-
- default:
- break;
- }
-
- return $buffer;
- }
-
- /**
- * Dump a variable
- *
- * @since V2.0.0 - 26 Apr 2006
- */
- protected function showDump($properties)
- {
- $buffer = '';
-
- // Check display with a <pre> design
- if (is_array($properties['info'][1])) {
- $preDisplay = true;
- } elseif (is_object($properties['info'][1])) {
- $preDisplay = true;
- } else {
- $preDisplay = false;
- }
-
- // Check var name
- if (empty($properties['info'][0])) {
- if (is_array($properties['info'][1])) {
- $varName = 'Array';
- } elseif (is_object($properties['info'][1])) {
- $varName = get_class($properties['info'][1]);
- } else {
- $varName = 'Variable';
- }
- } else {
- $varName = $properties['info'][0];
- }
-
- // Output
- if ($properties['type'] != PHP_DebugLine::TYPE_ENV) {
- $title = "dump of '";
- }
-
- $title .= $varName. "' (". gettype($properties['info'][1]) .") : ";
-
- $buffer .= $this->span($title , 'dump-title');
-
- if ($preDisplay == true){
- $buffer .= '<pre>';
- $buffer .= PHP_Debug::dumpVar($properties['info'][1],
- '', false, PHP_Debug::DUMP_STR);
- } else {
- $buffer .= $this->span(PHP_Debug::dumpVar(
- $properties['info'][1],
- '',
- false,
- PHP_Debug::DUMP_STR), 'dump-val');
- }
-
- if ($preDisplay == true){
- $buffer .= '</pre>';
- }
-
- return $buffer;
- }
-
- /**
- * Process the search combo box
- *
- * @since V2.0.0 - 26 Apr 2006
- */
- protected function showSearch()
- {
- // Repost all posted data
- $txtGo = 'Go !';
- $txtStringToSearch = 'Search for';
- $txtCaseSensitive = 'Case sensitive';
- $txtSelectByType = 'Select only info of type';
- $buffer = '';
-
- $debugSearchVal = isset($_REQUEST["PHPDEBUG_SEARCH"]) ? trim($_REQUEST["PHPDEBUG_SEARCH"]) : '';
- $debugSearchCSVal = isset($_REQUEST["PHPDEBUG_SEARCH_CS"]) ? ' checked="checked"' : '';
-
- $buffer .= '
- <form id="phpDebugForm" action="'. $_SERVER['PHP_SELF']. '">
- <table>
- <tr>
- <td class="pd-search">'. $txtStringToSearch .'</td>
- <td class="pd-search">:</td>
- <td class="pd-search">
- <input class="pd-search" type="text" name="PHPDEBUG_SEARCH" value="'. $debugSearchVal. '" />
- </td>
- <td class="pd-search">'. $txtCaseSensitive .'</td>
- <td class="pd-search">:</td>
- <td class="pd-search">
- <input class="pd-search" type="checkbox" name="PHPDEBUG_SEARCH_CS" '. $debugSearchCSVal .' />
- </td>
- </tr>
- <tr>
- <td class="pd-search">'. $txtSelectByType. '</td>
- <td class="pd-search">:</td>
- <td class="pd-search">
- <select class="pd-search" name="PHPDEBUG_SEARCH_TYPE">';
- foreach (PHP_DebugLine::$debugLineLabels as $lkey => $lvalue) {
- $debugSearchTypeVal = (!empty($_REQUEST["PHPDEBUG_SEARCH_TYPE"])
- & $lkey == $_REQUEST["PHPDEBUG_SEARCH_TYPE"]) ? ' selected="selected"' : '';
- $buffer .= " <option value=\"$lkey\"$debugSearchTypeVal>» $lvalue</option>". CR;
- }
- $buffer .= '
- </select>
- </td>
- <td class="pd-search"> </td>
- <td class="pd-search"> </td>
- <td class="pd-search">
- <input class="pd-search" type="submit" value="'. $txtGo. '" />
- </td>
- </tr>
- </table>
- </form>';
-
- return $buffer;
- }
-
- /**
- * Process the templates
- *
- * @since V2.0.0 - 26 Apr 2006
- */
- protected function showTemplates()
- {
- $txtMainFile = 'MAIN File';
- $idx = 1;
- $buffer = '<br />';
-
- foreach($this->DebugObject->getRequiredFiles() as $lvalue) {
-
- $isToDisplay = true;
-
- if ($this->options['HTML_TABLE_view_source_excluded_template']) {
- foreach ($this->options['HTML_TABLE_view_source_excluded_template'] as $template) {
- if (stristr($lvalue, $template)) {
- $isToDisplay = false;
- }
- }
- }
-
- if ($isToDisplay == true) {
-
- $buffer .= $this->span($lvalue, 'files');
- $buffer .= ' <a href="'. $this->options['HTML_TABLE_view_source_script_path']
- . '/'. $this->options['HTML_TABLE_view_source_script_name']
- .'?file='. urlencode($lvalue). '">View source</a> ';
-
- // Mark main file
- if ($idx == 1) {
- $buffer .= $this->span('« '. $txtMainFile, 'main-file');
- }
- $idx++;
- $buffer .= '<br />'. CR;
- }
- }
-
- $buffer .= '<br />'. CR;
- return $buffer;
- }
-
- /**
- * Process an error info
- *
- * @param array $info Array containing information about the error
- *
- * @since V2.0.0 - 25 Apr 2006
- * @see PHP_DEBUGLINE_PHPERROR
- */
- protected function showError($infos)
- {
- $buffer = '';
- $infos[1] = str_replace("'", '"', $infos[1]);
- $infos[1] = str_replace('href="function.', ' href="http://www.php.net/'. $this->options['lang']. '/', $infos[1]);
-
- switch ($infos[0])
- {
- case E_WARNING:
- $errorlevel = 'PHP WARNING : ';
- $buffer .= '<span class="pd-php-warning"> /!\\ '.
- $errorlevel. $infos[1] . ' /!\\ </span>';
- break;
-
- case E_NOTICE:
- $errorlevel = 'PHP notice : ';
- $buffer .= '<span class="pd-php-notice">'.
- $errorlevel. $infos[1] . '</span>';
- break;
-
- case E_USER_ERROR:
- $errorlevel = 'PHP User error : ';
- $buffer .= '<span class="pd-php-user-error"> /!\\ '.
- $errorlevel. $infos[1] . ' /!\\ </span>';
- break;
-
- case E_STRICT:
-
- $errorlevel = 'PHP STRICT error : ';
- $buffer .= '<span class="pd-php-user-error"> /!\\ '.
- $errorlevel. $infos[1] . ' /!\\ </span>';
- break;
-
- default:
- $errorlevel = 'PHP errorlevel = '. $infos[0]. ' : ';
- $buffer .= $errorlevel. ' is not implemented in PHP_Debug ('.
- __FILE__. ','. __LINE__. ')';
- break;
- }
- return $buffer;
- }
-
- /**
- * Show a super array
- *
- * @param string $SuperArrayType Type of super en array to add
- * @since V2.0.0 - 07 Apr 2006
- */
- protected function showSuperArray($SuperArrayType)
- {
- // Lang
- $txtVariable = 'Var';
- $txtNoVariable = 'NO VARIABLE';
- $NoVariable = ' -- '. $txtNoVariable. ' -- ';
- $SuperArray = null;
- $buffer = '';
-
- $ArrayTitle = PHP_Debug::$globalEnvConstantsCorresp[$SuperArrayType];
- $SuperArray = $GLOBALS[$ArrayTitle];
- $Title = $ArrayTitle. ' '. $txtVariable;
- $SectionBasetitle = '<b>$Title ('. count($SuperArray). ') :';
-
- if (count($SuperArray)) {
- $buffer .= $SectionBasetitle. '</b>';
- $buffer .= '<pre>'. PHP_Debug::dumpVar(
- $SuperArray,
- $ArrayTitle,
- false,
- PHP_Debug::DUMP_STR). '</pre>';
- }
- else {
- $buffer .= $SectionBasetitle. "$NoVariable</b>";
- }
- return $buffer;
- }
-
- /**
- * Add the environment display depending on the current configuration
- *
- * @since V2.0.0 - 18 apr 2006
- */
- protected function addSuperArray()
- {
- if ($this->options['HTML_TABLE_show_super_array'] == true) {
-
- // Divide Request tab
- if ($this->options['HTML_TABLE_use_request_arr'] == false) {
- // Include Post Var
- $this->DebugObject->addDebug(PHP_Debug::GLOBAL_POST, PHP_DebugLine::TYPE_ENV);
-
- // Include Get Var
- $this->DebugObject->addDebug(PHP_Debug::GLOBAL_GET, PHP_DebugLine::TYPE_ENV);
-
- // Include File Var
- $this->DebugObject->addDebug(PHP_Debug::GLOBAL_FILES, PHP_DebugLine::TYPE_ENV);
-
- // Include Cookie Var
- $this->DebugObject->addDebug(PHP_Debug::GLOBAL_COOKIE, PHP_DebugLine::TYPE_ENV);
- }
- else {
- // Only display Request Tab
- $this->DebugObject->addDebug(PHP_Debug::GLOBAL_REQUEST, PHP_DebugLine::TYPE_ENV);
- }
-
- // Include sessions variabmes, check if we have any
- if (!empty($_SESSION)) {
- $this->DebugObject->addDebug(PHP_Debug::GLOBAL_SESSION, PHP_DebugLine::TYPE_ENV);
- }
- }
- }
-
- /**
- * Add the process time information to the debug information
- *
- * @since V2.0.0 - 18 Apr 2006
- */
- protected function showProcessTime()
- {
- // Lang
- $txtExecutionTime = 'Global execution time ';
- $txtPHP = 'PHP';
- $txtSQL = 'SQL';
- $txtSECOND = 's';
- $txtOneQry = ' query';
- $txtMultQry = ' queries';
- $queryCount = $this->DebugObject->getQueryCount();
- $txtQuery = $queryCount > 1 ? $txtMultQry : $txtOneQry;
- $buffer = '';
-
- // Performance Debug
- $processTime = $this->DebugObject->getProcessTime();
- $sqlTime = $this->DebugObject->getQueryTime();
- $phpTime = $processTime - $sqlTime;
-
- $sqlPercent = round(($sqlTime / $processTime) * 100, 2);
- $phpPercent = round(($phpTime / $processTime) * 100, 2);
-
- $buffer .= '<div><table class="pd-perf-table"><tr><td class="pd-perf" align="center">'. $txtExecutionTime;
- $buffer .= '</td><td class="pd-perf" align="center">'. $processTime . $txtSECOND;
- $buffer .= '</td><td class="pd-perf" align="center">100%';
- $buffer .= '</td><td class="pd-perf" align="center"> </td></tr>';
-
- $buffer .= '<tr><td class="pd-perf" align="center">'. $txtPHP;
- $buffer .= '</td><td class="pd-perf" align="center">'. $phpTime . $txtSECOND;
- $buffer .= '</td><td class="pd-perf" align="center">'. $phpPercent .'%';
- $buffer .= '</td><td class="pd-perf" align="center"> </td></tr>';
-
- $buffer .= '<tr><td class="pd-perf" align="center">'. $txtSQL;
- $buffer .= '</td><td class="pd-perf" align="center">'. $sqlTime. $txtSECOND;
- $buffer .= '</td><td class="pd-perf" align="center">'. $sqlPercent . '%';
- $buffer .= '</td><td class="pd-perf" align="center">'. $queryCount. $txtQuery. '</td></tr>';
-
- $buffer .= '</table></div>';
-
- return $buffer;
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-/**
- * Configuration file for HTML_Table renderer
- *
- * @package PHP_Debug
- * @category PHP
- * @author Loic Vernet <qrf_coil at yahoo dot fr>
- * @since V2.0.0 - 10 Apr 2006
- *
- * @package PHP_Debug
- * @filesource
- */
-
-class PHP_Debug_Renderer_HTML_TableConfig
-{
- /**
- * Config container for Debug_Renderer_HTML_Table
- *
- * @var array
- * @since V2.0.0 - 11 apr 2006
- */
- protected static $options = array();
-
- /**
- * Static Instance of class
- *
- * @var array
- * @since V2.0.0 - 11 apr 2006
- */
- protected static $instance = null;
-
- /**
- * Debug_Renderer_HTML_Table_Config class constructor
- *
- * @since V2.0.0 - 11 apr 2006
- */
- protected function __construct()
- {
- /**
- * Enable or disable Credits in debug infos
- */
- self::$options['HTML_TABLE_disable_credits'] = false;
-
- /**
- * Enable or disable included and required files
- */
- self::$options['HTML_TABLE_show_templates'] = true;
-
- /**
- * Enable or disable pattern removing in included files
- */
- self::$options['HTML_TABLE_remove_templates_pattern'] = false;
-
- /**
- * Pattern list to remove in the display of included files
- * if HTML_TABLE_remove_templates_pattern is set to true
- */
- self::$options['HTML_TABLE_templates_pattern'] = array();
-
- /**
- * Enable or disable visualisation of $globals var in debug
- */
- self::$options['HTML_TABLE_show_globals'] = false;
-
- /**
- * Enable or disable search in debug
- */
- self::$options['HTML_TABLE_enable_search'] = true;
-
- /**
- * Enable or disable view of super arrays
- */
- self::$options['HTML_TABLE_show_super_array'] = true;
-
- /**
- * Enable or disable the use of $_REQUEST array instead of
- * $_POST + _$GET + $_COOKIE + $_FILES
- */
- self::$options['HTML_TABLE_use_request_arr'] = false;
-
- /**
- * View Source script path
- */
- self::$options['HTML_TABLE_view_source_script_path'] = '.';
-
- /**
- * View source script file name
- */
- self::$options['HTML_TABLE_view_source_script_name'] = 'PHP_Debug_ShowSource.php';
-
- /**
- * css path
- */
- self::$options['HTML_TABLE_css_path'] = 'css';
-
- /**
- * Tabsize for view source script
- */
- self::$options['HTML_TABLE_view_source_tabsize'] = 4;
-
- /**
- * Tabsize for view source script
- */
- self::$options['HTML_TABLE_view_source_numbers'] = 2; //HL_NUMBERS_TABLE
-
- /**
- * Define wether the display must be forced for the debug type when
- * in search mode
- */
- self::$options['HTML_TABLE_search_forced_type'] = array(
- PHP_DebugLine::TYPE_STD => false,
- PHP_DebugLine::TYPE_QUERY => false,
- PHP_DebugLine::TYPE_QUERYREL => false,
- PHP_DebugLine::TYPE_ENV => false,
- PHP_DebugLine::TYPE_APPERROR => false,
- PHP_DebugLine::TYPE_CREDITS => false,
- PHP_DebugLine::TYPE_SEARCH => true,
- PHP_DebugLine::TYPE_DUMP => false,
- PHP_DebugLine::TYPE_PROCESSPERF => false,
- PHP_DebugLine::TYPE_TEMPLATES => false,
- PHP_DebugLine::TYPE_PAGEACTION => false,
- PHP_DebugLine::TYPE_SQLPARSE => false,
- PHP_DebugLine::TYPE_WATCH => false,
- PHP_DebugLine::TYPE_PHPERROR => false
- );
-
- /**
- * After this goes all HTML related variables
- *
- *
- * HTML code for header
- */
- self::$options['HTML_TABLE_header'] = '
-<div id="pd-div">
-<br />
-<a name="pd-anchor" id="pd-anchor" />
-<table class="pd-table" cellspacing="0" cellpadding="0" width="100%">
- <tr>
- <td class="pd-table-header" align="center">File</td>
- <td class="pd-table-header" align="center">Line</td>
- <td class="pd-table-header" align="center">Inside/From function</td>
- <td class="pd-table-header" align="center">Inside/From Class</td>
- <td class="pd-table-header" align="center">Type</td>
- <td class="pd-table-header" align="center">Debug information</td>
- <td class="pd-table-header" align="center">Execution time (sec)</td>
- </tr>
- ';
-
- /**
- * HTML code for footer
- */
- self::$options['HTML_TABLE_credits'] = '
- PHP_Debug ['. PHP_Debug::PEAR_RELEASE .'] | By COil (2007) |
- <a href="http://www.coilblog.com">http://www.coilblog.com</a> |
- <a href="http://phpdebug.sourceforge.net/">PHP_Debug Project Home</a>
- ';
-
- /**
- * HTML code for a basic header
- */
- self::$options['HTML_TABLE_simple_header'] = '<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE html
- PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
- <head>
- <title>Pear::PHP_Debug</title>
-';
-
- /**
- * HTML code for a basic footer
- */
- self::$options['HTML_TABLE_simple_footer'] = '
-</body>
-</html>
-';
-
- /**
- * HTML pre-row code for debug column file
- */
- self::$options['HTML_TABLE_prerow'] = '
- <tr>';
-
- /**
- * HTML pre-row code for debug column file
- */
- self::$options['HTML_TABLE_interrow_file'] = '
- <td class="pd-td" align="center">';
-
- /**
- * HTML post-row code for debug column line (centered)
- */
- self::$options['HTML_TABLE_interrow_line'] = '
- </td>
- <td class="pd-td" align="center">';
-
- self::$options['HTML_TABLE_interrow_function'] = self::$options['HTML_TABLE_interrow_line'];
- self::$options['HTML_TABLE_interrow_class'] = self::$options['HTML_TABLE_interrow_line'];
- self::$options['HTML_TABLE_interrow_type'] = self::$options['HTML_TABLE_interrow_line'];
- self::$options['HTML_TABLE_interrow_time'] = self::$options['HTML_TABLE_interrow_line'];
-
- /**
- * HTML pre-row code for debug column info
- */
- self::$options['HTML_TABLE_interrow_info'] = '
- </td>
- <td class="pd-td" align="left">';
-
-
- /**
- * HTML post-row code for debugline
- */
- self::$options['HTML_TABLE_postrow'] = '
- </td>
- </tr>
-';
-
- /**
- * HTML code for footer
- */
- self::$options['HTML_TABLE_footer'] = '
-</table>
-</div>
-';
-
- }
-
- /**
- * returns the static instance of the class
- *
- * @since V2.0.0 - 11 apr 2006
- * @see PHP_Debug
- */
- public static function singleton()
- {
- if (!isset(self::$instance)) {
- $class = __CLASS__;
- self::$instance = new $class;
- }
- return self::$instance;
- }
-
- /**
- * returns the configuration
- *
- * @since V2.0.0 - 07 apr 2006
- * @see PHP_Debug
- */
- public static function getConfig()
- {
- return self::$options;
- }
-
- /**
- * HTML_Table_Config
- *
- * @since V2.0.0 - 26 Apr 2006
- */
- public function __toString()
- {
- return '<pre>'. PHP_Debug::dumpVar(
- $this->singleton()->getConfig(),
- __CLASS__,
- false,
- PHP_DEBUG_DUMP_ARR_STR). '</pre>';
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-
-class PHP_DebugLine
-{
-
- /**
- * PHP_DEBUGLINE Types
- *
- * - TYPE_ANY : All available types (for search mode)
- * - TYPE_STD : Standart debug
- * - TYPE_QUERY : Query debug
- * - TYPE_REL : Database related debug
- * - TYPE_ENV : Environment debug ($GLOBALS...)
- * - TYPE_APPERROR : Custom application error
- * - TYPE_CREDITS : Credits information
- * - TYPE_SEARCH : Search mode in debug
- * - TYPE_DUMP : Dump any kind of variable
- * - TYPE_PROCESSPERF : Performance analysys
- * - TYPE_TEMPLATES : Included templates of the calling script
- * - TYPE_PAGEACTION : Store main page action
- * - TYPE_SQLPARSE : SQL Parse error
- * - TYPE_WATCH : A variable to watch
- * - TYPE_PHPERROR : A debug generated by the custom error handler
- *
- * @category DebugLine
- */
-
- const TYPE_ANY = 0;
- const TYPE_STD = 1;
- const TYPE_QUERY = 2;
- const TYPE_QUERYREL = 3;
- const TYPE_ENV = 4;
- const TYPE_APPERROR = 5;
- const TYPE_CREDITS = 6;
- const TYPE_SEARCH = 7;
- const TYPE_DUMP = 8;
- const TYPE_PROCESSPERF = 9;
- const TYPE_TEMPLATES = 10;
- const TYPE_PAGEACTION = 11;
- const TYPE_SQLPARSE = 12;
- const TYPE_WATCH = 13;
- const TYPE_PHPERROR = 14;
- const TYPE_DEFAULT = self::TYPE_STD;
-
- /**
- * PHP_DEBUGLINE info levels
- */
- const INFO_LEVEL = 1;
- const WARNING_LEVEL = 2;
- const ERROR_LEVEL = 3;
-
- /**
- * Labels for debugline types
- */
- public static $debugLineLabels = array(
- self::TYPE_ANY => 'ALL',
- self::TYPE_STD => 'Standart',
- self::TYPE_QUERY => 'Query',
- self::TYPE_QUERYREL => 'Database related',
- self::TYPE_ENV => 'Environment',
- self::TYPE_APPERROR => 'Application error',
- self::TYPE_CREDITS => 'Credits',
- self::TYPE_SEARCH => 'Search',
- self::TYPE_DUMP => 'Variable dump',
- self::TYPE_PROCESSPERF => 'Performance analysis',
- self::TYPE_TEMPLATES => 'Included files',
- self::TYPE_PAGEACTION => 'Page main action',
- self::TYPE_SQLPARSE => 'SQL parse error',
- self::TYPE_WATCH => 'Watch',
- self::TYPE_PHPERROR => 'PHP error'
- );
-
- /**
- * Properties that stores the non formatted debug information
- *
- * @since V2.0.0 - 11 apr 2006
- * @var string
- */
- protected $info;
-
- /**
- * Type of the debug information
- *
- * @since V2.0.0 - 11 apr 2006
- * @see Debug_Line constants
- * @var integer
- */
- protected $type;
-
- /**
- * File of debug info
- *
- * @since V2.0.0 - 11 apr 2006
- * @var integer
- */
- protected $file;
-
- /**
- * Line of debug info
- *
- * @since V2.0.0 - 11 apr 2006
- * @var integer
- */
- protected $line;
-
- /**
- * Class from witch the debug was called
- *
- * @since V2.0.0 - 13 apr 2006
- * @var integer
- */
- protected $class;
-
- /**
- * Function from wich the debug was called
- *
- * @var integer
- * @since V2.0.0 - 11 apr 2006
- */
- protected $function;
-
- /**
- * Exection time for debug info
- *
- * @var float
- * @see stopTimer()
- * @since V2.0.0 - 16 apr 2006
- */
- protected $startTime;
-
- /**
- * Exection end time for debug info
- *
- * @see PHP_Debug::stopTimer(), setEndTime()
- * @since V2.0.0 - 16 apr 2006
- * @var float
- */
- protected $endTime;
-
- /**
- * PHP_DebugLine class constructor
- *
- * Here it is set :
- * - the start time of the debug info
- * - the traceback information
- *
- * @since V2.0.0 - 11 apr 2006
- * @see PHP_Debug::add()
- */
- public function __construct($info, $type = self::TYPE_DEFAULT)
- {
- $this->setStartTime();
- $this->info = $info;
- $this->type = $type;
- $this->setTraceback();
- }
-
- /**
- * Fills properties of debug line with backtrace informations
- *
- * @since V2.0.0 - 15 apr 2006
- */
- protected function setTraceback()
- {
- $callStack = debug_backtrace();
- $idx = 0;
-
- // Get max id of 'add' debug functions
- foreach($callStack as $lkey => $lvalue) {
- if (in_array($callStack[$lkey]['function'],
- PHP_Debug::$excludedBackTraceFunctions) == true
- ) {
- $idx = $lkey;
- }
- }
-
- $this->file = !empty($callStack[$idx] ['file'])
- ? $callStack[$idx]['file'] : '';
- $this->line = !empty($callStack[$idx] ['line'])
- ? $callStack[$idx]['line'] : '';
- $this->function = !empty($callStack[$idx+1]['function'])
- ? $callStack[$idx+1]['function'] : '';
- $this->class = !empty($callStack[$idx+1]['class'])
- ? $callStack[$idx+1]['class'] : '';
- }
-
- /**
- * Getter of all properties of Debug_Line object
- *
- * @return array Array containg all the properties of the debugline
- * @since V2.0.0 - 21 apr 2006
- */
- public function getProperties()
- {
- return array(
- 'class' => $this->class,
- 'file' => $this->file,
- 'function' => $this->function,
- 'line' => $this->line,
- 'info' => $this->info,
- 'type' => $this->type,
- 'startTime' => $this->startTime,
- 'endTime' => $this->endTime
- );
- }
-
- /**
- * setter of endTime
- *
- * @since V2.0.0 - 19 apr 2006
- */
- public function setEndTime($endTime = '')
- {
- $this->endTime = $endTime ? $endTime : PHP_Debug::getMicroTimeNow();
- }
-
- /**
- * setter of startTime
- *
- * @see pear bug http://pear.php.net/bugs/10919
- *
- * @since V2.1.2 - 04 may 2006
- */
- public function setStartTime($startTime = '')
- {
- $this->startTime = $startTime ? $startTime : PHP_Debug::getMicroTimeNow();
- }
-
- /**
- * Debug_Line default output function
- *
- * @since V2.0.0 - 11 apr 2006
- * @see PHP_Debug::dumpVar()
- */
- public function __toString()
- {
- return '<pre>'.
- PHP_Debug::dumpVar(
- $this,
- __CLASS__,
- false,
- PHP_DEBUG_DUMP_ARR_STR
- )
- . '</pre>';
- }
-
- /**
- * Function that give the debug type lable
- *
- * @author COil
- * @since V2.0.0 - 2 apr 2007
- */
- public static function getDebugLabel($type)
- {
- return self::$debugLineLabels[$type];
- }
-}
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Aidan Lister <aidan@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Compat.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
-
-
-/**
- * Provides missing functionality in the form of constants and functions
- * for older versions of PHP
- *
- * Optionally, you may simply include the file.
- * e.g. require_once 'PHP/Compat/Function/scandir.php';
- *
- * @category PHP
- * @package PHP_Compat
- * @version 1.1.0
- * @author Aidan Lister <aidan@php.net>
- * @static
- */
-class PHP_Compat
-{
- /**
- * Load a function, or array of functions
- *
- * @param string|array $function The function or functions to load.
- * @return bool|array true if loaded, false if not
- */
- function loadFunction ($function)
- {
- if (is_array($function)) {
-
- $res = array ();
- foreach ($function as $singlefunc) {
- $res[] = PHP_Compat::loadFunction($singlefunc);
- }
- return $res;
-
- } else {
-
- if (!function_exists($function)) {
- $file = sprintf('PHP/Compat/Function/%s.php', $function);
- if ((@include_once $file) !== false) {
- return true;
- }
- }
- return false;
- }
- }
-
-
- /**
- * Load a constant, or array of constants
- *
- * @param string|array $constant The constant or constants to load.
- * @return bool|array true if loaded, false if not
- */
- function loadConstant ($constant)
- {
- if (is_array($constant)) {
-
- $res = array ();
- foreach ($constant as $singleconst) {
- $res[] = PHP_Compat::loadConstant($singleconst);
- }
- return $res;
-
- } else {
-
- $file = sprintf('PHP/Compat/Constant/%s.php', $constant);
- if ((@include_once $file) !== false) {
- return true;
- }
- return false;
- }
- }
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Aidan Lister <aidan@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: E_STRICT.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-
-/**
- * Replace constant E_STRICT
- *
- * @category PHP
- * @package PHP_Compat
- * @link http://php.net/ref.errorfunc
- * @author Aidan Lister <aidan@php.net>
- * @version $Revision: 1.1.1.1 $
- * @since PHP 5
- */
-if (!defined('E_STRICT')) {
- define('E_STRICT', 2048);
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Aidan Lister <aidan@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: FILE.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-
-/**
- * Replace filesystem constants
- *
- * @category PHP
- * @package PHP_Compat
- * @link http://php.net/ref.filesystem
- * @author Aidan Lister <aidan@php.net>
- * @version $Revision: 1.1.1.1 $
- * @since PHP 5
- */
-if (!defined('FILE_USE_INCLUDE_PATH')) {
- define('FILE_USE_INCLUDE_PATH', 1);
-}
-
-if (!defined('FILE_IGNORE_NEW_LINES')) {
- define('FILE_IGNORE_NEW_LINES', 2);
-}
-
-if (!defined('FILE_SKIP_EMPTY_LINES')) {
- define('FILE_SKIP_EMPTY_LINES', 4);
-}
-
-if (!defined('FILE_APPEND')) {
- define('FILE_APPEND', 8);
-}
-
-if (!defined('FILE_NO_DEFAULT_CONTEXT')) {
- define('FILE_NO_DEFAULT_CONTEXT', 16);
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Aidan Lister <aidan@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: PATH_SEPARATOR.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-
-/**
- * Replace constant PATH_SEPARATOR
- *
- * @category PHP
- * @package PHP_Compat
- * @link http://php.net/ref.dir
- * @author Aidan Lister <aidan@php.net>
- * @version $Revision: 1.1.1.1 $
- * @since PHP 4.3.0-RC2
- */
-if (!defined('PATH_SEPARATOR')) { define('PATH_SEPARATOR',
- strtoupper(substr(PHP_OS, 0, 3) == 'WIN') ?
- ';' :
- ':');
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Aidan Lister <aidan@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: STD.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-
-/**
- * Replace commandline constants
- *
- * @category PHP
- * @package PHP_Compat
- * @link http://php.net/features.commandline
- * @author Aidan Lister <aidan@php.net>
- * @version $Revision: 1.1.1.1 $
- * @since PHP 4.3.0
- */
-if (!defined('STDIN')) {
- define('STDIN', fopen('php://stdin', 'r'));
-}
-
-if (!defined('STDOUT')) {
- define('STDOUT', fopen('php://stdout', 'w'));
-}
-
-if (!defined('STDERR')) {
- define('STDERR', fopen('php://stderr', 'w'));
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Stephan Schmidt <schst@php.net> |
-// | Aidan Lister <aidan@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: array_change_key_case.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-
-if (!defined('CASE_LOWER')) {
- define('CASE_LOWER', 0);
-}
-
-if (!defined('CASE_UPPER')) {
- define('CASE_UPPER', 1);
-}
-
-
-/**
- * Replace array_change_key_case()
- *
- * @category PHP
- * @package PHP_Compat
- * @link http://php.net/function.array_change_key_case
- * @author Stephan Schmidt <schst@php.net>
- * @author Aidan Lister <aidan@php.net>
- * @version $Revision: 1.1.1.1 $
- * @since PHP 4.2.0
- * @require PHP 4.0.1 (trigger_error)
- */
-if (!function_exists('array_change_key_case'))
-{
- function array_change_key_case($input, $case = CASE_LOWER)
- {
- if (!is_array($input)) {
- trigger_error('array_change_key_case(): The argument should be an array', E_USER_WARNING);
- return false;
- }
-
- $output = array ();
- $keys = array_keys($input);
- $casefunc = ($case == CASE_LOWER) ? 'strtolower' : 'strtoupper';
-
- foreach ($keys as $key) {
- $output[$casefunc($key)] = $input[$key];
- }
-
- return $output;
- }
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Aidan Lister <aidan@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: array_chunk.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-
-/**
- * Replace array_combine()
- *
- * @category PHP
- * @package PHP_Compat
- * @link http://php.net/function.array_chunk
- * @author Aidan Lister <aidan@php.net>
- * @author Thiemo Mättig (http://maettig.com)
- * @version $Revision: 1.1.1.1 $
- * @since PHP 4.2.0
- * @require PHP 4.0.1 (trigger_error)
- */
-if (!function_exists('array_chunk'))
-{
- function array_chunk($input, $size, $preserve_keys = false)
- {
- if (!is_array($input)) {
- trigger_error('array_chunk() expects parameter 1 to be array, ' . gettype($input) . ' given', E_USER_WARNING);
- return;
- }
-
- if (!is_numeric($size)) {
- trigger_error('array_chunk() expects parameter 2 to be long, ' . gettype($size) . ' given', E_USER_WARNING);
- return;
- }
-
- $size = (int)$size;
- if ($size <= 0)
- {
- trigger_error('array_chunk() Size parameter expected to be greater than 0', E_USER_WARNING);
- return;
- }
-
- $chunks = array();
- $i = 0;
-
- if ($preserve_keys !== false)
- {
- foreach ($input as $key => $value) {
- $chunks[(int)($i++ / $size)][$key] = $value;
- }
- }
- else
- {
- foreach ($input as $value) {
- $chunks[(int)($i++ / $size)][] = $value;
- }
- }
-
- return $chunks;
- }
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Aidan Lister <aidan@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: array_combine.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-
-/**
- * Replace array_combine()
- *
- * @category PHP
- * @package PHP_Compat
- * @link http://php.net/function.array_combine
- * @author Aidan Lister <aidan@php.net>
- * @version $Revision: 1.1.1.1 $
- * @since PHP 5
- * @require PHP 4.0.1 (trigger_error)
- */
-if (!function_exists('array_combine'))
-{
- function array_combine($keys, $values)
- {
- if (!is_array($keys)) {
- trigger_error('array_combine() expects parameter 1 to be array, ' . gettype($keys) . ' given', E_USER_WARNING);
- return;
- }
-
- if (!is_array($values)) {
- trigger_error('array_combine() expects parameter 2 to be array, ' . gettype($values) . ' given', E_USER_WARNING);
- return;
- }
-
- if (count($keys) !== count($values)) {
- trigger_error('array_combine() Both parameters should have equal number of elements', E_USER_WARNING);
- return false;
- }
-
- if (count($keys) === 0 || count($values) === 0) {
- trigger_error('array_combine() Both parameters should have number of elements at least 0', E_USER_WARNING);
- return false;
- }
-
- $keys = array_values($keys);
- $values = array_values($values);
-
- $combined = array ();
-
- for ($i = 0, $cnt = count($values); $i < $cnt; $i++) {
- $combined[$keys[$i]] = $values[$i];
- }
-
- return $combined;
- }
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Aidan Lister <aidan@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: array_diff_assoc.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-
-/**
- * Replace array_diff_assoc()
- *
- * @category PHP
- * @package PHP_Compat
- * @link http://php.net/function.array_diff_assoc
- * @author Aidan Lister <aidan@php.net>
- * @version $Revision: 1.1.1.1 $
- * @since PHP 4.3.0
- * @require PHP 4.0.1 (trigger_error)
- */
-if (!function_exists('array_diff_assoc'))
-{
- function array_diff_assoc()
- {
- // Check we have enough arguments
- $args = func_get_args();
- $count = count($args);
- if (count($args) < 2) {
- trigger_error('Wrong parameter count for array_diff_assoc()', E_USER_WARNING);
- return;
- }
-
- // Check arrays
- for ($i = 0; $i < $count; $i++)
- {
- if (!is_array($args[$i])) {
- trigger_error('array_diff_assoc() Argument #' . ($i + 1) . ' is not an array', E_USER_WARNING);
- return;
- }
- }
-
- // Get the comparison array
- $array_comp = array_shift($args);
- --$count;
-
- // Traverse values of the first array
- foreach ($array_comp as $key => $value)
- {
- // Loop through the other arrays
- for ($i = 0; $i < $count; $i++)
- {
- // Loop through this arrays key/value pairs and compare
- foreach ($args[$i] as $comp_key => $comp_value)
- {
- if ((string)$key === (string)$comp_key &&
- (string)$value === (string)$comp_value) {
-
- unset($array_comp[$key]);
- }
- }
- }
- }
-
- return $array_comp;
- }
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Aidan Lister <aidan@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: array_key_exists.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-
-/**
- * Replace array_key_exists()
- *
- * @category PHP
- * @package PHP_Compat
- * @link http://php.net/function.array_key_exists
- * @author Aidan Lister <aidan@php.net>
- * @version $Revision: 1.1.1.1 $
- * @since PHP 4.1.0
- * @require PHP 4.0.1 (trigger_error)
- */
-if (!function_exists('array_key_exists'))
-{
- function array_key_exists($key, $search)
- {
- if (!is_scalar($key)) {
- trigger_error('array_key_exists() The first argument should be either a string or an integer', E_USER_WARNING);
- return false;
- }
-
- if (is_object($search)) {
- $search = get_object_vars($search);
- }
-
- if (!is_array($search)) {
- trigger_error('array_key_exists() The second argument should be either an array or an object', E_USER_WARNING);
- return false;
- }
-
- return in_array($key, array_keys($search));
- }
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Aidan Lister <aidan@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: array_search.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-
-/**
- * Replace array_search()
- *
- * @category PHP
- * @package PHP_Compat
- * @link http://php.net/function.array_search
- * @author Aidan Lister <aidan@php.net>
- * @author Thiemo Mättig (http://maettig.com/)
- * @version $Revision: 1.1.1.1 $
- * @since PHP 4.0.5
- * @require PHP 4.0.1 (trigger_error)
- */
-if (!function_exists('array_search'))
-{
- function array_search($needle, $haystack, $strict = false)
- {
- if (!is_array($haystack)) {
- trigger_error("array_search() Wrong datatype for second argument", E_USER_WARNING);
- return false;
- }
-
- foreach ($haystack as $key => $value) {
- if ($strict ? $value === $needle : $value == $needle) {
- return $key;
- }
- }
-
- return false;
- }
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Stephan Schmidt <schst@php.net> |
-// | Aidan Lister <aidan@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: array_udiff.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-
-/**
- * Replace array_udiff()
- *
- * @category PHP
- * @package PHP_Compat
- * @link http://php.net/function.array_udiff
- * @author Stephan Schmidt <schst@php.net>
- * @author Aidan Lister <aidan@php.net>
- * @version $Revision: 1.1.1.1 $
- * @since PHP 5
- * @require PHP 4.0.6 (is_callable)
- */
-if (!function_exists('array_udiff'))
-{
- function array_udiff()
- {
- $args = func_get_args();
-
- if (count($args) < 3) {
- trigger_error('Wrong parameter count for array_udiff()', E_USER_WARNING);
- return;
- }
-
- // Get compare function
- $compare_func = array_pop($args);
- if (!is_callable($compare_func)) {
- if (is_array($compare_func)) {
- $compare_func = $compare_func[0] . '::' . $compare_func[1];
- }
- trigger_error('array_udiff() Not a valid callback ' . $compare_func, E_USER_WARNING);
- return;
- }
-
- // Check arrays
- $cnt = count($args);
- for ($i = 0; $i < $cnt; $i++) {
- if (!is_array($args[$i])) {
- trigger_error('array_udiff() Argument #' . ($i + 1). ' is not an array', E_USER_WARNING);
- return;
- }
- }
-
- $diff = array ();
- // Traverse values of the first array
- foreach ($args[0] as $key => $value) {
- // Check all arrays
- for ($i = 1; $i < $cnt; $i++) {
- foreach ($args[$i] as $cmp_value) {
- $result = call_user_func($compare_func, $value, $cmp_value);
- if ($result === 0) {
- continue 3;
- }
- }
- }
- $diff[$key] = $value;
- }
- return $diff;
- }
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Stephan Schmidt <schst@php.net> |
-// | Aidan Lister <aidan@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: array_udiff_assoc.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-
-/**
- * Replace array_udiff_assoc()
- *
- * @category PHP
- * @package PHP_Compat
- * @author Stephan Schmidt <schst@php.net>
- * @author Aidan Lister <aidan@php.net>
- * @version $Revision: 1.1.1.1 $
- * @link http://php.net/function.array-udiff-assoc
- * @since PHP 5
- * @require PHP 4.0.6 (is_callable)
- */
-if (!function_exists('array_udiff_assoc'))
-{
- function array_udiff_assoc()
- {
- $args = func_get_args();
- if (count($args) < 3) {
- trigger_error('Wrong parameter count for array_udiff_assoc()', E_USER_WARNING);
- return;
- }
-
- // Get compare function
- $compare_func = array_pop($args);
- if (!is_callable($compare_func)) {
- if (is_array($compare_func)) {
- $compare_func = $compare_func[0] . '::' . $compare_func[1];
- }
- trigger_error('array_udiff_assoc() Not a valid callback ' . $compare_func, E_USER_WARNING);
- return;
- }
-
- // Check arrays
- $count = count($args);
- for ($i = 0; $i < $count; $i++)
- {
- if (!is_array($args[$i])) {
- trigger_error('array_udiff_assoc() Argument #' . ($i + 1) . ' is not an array', E_USER_WARNING);
- return;
- }
- }
-
- $diff = array ();
- // Traverse values of the first array
- foreach ($args[0] as $key => $value)
- {
- // Check all arrays
- for ($i = 1; $i < $count; $i++)
- {
- if (!array_key_exists($key, $args[$i])) {
- continue;
- }
- $result = call_user_func($compare_func, $value, $args[$i][$key]);
- if ($result === 0) {
- continue 2;
- }
- }
-
- $diff[$key] = $value;
- }
-
- return $diff;
- }
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Aidan Lister <aidan@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: array_udiff_uassoc.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-
-/**
- * Replace array_udiff_uassoc()
- *
- * @category PHP
- * @package PHP_Compat
- * @link http://php.net/function.array_udiff_uassoc
- * @author Aidan Lister <aidan@php.net>
- * @version $Revision: 1.1.1.1 $
- * @since PHP 5
- * @require PHP 4.0.6 (is_callable)
- */
-if (!function_exists('array_udiff_uassoc'))
-{
- function array_udiff_uassoc()
- {
- $args = func_get_args();
- if (count($args) < 3) {
- trigger_error('Wrong parameter count for array_udiff_uassoc()', E_USER_WARNING);
- return;
- }
-
- // Get compare function
- $compare_func = array_pop($args);
- if (!is_callable($compare_func)) {
- if (is_array($compare_func)) {
- $compare_func = $compare_func[0] . '::' . $compare_func[1];
- }
- trigger_error('array_udiff_uassoc() Not a valid callback ' . $compare_func, E_USER_WARNING);
- return;
- }
-
- // Check arrays
- $count = count($args);
- for ($i = 0; $i < $count; $i++) {
- if (!is_array($args[$i])) {
- trigger_error('array_udiff_uassoc() Argument #' . ($i + 1) . ' is not an array', E_USER_WARNING);
- return;
- }
- }
-
- // Traverse values of the first array
- $diff = array ();
- foreach ($args[0] as $key => $value) {
- // Check all arrays
- for ($i = 1; $i < $count; $i++) {
- if (!array_key_exists($key, $args[$i])) {
- continue;
- }
- $result = call_user_func($compare_func, $value, $args[$i][$key]);
- if ($result === 0) {
- continue 2;
- }
- }
-
- $diff[$key] = $value;
- }
-
- return $diff;
- }
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Tom Buskens <ortega@php.net> |
-// | Aidan Lister <aidan@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: array_uintersect_assoc.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-
-/**
- * Replace array_uintersect_assoc()
- *
- * @category PHP
- * @package PHP_Compat
- * @link http://php.net/function.array_uintersect_assoc
- * @author Tom Buskens <ortega@php.net>
- * @author Aidan Lister <aidan@php.net>
- * @version $Revision: 1.1.1.1 $
- * @since PHP 5
- * @require PHP 4.0.6 (is_callable)
- */
-if (!function_exists('array_uintersect_assoc'))
-{
- function array_uintersect_assoc()
- {
- $args = func_get_args();
- if (count($args) < 3) {
- trigger_error('wrong parameter count for array_uintersect_assoc()', E_USER_WARNING);
- return;
- }
-
- // Get compare function
- $user_func = array_pop($args);
- if (!is_callable($user_func)) {
- if (is_array($user_func)) {
- $user_func = $user_func[0] . '::' . $user_func[1];
- }
- trigger_error('array_uintersect_assoc() Not a valid callback ' . $user_func, E_USER_WARNING);
- return;
- }
-
- // Check arrays
- $array_count = count($args);
- for ($i = 0; $i !== $array_count; $i++) {
- if (!is_array($args[$i])) {
- trigger_error('array_uintersect_assoc() Argument #' . ($i + 1) . ' is not an array', E_USER_WARNING);
- return;
- }
- }
-
- // Compare entries
- $output = array();
- foreach ($args[0] as $key => $item) {
- for ($i = 1; $i !== $array_count; $i++) {
- if (array_key_exists($key, $args[$i])) {
- $compare = call_user_func($user_func, $item, $args[$i][$key]);
- if ($compare === 0) {
- $output[$key] = $item;
- }
- }
-
- }
- }
-
- return $output;
- }
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Aidan Lister <aidan@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: array_uintersect_uassoc.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-
-/**
- * Replace array_uintersect_uassoc()
- *
- * @category PHP
- * @package PHP_Compat
- * @link http://php.net/function.array_uintersect_uassoc
- * @author Aidan Lister <aidan@php.net>
- * @version $Revision: 1.1.1.1 $
- * @since PHP 5
- * @require PHP 4.0.6 (is_callable)
- */
-if (!function_exists('array_uintersect_uassoc'))
-{
- function array_uintersect_uassoc()
- {
- $args = func_get_args();
- if (count($args) < 4) {
- trigger_error('Wrong parameter count for array_uintersect_uassoc()', E_USER_WARNING);
- return;
- }
-
- // Get key_compare_func
- $key_compare_func = array_pop($args);
- if (!is_callable($key_compare_func)) {
- if (is_array($key_compare_func)) {
- $key_compare_func = $key_compare_func[0] . '::' . $key_compare_func[1];
- }
- trigger_error('array_uintersect_uassoc() Not a valid callback ' . $key_compare_func, E_USER_WARNING);
- return;
- }
-
- // Get data_compare_func
- $data_compare_func = array_pop($args);
- if (!is_callable($data_compare_func)) {
- if (is_array($data_compare_func)) {
- $data_compare_func = $data_compare_func[0] . '::' . $data_compare_func[1];
- }
- trigger_error('array_uintersect_uassoc() Not a valid callback ' . $data_compare_func, E_USER_WARNING);
- return;
- }
-
- // Check arrays
- $count = count($args);
- for ($i = 0; $i !== $count; $i++) {
- if (!is_array($args[$i])) {
- trigger_error('array_uintersect_uassoc() Argument #' . ($i + 1) . ' is not an array', E_USER_WARNING);
- return;
- }
- }
-
- // Traverse values of the first array
- $intersect = array ();
- foreach ($args[0] as $key => $value) {
- // Check against each array
- for ($i = 1; $i < $count; $i++) {
- // Traverse each element in current array
- foreach ($args[$i] as $ckey => $cvalue) {
- // Compare key and value
- if (call_user_func($key_compare_func, $key, $ckey) === 0 &&
- call_user_func($data_compare_func, $value, $cvalue) === 0) {
-
- $intersect[$key] = $value;
- continue;
- }
- }
- }
- }
-
- return $intersect;
- }
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Tom Buskens <ortega@php.net> |
-// | Aidan Lister <aidan@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: array_walk_recursive.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-
-/**
- * Replace array_walk_recursive()
- *
- * @category PHP
- * @package PHP_Compat
- * @link http://php.net/function.array_walk_recursive
- * @author Tom Buskens <ortega@php.net>
- * @author Aidan Lister <aidan@php.net>
- * @version $Revision: 1.1.1.1 $
- * @since PHP 5
- * @require PHP 4.0.6 (is_callable)
- */
-if (!function_exists('array_walk_recursive'))
-{
- function array_walk_recursive(&$input, $funcname)
- {
- if (!is_callable($funcname)) {
- if (is_array($funcname)) {
- $funcname = $funcname[0] . '::' . $funcname[1];
- }
- trigger_error('array_walk_recursive() Not a valid callback ' . $user_func, E_USER_WARNING);
- return;
- }
-
- if (!is_array($input)) {
- trigger_error('array_walk_recursive() The argument should be an array', E_USER_WARNING);
- return;
- }
-
- $args = func_get_args();
-
- foreach ($input as $key => $item) {
- if (is_array($item)) {
- array_walk_recursive($item, $funcname, $args);
- $input[$key] = $item;
- } else {
- $args[0] = &$item;
- $args[1] = &$key;
- call_user_func_array($funcname, $args);
- $input[$key] = $item;
- }
- }
- }
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Aidan Lister <aidan@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: call_user_func_array.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-
-/**
- * Replace call_user_func_array()
- *
- * @category PHP
- * @package PHP_Compat
- * @link http://php.net/function.call_user_func_array
- * @author Aidan Lister <aidan@php.net>
- * @version $Revision: 1.1.1.1 $
- * @since PHP 4.0.4
- * @require PHP 4.0.1 (trigger_error)
- */
-if (!function_exists('call_user_func_array'))
-{
- function call_user_func_array($function, $param_arr)
- {
- $param_arr = (array) $param_arr;
-
- // Sanity check
- if (!is_callable($function))
- {
- if (is_array($function) && count($function) > 2) {
- $function = $function[0] . '::' . $function[1];
- }
- $error = sprintf('call_user_func_array() First argument is expected to be a valid callback, \'%s\' was given', $function);
- trigger_error($error, E_USER_WARNING);
- return;
- }
-
- // Build argument string
- $arg_string = '';
- $comma = '';
- for ($i = 0, $x = count($param_arr); $i < $x; $i++) {
- $arg_string .= $comma . "\$param_arr[$i]";
- $comma = ', ';
- }
-
- // Determine method of calling function
- if (is_array($function))
- {
- $object =& $function[0];
- $method = $function[1];
-
- // Static vs method call
- if (is_string($function[0])) {
- eval("\$retval = $object::\$method($arg_string);");
- } else {
- eval("\$retval = \$object->\$method($arg_string);");
- }
- }
- else {
- eval("\$retval = \$function($arg_string);");
- }
-
- return $retval;
- }
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Aidan Lister <aidan@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: constant.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-
-/**
- * Replace constant()
- *
- * @category PHP
- * @package PHP_Compat
- * @link http://php.net/function.constant
- * @author Aidan Lister <aidan@php.net>
- * @version $Revision: 1.1.1.1 $
- * @since PHP 4.0.4
- * @require PHP 4.0.1 (trigger_error)
- */
-if (!function_exists('constant'))
-{
- function constant($constant)
- {
- if (!defined($constant)) {
- $error = sprintf('constant() Couldn\'t find constant %s', $constant);
- trigger_error($error, E_USER_WARNING);
- return false;
- }
-
- eval("\$value=$constant;");
-
- return $value;
- }
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Michael Wallner <mike@php.net> |
-// | Aidan Lister <aidan@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: convert_uudecode.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-
-/**
- * Replace convert_uudecode()
- *
- * @category PHP
- * @package PHP_Compat
- * @link http://php.net/function.convert_uudecode
- * @author Michael Wallner <mike@php.net>
- * @author Aidan Lister <aidan@php.net>
- * @version $Revision: 1.1.1.1 $
- * @since PHP 5
- * @require PHP 4.0.1 (trigger_error)
- */
-if (!function_exists('convert_uudecode'))
-{
- function convert_uudecode($string)
- {
- // Sanity check
- if (!is_scalar($string)) {
- trigger_error('convert_uuencode() expects parameter 1 to be string, ' . gettype($string) . ' given', E_USER_WARNING);
- return false;
- }
-
- if (strlen($string) < 8) {
- trigger_error('convert_uuencode() The given parameter is not a valid uuencoded string', E_USER_WARNING);
- return false;
- }
-
- $decoded = '';
- foreach (explode("\n", $string) as $line) {
-
- $c = count($bytes = unpack('c*', substr(trim($line), 1)));
-
- while ($c % 4) {
- $bytes[++$c] = 0;
- }
-
- foreach (array_chunk($bytes, 4) as $b) {
- $b0 = $b[0] == 0x60 ? 0 : $b[0] - 0x20;
- $b1 = $b[1] == 0x60 ? 0 : $b[1] - 0x20;
- $b2 = $b[2] == 0x60 ? 0 : $b[2] - 0x20;
- $b3 = $b[3] == 0x60 ? 0 : $b[3] - 0x20;
-
- $b0 <<= 2;
- $b0 |= ($b1 >> 4) & 0x03;
- $b1 <<= 4;
- $b1 |= ($b2 >> 2) & 0x0F;
- $b2 <<= 6;
- $b2 |= $b3 & 0x3F;
-
- $decoded .= pack('c*', $b0, $b1, $b2);
- }
- }
-
- return rtrim($decoded, "\0");
- }
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Michael Wallner <mike@php.net> |
-// | Aidan Lister <aidan@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: convert_uuencode.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-
-/**
- * Replace convert_uuencode()
- *
- * @category PHP
- * @package PHP_Compat
- * @link http://php.net/function.convert_uuencode
- * @author Michael Wallner <mike@php.net>
- * @author Aidan Lister <aidan@php.net>
- * @version $Revision: 1.1.1.1 $
- * @since PHP 5
- * @require PHP 4.0.1 (trigger_error)
- */
-if (!function_exists('convert_uuencode'))
-{
- function convert_uuencode($string)
- {
- // Sanity check
- if (!is_scalar($string)) {
- trigger_error('convert_uuencode() expects parameter 1 to be string, ' . gettype($string) . ' given', E_USER_WARNING);
- return false;
- }
-
- $u = 0;
- $encoded = '';
-
- while ($c = count($bytes = unpack('c*', substr($string, $u, 45)))) {
- $u += 45;
- $encoded .= pack('c', $c + 0x20);
-
- while ($c % 3) {
- $bytes[++$c] = 0;
- }
-
- foreach (array_chunk($bytes, 3) as $b) {
- $b0 = ($b[0] & 0xFC) >> 2;
- $b1 = (($b[0] & 0x03) << 4) + (($b[1] & 0xF0) >> 4);
- $b2 = (($b[1] & 0x0F) << 2) + (($b[2] & 0xC0) >> 6);
- $b3 = $b[2] & 0x3F;
-
- $b0 = $b0 ? $b0 + 0x20 : 0x60;
- $b1 = $b1 ? $b1 + 0x20 : 0x60;
- $b2 = $b2 ? $b2 + 0x20 : 0x60;
- $b3 = $b3 ? $b3 + 0x20 : 0x60;
-
- $encoded .= pack('c*', $b0, $b1, $b2, $b3);
- }
-
- $encoded .= "\n";
- }
-
- // Add termination characters
- $encoded .= "\x60\n";
-
- return $encoded;
- }
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Aidan Lister <aidan@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: file_get_contents.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-
-/**
- * Replace file_get_contents()
- *
- * @category PHP
- * @package PHP_Compat
- * @link http://php.net/function.file_get_contents
- * @author Aidan Lister <aidan@php.net>
- * @version $Revision: 1.1.1.1 $
- * @internal resource_context is not supported
- * @since PHP 5
- * @require PHP 4.0.1 (trigger_error)
- */
-if (!function_exists('file_get_contents'))
-{
- function file_get_contents($filename, $incpath = false, $resource_context = null)
- {
- if (false === $fh = fopen($filename, 'rb', $incpath)) {
- trigger_error('file_get_contents() failed to open stream: No such file or directory', E_USER_WARNING);
- return false;
- }
-
- clearstatcache();
- if ($fsize = filesize($filename)) {
- $data = fread($fh, $fsize);
- } else {
- while (!feof($fh)) {
- $data .= fread($fh, 8192);
- }
- }
-
- fclose($fh);
- return $data;
- }
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Aidan Lister <aidan@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: file_put_contents.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-
-if (!defined('FILE_USE_INCLUDE_PATH')) {
- define('FILE_USE_INCLUDE_PATH', 1);
-}
-
-if (!defined('FILE_APPEND')) {
- define('FILE_APPEND', 8);
-}
-
-
-/**
- * Replace file_put_contents()
- *
- * @category PHP
- * @package PHP_Compat
- * @link http://php.net/function.file_put_contents
- * @author Aidan Lister <aidan@php.net>
- * @version $Revision: 1.1.1.1 $
- * @internal $resource_context is not supported
- * @since PHP 5
- * @require PHP 4.0.1 (trigger_error)
- */
-if (!function_exists('file_put_contents'))
-{
- function file_put_contents($filename, $content, $flags = null, $resource_context = null)
- {
- // If $content is an array, convert it to a string
- if (is_array($content)) {
- $content = implode('', $content);
- }
-
- // If we don't have a string, throw an error
- if (!is_string($content)) {
- trigger_error('file_put_contents() The 2nd parameter should be either a string or an array', E_USER_WARNING);
- return false;
- }
-
- // Get the length of date to write
- $length = strlen($content);
-
- // Check what mode we are using
- $mode = ($flags & FILE_APPEND) ?
- $mode = 'a' :
- $mode = 'w';
-
- // Check if we're using the include path
- $use_inc_path = ($flags & FILE_USE_INCLUDE_PATH) ?
- true :
- false;
-
- // Open the file for writing
- if (($fh = @fopen($filename, $mode, $use_inc_path)) === false) {
- trigger_error('file_put_contents() failed to open stream: Permission denied', E_USER_WARNING);
- return false;
- }
-
- // Write to the file
- $bytes = 0;
- if (($bytes = @fwrite($fh, $content)) === false) {
- $errormsg = sprintf('file_put_contents() Failed to write %d bytes to %s',
- $length,
- $filename);
- trigger_error($errormsg, E_USER_WARNING);
- return false;
- }
-
- // Close the handle
- @fclose($fh);
-
- // Check all the data was written
- if ($bytes != $length) {
- $errormsg = sprintf('file_put_contents() Only %d of %d bytes written, possibly out of free disk space.',
- $bytes,
- $length);
- trigger_error($errormsg, E_USER_WARNING);
- return false;
- }
-
- // Return length
- return $bytes;
- }
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Aidan Lister <aidan@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: fprintf.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-
-/**
- * Replace fprintf()
- *
- * @category PHP
- * @package PHP_Compat
- * @link http://php.net/function.fprintf
- * @author Aidan Lister <aidan@php.net>
- * @version $Revision: 1.1.1.1 $
- * @since PHP 5
- * @require PHP 4.0.1 (trigger_error)
- */
-if (!function_exists('fprintf'))
-{
- function fprintf() {
- $args = func_get_args();
-
- if (count($args) < 2) {
- trigger_error ('Wrong parameter count for fprintf()', E_USER_WARNING);
- return;
- }
-
- $resource_handle = array_shift($args);
- $format = array_shift($args);
-
- if (!is_resource($resource_handle)) {
- trigger_error ('fprintf(): supplied argument is not a valid stream resource', E_USER_WARNING);
- return false;
- }
-
- return fwrite($resource_handle, vsprintf($format, $args));
- }
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Stephan Schmidt <schst@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: get_include_path.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-
-/**
- * Replace get_include_path()
- *
- * @category PHP
- * @package PHP_Compat
- * @link http://php.net/function.get_include_path
- * @author Stephan Schmidt <schst@php.net>
- * @version $Revision: 1.1.1.1 $
- * @since PHP 4.3.0
- */
-if (!function_exists('get_include_path'))
-{
- function get_include_path()
- {
- return ini_get('include_path');
- }
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: David Irvine <dave@codexweb.co.za> |
-// | Aidan Lister <aidan@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: html_entity_decode.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-
-if (!defined('ENT_NOQUOTES')) {
- define('ENT_NOQUOTES', 0);
-}
-
-if (!defined('ENT_COMPAT')) {
- define('ENT_COMPAT', 2);
-}
-
-if (!defined('ENT_QUOTES')) {
- define('ENT_QUOTES', 3);
-}
-
-
-/**
- * Replace html_entity_decode()
- *
- * @category PHP
- * @package PHP_Compat
- * @link http://php.net/function.html_entity_decode
- * @author David Irvine <dave@codexweb.co.za>
- * @author Aidan Lister <aidan@php.net>
- * @version $Revision: 1.1.1.1 $
- * @since PHP 4.3.0
- * @internal Setting the charset will not do anything
- * @require PHP 4.0.1 (trigger_error)
- */
-if (!function_exists('html_entity_decode'))
-{
- function html_entity_decode($string, $quote_style = ENT_COMPAT, $charset = null)
- {
- if (!is_int($quote_style)) {
- trigger_error('html_entity_decode() expects parameter 2 to be long, ' . gettype($quote_style) . ' given', E_USER_WARNING);
- return;
- }
-
- $trans_tbl = get_html_translation_table(HTML_ENTITIES);
- $trans_tbl = array_flip($trans_tbl);
-
- // Add single quote to translation table;
- $trans_tbl['''] = '\'';
-
- // Not translating double quotes
- if ($quote_style & ENT_NOQUOTES) {
- // Remove double quote from translation table
- unset($trans_tbl['"']);
- }
-
- return strtr($string, $trans_tbl);
- }
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?PHP
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Stephan Schmidt <schst@php.net> |
-// | Aidan Lister <aidan@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: http_build_query.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-
-/**
- * Replace function http_build_query()
- *
- * @category PHP
- * @package PHP_Compat
- * @link http://php.net/function.http-build-query
- * @author Stephan Schmidt <schst@php.net>
- * @author Aidan Lister <aidan@php.net>
- * @version $Revision: 1.1.1.1 $
- * @since PHP 5
- * @require PHP 4.0.1 (trigger_error)
- */
-if (!function_exists('http_build_query'))
-{
- function http_build_query($formdata, $numeric_prefix = null)
- {
- // If $formdata is an object, convert it to an array
- if (is_object($formdata)) {
- $formdata = get_object_vars($formdata);
- }
-
- // Check we have an array to work with
- if (!is_array($formdata)) {
- trigger_error('http_build_query() Parameter 1 expected to be Array or Object. Incorrect value given.', E_USER_WARNING);
- return false;
- }
-
- // If the array is empty, return null
- if (empty($formdata)) {
- return;
- }
-
- // Start building the query
- $tmp = array ();
- foreach ($formdata as $key => $val)
- {
- if (is_integer($key) && $numeric_prefix != null) {
- $key = $numeric_prefix . $key;
- }
-
- if (is_scalar($val)) {
- array_push($tmp, urlencode($key).'='.urlencode($val));
- continue;
- }
-
- // If the value is an array, recursively parse it
- if (is_array($val)) {
- array_push($tmp, __http_build_query($val, urlencode($key)));
- continue;
- }
- }
-
- return implode('&', $tmp);
- }
-
- // Helper function
- function __http_build_query ($array, $name)
- {
- $tmp = array ();
- foreach ($array as $key => $value)
- {
- if (is_array($value)) {
- array_push($tmp, __http_build_query($value, sprintf('%s[%s]', $name, $key)));
- }
-
- elseif (is_scalar($value)) {
- array_push($tmp, sprintf('%s[%s]=%s', $name, urlencode($key), urlencode($value)));
- }
-
- elseif (is_object($value)) {
- array_push($tmp, __http_build_query(get_object_vars($value), sprintf('%s[%s]', $name, $key)));
- }
- }
-
- return implode('&', $tmp);
- }
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Aidan Lister <aidan@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: image_type_to_mime_type.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-
-if (!defined('IMAGETYPE_GIF')) {
- define('IMAGETYPE_GIF', 1);
-}
-
-if (!defined('IMAGETYPE_JPEG')) {
- define('IMAGETYPE_JPEG', 2);
-}
-
-if (!defined('IMAGETYPE_PNG')) {
- define('IMAGETYPE_PNG', 3);
-}
-
-if (!defined('IMAGETYPE_SWF')) {
- define('IMAGETYPE_SWF', 4);
-}
-
-if (!defined('IMAGETYPE_PSD')) {
- define('IMAGETYPE_PSD', 5);
-}
-
-if (!defined('IMAGETYPE_BMP')) {
- define('IMAGETYPE_BMP', 6);
-}
-
-if (!defined('IMAGETYPE_TIFF_II')) {
- define('IMAGETYPE_TIFF_II', 7);
-}
-
-if (!defined('IMAGETYPE_TIFF_MM')) {
- define('IMAGETYPE_TIFF_MM', 8);
-}
-
-if (!defined('IMAGETYPE_JPC')) {
- define('IMAGETYPE_JPC', 9);
-}
-
-if (!defined('IMAGETYPE_JP2')) {
- define('IMAGETYPE_JP2', 10);
-}
-
-if (!defined('IMAGETYPE_JPX')) {
- define('IMAGETYPE_JPX', 11);
-}
-
-if (!defined('IMAGETYPE_JB2')) {
- define('IMAGETYPE_JB2', 12);
-}
-
-if (!defined('IMAGETYPE_SWC')) {
- define('IMAGETYPE_SWC', 13);
-}
-
-if (!defined('IMAGETYPE_IFF')) {
- define('IMAGETYPE_IFF', 14);
-}
-
-if (!defined('IMAGETYPE_WBMP')) {
- define('IMAGETYPE_WBMP', 15);
-}
-
-if (!defined('IMAGETYPE_XBM')) {
- define('IMAGETYPE_XBM', 16);
-}
-
-
-/**
- * Replace image_type_to_mime_type()
- *
- * @category PHP
- * @package PHP_Compat
- * @link http://php.net/function.image_type_to_mime_type
- * @author Aidan Lister <aidan@php.net>
- * @version $Revision: 1.1.1.1 $
- * @since PHP 4.3.0
- * @require PHP 3
- */
-if (!function_exists('image_type_to_mime_type'))
-{
- function image_type_to_mime_type($imagetype)
- {
- switch ($imagetype):
- case IMAGETYPE_GIF:
- return "image/gif";
- break;
- case IMAGETYPE_JPEG:
- return "image/jpeg";
- break;
- case IMAGETYPE_PNG:
- return "image/png";
- break;
- case IMAGETYPE_SWF:
- case IMAGETYPE_SWC:
- return "application/x-shockwave-flash";
- break;
- case IMAGETYPE_PSD:
- return "image/psd";
- break;
- case IMAGETYPE_BMP:
- return "image/bmp";
- break;
- case IMAGETYPE_TIFF_MM:
- case IMAGETYPE_TIFF_II:
- return "image/tiff";
- break;
- case IMAGETYPE_JP2:
- return "image/jp2";
- break;
- case IMAGETYPE_IFF:
- return "image/iff";
- break;
- case IMAGETYPE_WBMP:
- return "image/vnd.wap.wbmp";
- break;
- case IMAGETYPE_XBM:
- return "image/xbm";
- break;
- case IMAGETYPE_JPX:
- case IMAGETYPE_JB2:
- case IMAGETYPE_JPC:
- default:
- return "application/octet-stream";
- break;
-
- endswitch;
- }
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Aidan Lister <aidan@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: is_a.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-
-/**
- * Replace function is_a()
- *
- * @category PHP
- * @package PHP_Compat
- * @link http://php.net/function.is_a
- * @author Aidan Lister <aidan@php.net>
- * @version $Revision: 1.1.1.1 $
- * @since PHP 4.2.0
- * @require PHP 4.0.0 (is_subclass_of)
- */
-if (!function_exists('is_a'))
-{
- function is_a($object, $class)
- {
- if (get_class($object) == strtolower($class)) {
- return true;
- }
-
- else {
- return is_subclass_of($object, $class);
- }
- }
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Aidan Lister <aidan@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: ob_clean.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-
-/**
- * Replace ob_clean()
- *
- * @category PHP
- * @package PHP_Compat
- * @link http://php.net/function.ob_clean
- * @author Aidan Lister <aidan@php.net>
- * @author Thiemo Mättig (http://maettig.com/)
- * @version $Revision: 1.1.1.1 $
- * @since PHP 4.2.0
- * @require PHP 4.0.1 (trigger_error)
- */
-if (!function_exists('ob_clean'))
-{
- function ob_clean()
- {
- if (@ob_end_clean()) {
- return ob_start();
- }
-
- trigger_error("ob_clean() failed to delete buffer. No buffer to delete.", E_USER_NOTICE);
-
- return false;
- }
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Aidan Lister <aidan@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: ob_flush.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-
-/**
- * Replace ob_flush()
- *
- * @category PHP
- * @package PHP_Compat
- * @link http://php.net/function.ob_flush
- * @author Aidan Lister <aidan@php.net>
- * @author Thiemo Mättig (http://maettig.com/)
- * @version $Revision: 1.1.1.1 $
- * @since PHP 4.2.0
- * @require PHP 4.0.1 (trigger_error)
- */
-if (!function_exists('ob_flush'))
-{
- function ob_flush()
- {
- if (@ob_end_flush()) {
- return ob_start();
- }
-
- trigger_error("ob_flush() Failed to flush buffer. No buffer to flush.", E_USER_NOTICE);
-
- return false;
- }
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Aidan Lister <aidan@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: ob_get_clean.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-
-/**
- * Replace ob_get_clean()
- *
- * @category PHP
- * @package PHP_Compat
- * @link http://php.net/function.ob_get_clean
- * @author Aidan Lister <aidan@php.net>
- * @author Thiemo Mättig (http://maettig.com/)
- * @version $Revision: 1.1.1.1 $
- * @since PHP 4.3.0
- * @require PHP 4.0.1 (trigger_error)
- */
-if (!function_exists('ob_get_clean'))
-{
- function ob_get_clean()
- {
- $contents = ob_get_contents();
-
- if ($contents !== false) {
- ob_end_clean();
- }
-
- return $contents;
- }
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Aidan Lister <aidan@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: ob_get_flush.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-
-/**
- * Replace ob_get_flush()
- *
- * @category PHP
- * @package PHP_Compat
- * @link http://php.net/function.ob_get_flush
- * @author Aidan Lister <aidan@php.net>
- * @author Thiemo Mättig (http://maettig.com/)
- * @version $Revision: 1.1.1.1 $
- * @since PHP 4.3.0
- * @require PHP 4.0.1 (trigger_error)
- */
-if (!function_exists('ob_get_flush'))
-{
- function ob_get_flush()
- {
- $contents = ob_get_contents();
-
- if ($contents !== false) {
- ob_end_flush();
- }
-
- return $contents;
- }
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Aidan Lister <aidan@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: php_strip_whitespace.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-
-/**
- * Replace php_strip_whitespace()
- *
- * @category PHP
- * @package PHP_Compat
- * @link http://php.net/function.php_strip_whitespace
- * @author Aidan Lister <aidan@php.net>
- * @version $Revision: 1.1.1.1 $
- * @since PHP 5
- * @require PHP 4.0.1 (trigger_error), Tokenizer extension
- */
-if (!function_exists('php_strip_whitespace'))
-{
- function php_strip_whitespace($file)
- {
- // Sanity check
- if (!is_scalar($file)) {
- trigger_error('php_strip_whitespace() expects parameter 1 to be string, ' . gettype($file) . ' given', E_USER_WARNING);
- return;
- }
-
- // Load file / tokens
- $source = implode('', file($file));
- $tokens = token_get_all($source);
-
- // Init
- $source = '';
- $was_ws = false;
-
- // Process
- foreach ($tokens as $token) {
- if (is_string($token)) {
- // This will be ";"
- $source .= $token;
- } else {
- list($id, $text) = $token;
-
- switch ($id) {
- // Skip all comments
- case T_COMMENT:
- case T_ML_COMMENT:
- case T_DOC_COMMENT:
- break;
-
- // Remove whitespace
- case T_WHITESPACE:
- // We don't want more than one whitespace in a row replaced
- if ($was_ws !== true) {
- $source .= ' ';
- }
- $was_ws = true;
- break;
-
- default:
- $was_ws = false;
- $source .= $text;
- break;
- }
- }
- }
-
- return $source;
- }
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Stephan Schmidt <schst@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: restore_include_path.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-
-/**
- * Replace restore_include_path()
- *
- * @category PHP
- * @package PHP_Compat
- * @link http://php.net/function.restore_include_path
- * @author Stephan Schmidt <schst@php.net>
- * @version $Revision: 1.1.1.1 $
- * @since PHP 4.3.0
- */
-if (!function_exists('restore_include_path'))
-{
- function restore_include_path()
- {
- return ini_restore('include_path');
- }
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Aidan Lister <aidan@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: scandir.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-
-/**
- * Replace scandir()
- *
- * @category PHP
- * @package PHP_Compat
- * @link http://php.net/function.scandir
- * @author Aidan Lister <aidan@php.net>
- * @version $Revision: 1.1.1.1 $
- * @since PHP 5
- * @require PHP 4.0.1 (trigger_error)
- */
-if (!function_exists('scandir'))
-{
- function scandir($directory, $sorting_order = 0)
- {
- if (!is_string($directory)) {
- trigger_error('scandir() expects parameter 1 to be string, ' . gettype($directory) . ' given', E_USER_WARNING);
- return;
- }
-
- if (!is_int($sorting_order) && !is_bool($sorting_order)) {
- trigger_error('scandir() expects parameter 2 to be long, ' . gettype($sorting_order) . ' given', E_USER_WARNING);
- return;
- }
-
- if (!is_dir($directory) || (false === $fh = @opendir($directory))) {
- trigger_error('scandir() failed to open dir: Invalid argument', E_USER_WARNING);
- return false;
- }
-
- $files = array ();
- while (false !== ($filename = readdir($fh))) {
- $files[] = $filename;
- }
-
- closedir($fh);
-
- if ($sorting_order == 1) {
- rsort($files);
- } else {
- sort($files);
- }
-
- return $files;
- }
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Stephan Schmidt <schst@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: set_include_path.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-
-/**
- * Replace set_include_path()
- *
- * @category PHP
- * @package PHP_Compat
- * @link http://php.net/function.set_include_path
- * @author Stephan Schmidt <schst@php.net>
- * @version $Revision: 1.1.1.1 $
- * @since PHP 4.3.0
- */
-if (!function_exists('set_include_path'))
-{
- function set_include_path($new_include_path)
- {
- return ini_set('include_path', $new_include_path);
- }
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Aidan Lister <aidan@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: str_ireplace.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-
-/**
- * Replace str_ireplace()
- *
- * @category PHP
- * @package PHP_Compat
- * @link http://php.net/function.str_ireplace
- * @author Aidan Lister <aidan@php.net>
- * @version $Revision: 1.1.1.1 $
- * @since PHP 5
- * @require PHP 4.0.1 (trigger_error)
- * @note count not by returned by reference, to enable
- * change '$count = null' to '&$count'
- */
-if (!function_exists('str_ireplace'))
-{
- function str_ireplace($search, $replace, $subject, $count = null)
- {
- if (is_string($search) && is_array($replace)) {
- trigger_error('Array to string conversion', E_USER_NOTICE);
- $replace = (string) $replace;
- }
-
- // If search isn't an array, make it one
- if (!is_array($search)) {
- $search = array ($search);
- }
-
- // If replace isn't an array, make it one, and pad it to the length of search
- if (!is_array($replace))
- {
- $replace_string = $replace;
-
- $replace = array ();
- for ($i = 0, $c = count($search); $i < $c; $i++)
- {
- $replace[$i] = $replace_string;
- }
- }
-
- // Check the replace array is padded to the correct length
- $length_replace = count($replace);
- $length_search = count($search);
- if ($length_replace < $length_search)
- {
- for ($i = $length_replace; $i < $length_search; $i++)
- {
- $replace[$i] = '';
- }
- }
-
- // If subject is not an array, make it one
- $was_array = false;
- if (!is_array($subject)) {
- $was_array = true;
- $subject = array ($subject);
- }
-
- // Loop through each subject
- $count = 0;
- foreach ($subject as $subject_key => $subject_value)
- {
- // Loop through each search
- foreach ($search as $search_key => $search_value)
- {
- // Split the array into segments, in between each part is our search
- $segments = explode(strtolower($search_value), strtolower($subject_value));
-
- // The number of replacements done is the number of segments minus the first
- $count += count($segments) - 1;
- $pos = 0;
-
- // Loop through each segment
- foreach ($segments as $segment_key => $segment_value)
- {
- // Replace the lowercase segments with the upper case versions
- $segments[$segment_key] = substr($subject_value, $pos, strlen($segment_value));
- // Increase the position relative to the initial string
- $pos += strlen($segment_value) + strlen($search_value);
- }
-
- // Put our original string back together
- $subject_value = implode($replace[$search_key], $segments);
- }
-
- $result[$subject_key] = $subject_value;
- }
-
- // Check if subject was initially a string and return it as a string
- if ($was_array === true) {
- return $result[0];
- }
-
- // Otherwise, just return the array
- return $result;
- }
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Alan Morey <alan@caint.com> |
-// | Aidan Lister <aidan@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: str_rot13.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-
-/**
- * Replace str_rot13()
- *
- * @category PHP
- * @package PHP_Compat
- * @link http://php.net/function.str_rot13
- * @author Alan Morey <alan@caint.com>
- * @author Aidan Lister <aidan@php.net>
- * @version $Revision: 1.1.1.1 $
- * @since PHP 4.2.0
- */
-if (!function_exists('str_rot13'))
-{
- function str_rot13($str)
- {
- $from = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
- $to = 'nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM';
-
- return strtr($str, $from, $to);
- }
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Aidan Lister <aidan@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: str_shuffle.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-
-/**
- * Replace str_shuffle()
- *
- * @category PHP
- * @package PHP_Compat
- * @link http://php.net/function.str_shuffle
- * @author Aidan Lister <aidan@php.net>
- * @version $Revision: 1.1.1.1 $
- * @since PHP 4.3.0
- * @require PHP 4.0.1 (trigger_error)
- */
-if (!function_exists('str_shuffle'))
-{
- function str_shuffle($str)
- {
- $newstr = '';
- $strlen = strlen($str);
- $str = (string) $str;
-
- // Seed
- list($usec, $sec) = explode(' ', microtime());
- $seed = (float) $sec + ((float) $usec * 100000);
- mt_srand($seed);
-
- // Shuffle
- for ($i = 0; $strlen > $i; $i++) {
- $newstr .= $str[mt_rand(0, $strlen - 1)];
- }
-
- return $newstr;
- }
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Aidan Lister <aidan@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: str_split.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-
-/**
- * Replace str_split()
- *
- * @category PHP
- * @package PHP_Compat
- * @link http://php.net/function.str_split
- * @author Aidan Lister <aidan@php.net>
- * @version $Revision: 1.1.1.1 $
- * @since PHP 5
- * @require PHP 4.0.1 (trigger_error)
- */
-if (!function_exists('str_split'))
-{
- function str_split($string, $split_length = 1)
- {
- if (!is_numeric($split_length)) {
- trigger_error('str_split() expects parameter 2 to be long, ' . gettype($split_length) . ' given', E_USER_WARNING);
- return false;
- }
-
- if ($split_length < 1) {
- trigger_error('str_split() The the length of each segment must be greater then zero', E_USER_WARNING);
- return false;
- }
-
- preg_match_all('/.{1,' . $split_length . '}/s', $string, $matches);
- return $matches[0];
- }
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Aidan Lister <aidan@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: str_word_count.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-
-/**
- * Replace str_word_count()
- *
- * @category PHP
- * @package PHP_Compat
- * @link http://php.net/function.str_word_count
- * @author Aidan Lister <aidan@php.net>
- * @version $Revision: 1.1.1.1 $
- * @since PHP 4.3.0
- * @require PHP 4.0.1 (trigger_error)
- */
-if (!function_exists('str_word_count'))
-{
- function str_word_count($string, $format = null)
- {
- if ($format != 1 && $format != 2 && $format !== null) {
- trigger_error("str_word_count() The specified format parameter, '$format' is invalid", E_USER_WARNING);
- return false;
- }
-
- $word_string = preg_replace('/[0-9]+/', '', $string);
- $word_array = preg_split('/[^A-Za-z0-9_\']+/', $word_string, -1, PREG_SPLIT_NO_EMPTY);
-
- switch ($format) {
- case null:
- return count($word_array);
- break;
-
- case 1:
- return $word_array;
- break;
-
- case 2:
- $lastmatch = 0;
- $word_assoc = array();
- foreach ($word_array as $word) {
- $word_assoc[$lastmatch = strpos($string, $word, $lastmatch)] = $word;
- }
- return $word_assoc;
- break;
- }
- }
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Aidan Lister <aidan@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: stripos.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-
-/**
- * Replace stripos()
- *
- * @category PHP
- * @package PHP_Compat
- * @link http://php.net/function.stripos
- * @author Aidan Lister <aidan@php.net>
- * @version $Revision: 1.1.1.1 $
- * @since PHP 5
- * @require PHP 4.0.1 (trigger_error)
- */
-if (!function_exists('stripos'))
-{
- function stripos($haystack, $needle, $offset = null)
- {
- if (!is_scalar($haystack)) {
- trigger_error('stripos() expects parameter 1 to be string, ' . gettype($haystack) . ' given', E_USER_WARNING);
- return false;
- }
-
- if (!is_scalar($needle)) {
- trigger_error('stripos() needle is not a string or an integer.', E_USER_WARNING);
- return false;
- }
-
- if (!is_null($offset) && !is_numeric($offset)) {
- trigger_error('stripos() expects parameter 3 to be long, ' . gettype($offset) . ' given', E_USER_WARNING);
- return false;
- }
-
- // Manipulate the string if there is an offset
- $fix = 0;
- if (!is_null($offset))
- {
- if ($offset > 0)
- {
- $haystack = substr($haystack, $offset, strlen($haystack) - $offset);
- $fix = $offset;
- }
- }
-
- $segments = explode(strtolower($needle), strtolower($haystack), 2);
-
- // Check there was a match
- if (count($segments) == 1) {
- return false;
- }
-
- $position = strlen($segments[0]) + $fix;
- return $position;
- }
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Stephan Schmidt <schst@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: strpbrk.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-
-/**
- * Replace strpbrk()
- *
- * @category PHP
- * @package PHP_Compat
- * @link http://php.net/function.strpbrk
- * @author Stephan Schmidt <schst@php.net>
- * @version $Revision: 1.1.1.1 $
- * @since PHP 5
- * @require PHP 4.0.1 (trigger_error)
- */
-if (!function_exists('strpbrk'))
-{
- function strpbrk($haystack, $char_list)
- {
- if (!is_scalar($haystack)) {
- trigger_error('strpbrk() expects parameter 1 to be string, ' . gettype($haystack) . ' given', E_USER_WARNING);
- return false;
- }
-
- if (!is_scalar($char_list)) {
- trigger_error('strpbrk() expects parameter 2 to be scalar, ' . gettype($needle) . ' given', E_USER_WARNING);
- return false;
- }
-
- $haystack = (string) $haystack;
- $char_list = (string) $char_list;
-
- $len = strlen($haystack);
- for ($i = 0; $i < $len; $i++) {
- $char = substr($haystack, $i, 1);
- if (strpos($char_list, $char) === false) {
- continue;
- }
- return substr($haystack, $i);
- }
-
- return false;
- }
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Aidan Lister <aidan@php.net> |
-// | Stephan Schmidt <schst@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: strripos.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-
-/**
- * Replace strripos()
- *
- * @category PHP
- * @package PHP_Compat
- * @link http://php.net/function.strripos
- * @author Aidan Lister <aidan@php.net>
- * @author Stephan Schmidt <schst@php.net>
- * @version $Revision: 1.1.1.1 $
- * @since PHP 5
- * @require PHP 4.0.1 (trigger_error)
- */
-if (!function_exists('strripos'))
-{
- function strripos($haystack, $needle, $offset = null)
- {
- if (!is_scalar($haystack)) {
- trigger_error('strripos() expects parameter 1 to be scalar, ' . gettype($haystack) . ' given', E_USER_WARNING);
- return false;
- }
-
- if (!is_scalar($needle)) {
- trigger_error('strripos() expects parameter 2 to be scalar, ' . gettype($needle) . ' given', E_USER_WARNING);
- return false;
- }
-
- if (!is_null($offset) && !is_numeric($offset)) {
- trigger_error('strripos() expects parameter 3 to be long, ' . gettype($offset) . ' given', E_USER_WARNING);
- return false;
- }
-
- // Manipulate the string if there is an offset
- $fix = 0;
- if (!is_null($offset))
- {
- // If the offset is larger than the haystack, return
- if (abs($offset) >= strlen($haystack)) {
- return false;
- }
-
- // Check whether offset is negative or positive
- if ($offset > 0) {
- $haystack = substr($haystack, $offset, strlen($haystack) - $offset);
- // We need to add this to the position of the needle
- $fix = $offset;
- }
- else {
- $haystack = substr($haystack, 0, strlen($haystack) + $offset);
- }
- }
-
- $segments = explode(strtolower($needle), strtolower($haystack));
-
- $last_seg = count($segments) - 1;
- $position = strlen($haystack) + $fix - strlen($segments[$last_seg]) - strlen($needle);
-
- return $position;
- }
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Tom Buskens <ortega@php.net> |
-// | Aidan Lister <aidan@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: substr_compare.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-
-/**
- * Replace substr_compare()
- *
- * @category PHP
- * @package PHP_Compat
- * @link http://php.net/function.substr_compare
- * @author Tom Buskens <ortega@php.net>
- * @author Aidan Lister <aidan@php.net>
- * @version $Revision: 1.1.1.1 $
- * @since PHP 5
- * @require PHP 4.0.1 (trigger_error)
- */
-if (!function_exists('substr_compare'))
-{
- function substr_compare($main_str, $str, $offset, $length = null, $case_insensitive = false)
- {
- if (!is_string($main_str)) {
- trigger_error('substr_compare() expects parameter 1 to be string, ' . gettype($main_str) . ' given', E_USER_WARNING);
- return;
- }
-
- if (!is_string($str)) {
- trigger_error('substr_compare() expects parameter 2 to be string, ' . gettype($str) . ' given', E_USER_WARNING);
- return;
- }
-
- if (!is_int($offset)) {
- trigger_error('substr_compare() expects parameter 3 to be long, ' . gettype($offset) . ' given', E_USER_WARNING);
- return;
- }
-
- if (is_null($length)) {
- $length = strlen($main_str) - $offset;
- } elseif ($offset >= strlen($main_str)) {
- trigger_error('substr_compare() The start position cannot exceed initial string length', E_USER_WARNING);
- return false;
- }
-
- $main_str = substr($main_str, $offset, $length);
- $str = substr($str, 0, strlen($main_str));
-
- if ($case_insensitive === false) {
- return strcmp($main_str, $str);
- } else {
- return strcasecmp($main_str, $str);
- }
- }
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Aidan Lister <aidan@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: var_export.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-
-/**
- * Replace var_export()
- *
- * @category PHP
- * @package PHP_Compat
- * @link http://php.net/function.var_export
- * @author Aidan Lister <aidan@php.net>
- * @version $Revision: 1.1.1.1 $
- * @since PHP 4.2.0
- * @require PHP 4.0.1 (trigger_error)
- */
-if (!function_exists('var_export'))
-{
- function var_export($array, $return = false)
- {
- // Common output variables
- $indent = ' ';
- $doublearrow = ' => ';
- $lineend = ",\n";
- $stringdelim = '\'';
- $newline = "\n";
-
- // Check the export isn't a simple string / int
- if (is_string($array)) {
- $out = $stringdelim . $array . $stringdelim;
- }
- elseif (is_int($array)) {
- $out = (string)$array;
- }
-
- // Begin the array export
- else
- {
- // Start the string
- $out = "array (\n";
-
- // Loop through each value in array
- foreach ($array as $key => $value)
- {
- // If the key is a string, delimit it
- if (is_string($key)) {
- $key = $stringdelim . addslashes($key) . $stringdelim;
- }
-
- // If the value is a string, delimit it
- if (is_string($value)) {
- $value = $stringdelim . addslashes($value) . $stringdelim;
- }
-
- // We have an array, so do some recursion
- elseif (is_array($value))
- {
- // Do some basic recursion while increasing the indent
- $recur_array = explode($newline, var_export($value, true));
- $recur_newarr = array ();
- foreach ($recur_array as $recur_line) {
- $recur_newarr[] = $indent . $recur_line;
- }
- $recur_array = implode($newline, $recur_newarr);
- $value = $newline . $recur_array;
- }
-
- // Piece together the line
- $out .= $indent . $key . $doublearrow . $value . $lineend;
- }
-
- // End our string
- $out .= ")";
- }
-
-
- // Decide method of output
- if ($return === true) {
- return $out;
- } else {
- echo $out;
- return;
- }
- }
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Philippe Jausions <Philippe.Jausions@11abacus.com> |
-// | Aidan Lister <aidan@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: version_compare.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-
-/**
- * Replace version_compare()
- *
- * @category PHP
- * @package PHP_Compat
- * @link http://php.net/function.version_compare
- * @author Philippe Jausions <Philippe.Jausions@11abacus.com>
- * @author Aidan Lister <aidan@php.net>
- * @version $Revision: 1.1.1.1 $
- * @since PHP 4.1.0
- * @require PHP 4.0.1 (trigger_error)
- */
-if (!function_exists('version_compare')) {
-
- function version_compare ($version1, $version2, $operator = '<')
- {
- // Check input
- if (!is_scalar($version1)) {
- trigger_error('version_compare() expects parameter 1 to be string, ' . gettype($version1) . ' given', E_USER_WARNING);
- return;
- }
-
- if (!is_scalar($version2)) {
- trigger_error('version_compare() expects parameter 2 to be string, ' . gettype($version2) . ' given', E_USER_WARNING);
- return;
- }
-
- if (!is_scalar($operator)) {
- trigger_error('version_compare() expects parameter 3 to be string, ' . gettype($operator) . ' given', E_USER_WARNING);
- return;
- }
-
- // Standardise versions
- $v1 = explode('.',
- str_replace('..', '.',
- preg_replace('/([^0-9\.]+)/', '.$1.',
- str_replace(array('-', '_', '+'), '.',
- trim($version1)))));
-
- $v2 = explode('.',
- str_replace('..', '.',
- preg_replace('/([^0-9\.]+)/', '.$1.',
- str_replace(array('-', '_', '+'), '.',
- trim($version2)))));
-
- // Replace empty entries at the start of the array
- while (empty($v1[0]) && array_shift($v1)) {}
- while (empty($v2[0]) && array_shift($v2)) {}
-
- // Describe our release states
- $versions = array(
- 'dev' => 0,
- 'alpha' => 1,
- 'a' => 1,
- 'beta' => 2,
- 'b' => 2,
- 'RC' => 3,
- 'pl' => 4);
-
- // Loop through each segment in the version string
- $compare = 0;
- for ($i = 0, $x = min(count($v1), count($v2)); $i < $x; $i++)
- {
- if ($v1[$i] == $v2[$i]) {
- continue;
- }
- if (is_numeric($v1[$i]) && is_numeric($v2[$i])) {
- $compare = ($v1[$i] < $v2[$i]) ? -1 : 1;
- }
- elseif (is_numeric($v1[$i])) {
- $compare = 1;
- }
- elseif (is_numeric($v2[$i])) {
- $compare = -1;
- }
- elseif (isset($versions[$v1[$i]]) && isset($versions[$v2[$i]])) {
- $compare = ($versions[$v1[$i]] < $versions[$v2[$i]]) ? -1 : 1;
- }
- else {
- $compare = strcmp($v2[$i], $v1[$i]);
- }
-
- break;
- }
-
- // If previous loop didn't find anything, compare the "extra" segments
- if ($compare == 0) {
- if (count($v2) > count($v1))
- {
- if (isset($versions[$v2[$i]])) {
- $compare = ($versions[$v2[$i]] < 4) ? 1 : -1;
- } else {
- $compare = -1;
- }
- }
- elseif (count($v2) < count($v1))
- {
- if (isset($versions[$v1[$i]])) {
- $compare = ($versions[$v1[$i]] < 4) ? -1 : 1;
- } else {
- $compare = 1;
- }
- }
- }
-
- // Compare the versions
- if (func_num_args() > 2)
- {
- switch ($operator)
- {
- case '>':
- case 'gt':
- return (bool) ($compare > 0);
- break;
- case '>=':
- case 'ge':
- return (bool) ($compare >= 0);
- break;
- case '<=':
- case 'le':
- return (bool) ($compare <= 0);
- break;
- case '==':
- case '=':
- case 'eq':
- return (bool) ($compare == 0);
- break;
- case '<>':
- case '!=':
- case 'ne':
- return (bool) ($compare != 0);
- break;
- case '':
- case '<':
- case 'lt':
- return (bool) ($compare < 0);
- break;
- default:
- return;
- }
- }
-
- return $compare;
- }
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Aidan Lister <aidan@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: vprintf.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-
-/**
- * Replace vprintf()
- *
- * @category PHP
- * @package PHP_Compat
- * @link http://php.net/function.vprintf
- * @author Aidan Lister <aidan@php.net>
- * @version $Revision: 1.1.1.1 $
- * @since PHP 4.1.0
- * @require PHP 4.0.4 (call_user_func_array)
- */
-if (!function_exists('vprintf'))
-{
- function vprintf ($format, $args)
- {
- if (count($args) < 2) {
- trigger_error('vprintf() Too few arguments', E_USER_WARNING);
- return;
- }
-
- array_unshift($args, $format);
- return call_user_func_array('printf', $args);
- }
-}
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Aidan Lister <aidan@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: vsprintf.php,v 1.1.1.1 2008/04/28 15:20:49 jamie Exp $
-
-
-/**
- * Replace vsprintf()
- *
- * @category PHP
- * @package PHP_Compat
- * @link http://php.net/function.vsprintf
- * @author Aidan Lister <aidan@php.net>
- * @version $Revision: 1.1.1.1 $
- * @since PHP 4.1.0
- * @require PHP 4.0.4 (call_user_func_array)
- */
-if (!function_exists('vsprintf'))
-{
- function vsprintf ($format, $args)
- {
- if (count($args) < 2) {
- trigger_error('vsprintf() Too few arguments', E_USER_WARNING);
- return;
- }
-
- array_unshift($args, $format);
- return call_user_func_array('sprintf', $args);
- }
-}
-
-?>
\ No newline at end of file
+++ /dev/null
---TEST--
-Constant -- E_STRICT
---SKIPIF--
-<?php if (defined('E_STRICT')) { echo 'skip'; } ?>
---FILE--
-<?php
-require_once ('PHP/Compat.php');
-PHP_Compat::loadConstant('E_STRICT');
-
-echo E_STRICT;
-?>
---EXPECT--
-2048
\ No newline at end of file
+++ /dev/null
---TEST--
-Constant -- File System Constants
---SKIPIF--
-<?php if (defined('FILE_USE_INCLUDE_PATH')) { echo 'skip'; } ?>
---FILE--
-<?php
-require_once ('PHP/Compat.php');
-PHP_Compat::loadConstant('FILE');
-
-echo FILE_USE_INCLUDE_PATH, "\n";
-echo FILE_IGNORE_NEW_LINES, "\n";
-echo FILE_SKIP_EMPTY_LINES, "\n";
-echo FILE_APPEND, "\n";
-echo FILE_NO_DEFAULT_CONTEXT
-?>
---EXPECT--
-1
-2
-4
-8
-16
\ No newline at end of file
+++ /dev/null
---TEST--
-Constant -- PATH_SEPARATOR
---SKIPIF--
-<?php if (defined('PATH_SEPARATOR')) { echo 'skip'; } ?>
---FILE--
-<?php
-require_once ('PHP/Compat.php');
-PHP_Compat::loadConstant('PATH_SEPARATOR');
-
-echo (PATH_SEPARATOR == ';' || PATH_SEPARATOR == ':') ?
- 'true' :
- 'false';
-?>
---EXPECT--
-true
\ No newline at end of file
+++ /dev/null
---TEST--
-Constant -- CLI Constants
---SKIPIF--
-<?php if (defined('STDIN')) { echo 'skip'; } ?>
---FILE--
-<?php
-require_once ('PHP/Compat.php');
-PHP_Compat::loadConstant('STD');
-
-echo (is_resource(STDIN)) ? 'true' : 'false', "\n";
-echo (is_resource(STDOUT)) ? 'true' : 'false', "\n";
-echo (is_resource(STDERR)) ? 'true' : 'false';
-?>
---EXPECT--
-true
-true
-true
\ No newline at end of file
+++ /dev/null
---TEST--
-Function -- array_change_key_case
---SKIPIF--
-<?php if (function_exists('array_change_key_case')) { echo 'skip'; } ?>
---FILE--
-<?php
-require_once 'PHP/Compat.php';
-PHP_Compat::loadFunction('array_change_key_case');
-
-$in = array('FirSt' => 1, 'SecOnd' => 4);
-print_r(array_change_key_case($in));
-print_r(array_change_key_case($in, CASE_LOWER));
-print_r(array_change_key_case($in, CASE_UPPER));
-$in = array('FIRST' => 1, 'SECOND' => 4);
-print_r(array_change_key_case($in));
-print_r(array_change_key_case($in, CASE_LOWER));
-print_r(array_change_key_case($in, CASE_UPPER));
-$in = array('first' => 1, 'second' => 4);
-print_r(array_change_key_case($in));
-print_r(array_change_key_case($in, CASE_LOWER));
-print_r(array_change_key_case($in, CASE_UPPER));
-$in = array('foo', 'bar');
-print_r(array_change_key_case($in));
-print_r(array_change_key_case($in, CASE_LOWER));
-print_r(array_change_key_case($in, CASE_UPPER));
-$in = array();
-print_r(array_change_key_case($in));
-print_r(array_change_key_case($in, CASE_LOWER));
-print_r(array_change_key_case($in, CASE_UPPER));
-?>
---EXPECT--
-Array
-(
- [first] => 1
- [second] => 4
-)
-Array
-(
- [first] => 1
- [second] => 4
-)
-Array
-(
- [FIRST] => 1
- [SECOND] => 4
-)
-Array
-(
- [first] => 1
- [second] => 4
-)
-Array
-(
- [first] => 1
- [second] => 4
-)
-Array
-(
- [FIRST] => 1
- [SECOND] => 4
-)
-Array
-(
- [first] => 1
- [second] => 4
-)
-Array
-(
- [first] => 1
- [second] => 4
-)
-Array
-(
- [FIRST] => 1
- [SECOND] => 4
-)
-Array
-(
- [0] => foo
- [1] => bar
-)
-Array
-(
- [0] => foo
- [1] => bar
-)
-Array
-(
- [0] => foo
- [1] => bar
-)
-Array
-(
-)
-Array
-(
-)
-Array
-(
-)
\ No newline at end of file
+++ /dev/null
---TEST--
-Function -- array_chunk
---SKIPIF--
-<?php if (function_exists('array_chunk')) { echo 'skip'; } ?>
---FILE--
-<?php
-require_once 'PHP/Compat.php';
-PHP_Compat::loadFunction('array_chunk');
-
-$input_array = array(2 => 'a', 3 => 'b', 4 => 'c', 5 => 'd', 6 => 'e');
-print_r(array_chunk($input_array, 2));
-print_r(array_chunk($input_array, 2, true));
-print_r(array_chunk($input_array, 3));
-print_r(array_chunk($input_array, 3, true));
-print_r(array_chunk($input_array, 4));
-print_r(array_chunk($input_array, 4, true));
-print_r(array_chunk($input_array, 5));
-print_r(array_chunk($input_array, 5, true));
-print_r(array_chunk($input_array, 6));
-print_r(array_chunk($input_array, 6, true));
-?>
---EXPECT--
-Array
-(
- [0] => Array
- (
- [0] => a
- [1] => b
- )
-
- [1] => Array
- (
- [0] => c
- [1] => d
- )
-
- [2] => Array
- (
- [0] => e
- )
-
-)
-Array
-(
- [0] => Array
- (
- [2] => a
- [3] => b
- )
-
- [1] => Array
- (
- [4] => c
- [5] => d
- )
-
- [2] => Array
- (
- [6] => e
- )
-
-)
-Array
-(
- [0] => Array
- (
- [0] => a
- [1] => b
- [2] => c
- )
-
- [1] => Array
- (
- [0] => d
- [1] => e
- )
-
-)
-Array
-(
- [0] => Array
- (
- [2] => a
- [3] => b
- [4] => c
- )
-
- [1] => Array
- (
- [5] => d
- [6] => e
- )
-
-)
-Array
-(
- [0] => Array
- (
- [0] => a
- [1] => b
- [2] => c
- [3] => d
- )
-
- [1] => Array
- (
- [0] => e
- )
-
-)
-Array
-(
- [0] => Array
- (
- [2] => a
- [3] => b
- [4] => c
- [5] => d
- )
-
- [1] => Array
- (
- [6] => e
- )
-
-)
-Array
-(
- [0] => Array
- (
- [0] => a
- [1] => b
- [2] => c
- [3] => d
- [4] => e
- )
-
-)
-Array
-(
- [0] => Array
- (
- [2] => a
- [3] => b
- [4] => c
- [5] => d
- [6] => e
- )
-
-)
-Array
-(
- [0] => Array
- (
- [0] => a
- [1] => b
- [2] => c
- [3] => d
- [4] => e
- )
-
-)
-Array
-(
- [0] => Array
- (
- [2] => a
- [3] => b
- [4] => c
- [5] => d
- [6] => e
- )
-
-)
\ No newline at end of file
+++ /dev/null
---TEST--
-Function -- array_combine
---SKIPIF--
-<?php if (function_exists('array_combine')) { echo 'skip'; } ?>
---FILE--
-<?php
-require_once 'PHP/Compat.php';
-PHP_Compat::loadFunction('array_combine');
-
-$a = array('green', 'red', 'yellow');
-$b = array('avocado', 'apple', 'banana');
-$c = array_combine($a, $b);
-
-print_r($c);
-?>
---EXPECT--
-Array
-(
- [green] => avocado
- [red] => apple
- [yellow] => banana
-)
\ No newline at end of file
+++ /dev/null
---TEST--
-Function -- array_diff_assoc
---SKIPIF--
-<?php if (function_exists('array_diff_assoc')) { echo 'skip'; } ?>
---FILE--
-<?php
-require_once 'PHP/Compat.php';
-PHP_Compat::loadFunction('array_diff_assoc');
-
-$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
-$array2 = array("a" => "green", "yellow", "red");
-$result = array_diff_assoc($array1, $array2);
-print_r($result);
-?>
---EXPECT--
-Array
-(
- [b] => brown
- [c] => blue
- [0] => red
-)
\ No newline at end of file
+++ /dev/null
---TEST--
-Function -- array_key_exists
---SKIPIF--
-<?php if (function_exists('array_key_exists')) { echo 'skip'; } ?>
---FILE--
-<?php
-require_once 'PHP/Compat.php';
-PHP_Compat::loadFunction('array_key_exists');
-
-$search_array = array("first" => 1, "second" => 4);
-if (array_key_exists("first", $search_array)) {
- echo "The 'first' element is in the array";
-}
-?>
---EXPECT--
-The 'first' element is in the array
\ No newline at end of file
+++ /dev/null
---TEST--
-Function -- array_search
---SKIPIF--
-<?php if (function_exists('array_search')) { echo 'skip'; } ?>
---FILE--
-<?php
-require_once 'PHP/Compat.php';
-PHP_Compat::loadFunction('array_search');
-
-$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
-
-var_dump(array_search('green', $array));
-var_dump(array_search('red', $array));
-?>
---EXPECT--
-int(2)
-int(1)
\ No newline at end of file
+++ /dev/null
---TEST--
-Function -- array_udiff
---SKIPIF--
-<?php if (function_exists('array_udiff')) { echo 'skip'; } ?>
---FILE--
-<?php
-require_once 'PHP/Compat.php';
-PHP_Compat::loadFunction('array_udiff');
-
-class cr {
- var $priv_member;
- function cr($val)
- {
- $this->priv_member = $val;
- }
-
- function comp_func_cr($a, $b)
- {
- if ($a->priv_member === $b->priv_member) return 0;
- return ($a->priv_member > $b->priv_member)? 1:-1;
- }
-}
-
-$a = array("0.1" => new cr(9), "0.5" => new cr(12), 0 => new cr(23), 1=> new cr(4), 2 => new cr(-15),);
-$b = array("0.2" => new cr(9), "0.5" => new cr(22), 0 => new cr(3), 1=> new cr(4), 2 => new cr(-15),);
-
-$result = array_udiff($a, $b, array("cr", "comp_func_cr"));
-echo serialize($result);
-?>
---EXPECT--
-a:2:{s:3:"0.5";O:2:"cr":1:{s:11:"priv_member";i:12;}i:0;O:2:"cr":1:{s:11:"priv_member";i:23;}}
\ No newline at end of file
+++ /dev/null
---TEST--
-Function -- array_udiff_assoc
---SKIPIF--
-<?php if (function_exists('array_udiff_assoc')) { echo 'skip'; } ?>
---FILE--
-<?php
-require_once 'PHP/Compat.php';
-PHP_Compat::loadFunction('array_udiff_assoc');
-
-class cr {
- var $priv_member;
- function cr($val)
- {
- $this->priv_member = $val;
- }
-
- function comp_func_cr($a, $b)
- {
- if ($a->priv_member === $b->priv_member) return 0;
- return ($a->priv_member > $b->priv_member)? 1:-1;
- }
-}
-
-$a = array("0.1" => new cr(9), "0.5" => new cr(12), 0 => new cr(23), 1=> new cr(4), 2 => new cr(-15),);
-$b = array("0.2" => new cr(9), "0.5" => new cr(22), 0 => new cr(3), 1=> new cr(4), 2 => new cr(-15),);
-
-$result = array_udiff_assoc($a, $b, array("cr", "comp_func_cr"));
-echo serialize($result);
-?>
---EXPECT--
-a:3:{s:3:"0.1";O:2:"cr":1:{s:11:"priv_member";i:9;}s:3:"0.5";O:2:"cr":1:{s:11:"priv_member";i:12;}i:0;O:2:"cr":1:{s:11:"priv_member";i:23;}}
\ No newline at end of file
+++ /dev/null
---TEST--
-Function -- array_udiff_uassoc
---SKIPIF--
-<?php if (function_exists('array_udiff_uassoc')) { echo 'skip'; } ?>
---FILE--
-<?php
-require_once 'PHP/Compat.php';
-PHP_Compat::loadFunction('array_udiff_uassoc');
-
-class cr
-{
- var $val;
-
- function cr($val)
- {
- $this->val = $val;
- }
-
- function comp_func_cr($a, $b)
- {
- if ($a->val === $b->val) return 0;
- return ($a->val > $b->val) ? 1 : -1;
- }
-
- function comp_func_key($a, $b)
- {
- if ($a === $b) return 0;
- return ($a > $b) ? 1 : -1;
- }
-}
-
-$a = array('0.1' => new cr(9), '0.5' => new cr(12), 0 => new cr(23), 1 => new cr(4), 2 => new cr(-15));
-$b = array('0.2' => new cr(9), '0.5' => new cr(22), 0 => new cr(3), 1 => new cr(4), 2 => new cr(-15));
-
-$result = array_udiff_uassoc($a, $b, array('cr', 'comp_func_cr'), array('cr', 'comp_func_key'));
-print_r($result);
-?>
---EXPECT--
-Array
-(
- [0.1] => cr Object
- (
- [val] => 9
- )
-
- [0.5] => cr Object
- (
- [val] => 12
- )
-
- [0] => cr Object
- (
- [val] => 23
- )
-
-)
\ No newline at end of file
+++ /dev/null
---TEST--
-Function -- array_uintersect
---SKIPIF--
-<?php if (function_exists('array_uintersect')) { echo 'skip'; } ?>
---FILE--
-<?php
-require_once 'PHP/Compat.php';
-PHP_Compat::loadFunction('array_uintersect');
-
-$array1 = array('a' => 'green', 'b' => 'brown', 'c' => 'blue', 'red');
-$array2 = array('a' => 'GREEN', 'B' => 'brown', 'yellow', 'red');
-
-print_r(array_uintersect($array1, $array2, 'strcasecmp'));
-?>
---EXPECT--
-Array
-(
- [a] => green
- [b] => brown
- [0] => red
-)
\ No newline at end of file
+++ /dev/null
---TEST--
-Function -- array_uintersect_assoc
---SKIPIF--
-<?php if (function_exists('array_uintersect_assoc')) { echo 'skip'; } ?>
---FILE--
-<?php
-require_once 'PHP/Compat.php';
-PHP_Compat::loadFunction('array_uintersect_assoc');
-
-$array1 = array('a' => 'green', 'b' => 'brown', 'c' => 'blue', 'red');
-$array2 = array('a' => 'GREEN', 'B' => 'brown', 'yellow', 'red');
-
-print_r(array_uintersect_assoc($array1, $array2, 'strcasecmp'));
-?>
---EXPECT--
-Array
-(
- [a] => green
-)
\ No newline at end of file
+++ /dev/null
---TEST--
-Function -- array_uintersect_uassoc
---SKIPIF--
-<?php if (function_exists('array_uintersect_uassoc')) { echo 'skip'; } ?>
---FILE--
-<?php
-require_once 'PHP/Compat.php';
-PHP_Compat::loadFunction('array_uintersect_uassoc');
-
-$array1 = array('a' => 'green', 'b' => 'brown', 'c' => 'blue', 'red');
-$array2 = array('a' => 'GREEN', 'B' => 'brown', 'yellow', 'red');
-
-print_r(array_uintersect_uassoc($array1, $array2, 'strcasecmp', 'strcasecmp'));
-?>
---EXPECT--
-Array
-(
- [a] => green
- [b] => brown
-)
\ No newline at end of file
+++ /dev/null
---TEST--
-Function -- array_walk_recursive
---SKIPIF--
-<?php if (function_exists('array_walk_recursive')) { echo 'skip'; } ?>
---FILE--
-<?php
-require_once 'PHP/Compat.php';
-PHP_Compat::loadFunction('array_walk_recursive');
-
-$sweet = array('a' => 'apple', 'b' => 'banana');
-$fruits = array('sweet' => $sweet, 'sour' => 'lemon');
-
-function test_print($item, $key)
-{
- echo "$key holds $item\n";
-}
-
-array_walk_recursive($fruits, 'test_print');
-?>
---EXPECT--
-a holds apple
-b holds banana
-sour holds lemon
\ No newline at end of file
+++ /dev/null
---TEST--
-Function -- call_user_func_array
---SKIPIF--
-<?php if (function_exists('call_user_func_array')) { echo 'skip'; } ?>
---FILE--
-<?php
-require_once 'PHP/Compat.php';
-PHP_Compat::loadFunction('call_user_func_array');
-
-function somefunc ($param1, $param2, $param3) {
- echo $param1, "\n", $param2, "\n", $param3;
-}
-
-$args = array ('foo', 'bar', 'meta');
-call_user_func_array('somefunc', $args);
-?>
---EXPECT--
-foo
-bar
-meta
\ No newline at end of file
+++ /dev/null
---TEST--
-Function -- constant
---SKIPIF--
-<?php if (function_exists('constant')) { echo 'skip'; } ?>
---FILE--
-<?php
-require_once 'PHP/Compat.php';
-PHP_Compat::loadFunction('constant');
-
-$constant = 'BAR';
-define($constant, 'foo');
-echo constant($constant);
-?>
---EXPECT--
-foo
\ No newline at end of file
+++ /dev/null
---TEST--
-Function -- convert_uudecode
---SKIPIF--
-<?php if (function_exists('convert_uudecode')) { echo 'skip'; } ?>
---FILE--
-<?php
-require_once 'PHP/Compat.php';
-PHP_Compat::loadFunction('convert_uudecode');
-
-$string = base64_decode('NTUmQUk8UiFJPFIhQSgnLUk7NyFMOTIhVDk3LVQKYAo=');
-echo convert_uudecode($string);
-?>
---EXPECT--
-This is a simple test
\ No newline at end of file
+++ /dev/null
---TEST--
-Function -- convert_uuencode
---SKIPIF--
-<?php if (function_exists('convert_uuencode')) { echo 'skip'; } ?>
---FILE--
-<?php
-require_once 'PHP/Compat.php';
-PHP_Compat::loadFunction('convert_uuencode');
-
-// Simple test
-echo md5(convert_uuencode('This is a simple test')), "\n";
-
-// Really messy test
-$string = '';
-for ($i = 0; 127 > $i; $i++) {
- $string .= str_repeat(chr($i), 10);
-}
-echo md5(convert_uuencode($string));
-
-?>
---EXPECT--
-d7974131c8970783f70851c83fe17767
-19acf7157a8345307ea5e5ea6878abb4
\ No newline at end of file
+++ /dev/null
---TEST--
-Function -- file_get_contents
---SKIPIF--
-<?php if (function_exists('file_get_contents')) { echo 'skip'; } ?>
---FILE--
-<?php
-require_once 'PHP/Compat.php';
-PHP_Compat::loadFunction('file_get_contents');
-
-$tmpfname = tempnam('/tmp', 'php');
-$handle = fopen($tmpfname, 'w');
-fwrite($handle, "test test");
-fclose($handle);
-
-echo file_get_contents($tmpfname);
-
-unlink($tmpfname);
-?>
---EXPECT--
-test test
\ No newline at end of file
+++ /dev/null
---TEST--
-Function -- file_put_contents
---SKIPIF--
-<?php if (function_exists('file_put_contents')) { echo 'skip'; } ?>
---FILE--
-<?php
-require_once 'PHP/Compat.php';
-PHP_Compat::loadFunction('file_put_contents');
-
-// Create a temp file
-$tmpfname = tempnam('/tmp', 'phpcompat');
-
-// With a string
-$string = "abcd";
-
-echo file_put_contents($tmpfname, $string), "\n";
-echo implode('', file($tmpfname)), "\n";
-
-// With an array
-$string = array('foo', 'bar');
-
-echo file_put_contents($tmpfname, $string), "\n";
-echo implode('', file($tmpfname)), "\n";
-
-// Test append
-$string = 'foobar';
-$string2 = 'testtest';
-$tmpfname = tempnam('/tmp', 'php');
-
-echo file_put_contents($tmpfname, $string), "\n";
-echo file_put_contents($tmpfname, $string2, FILE_APPEND), "\n";
-echo implode('', file($tmpfname)), "\n";
-echo file_put_contents($tmpfname, $string2), "\n";
-echo implode('', file($tmpfname));
-
-unlink($tmpfname);
-?>
---EXPECT--
-4
-abcd
-6
-foobar
-6
-8
-foobartesttest
-8
-testtest
\ No newline at end of file
+++ /dev/null
---TEST--
-Function -- fprintf
---SKIPIF--
-<?php if (function_exists('fprintf')) { echo 'skip'; } ?>
---FILE--
-<?php
-require_once 'PHP/Compat.php';
-PHP_Compat::loadFunction('fprintf');
-
-$tmpfname = tempnam('/tmp', 'php');
-$handle = fopen($tmpfname, 'w');
-fprintf($handle, 'The %s went to the %s for %d days', 'dog', 'park', 2);
-fclose($handle);
-$data = implode('', file($tmpfname));
-unlink($tmpfname);
-
-echo $data;
-?>
---EXPECT--
-The dog went to the park for 2 days
\ No newline at end of file
+++ /dev/null
---TEST--
-Function -- get_include_path
---SKIPIF--
-<?php if (function_exists('get_include_path')) { echo 'skip'; } ?>
---FILE--
-<?php
-require_once 'PHP/Compat.php';
-PHP_Compat::loadFunction('get_include_path');
-
-if (get_include_path() == ini_get('include_path')) {
- echo 'true';
-}
-?>
---EXPECT--
-true
\ No newline at end of file
+++ /dev/null
---TEST--
-Function -- html_entity_decode
---SKIPIF--
-<?php if (function_exists('html_entity_decode')) { echo 'skip'; } ?>
---FILE--
-<?php
-require_once 'PHP/Compat.php';
-PHP_Compat::loadFunction('html_entity_decode');
-
-$string = "I'll "walk" the <b>dog</b> now";
-echo html_entity_decode($string), "\n";
-echo html_entity_decode($string, ENT_COMPAT), "\n";
-echo html_entity_decode($string, ENT_QUOTES), "\n";
-echo html_entity_decode($string, ENT_NOQUOTES), "\n";
-?>
---EXPECT--
-I'll "walk" the <b>dog</b> now
-I'll "walk" the <b>dog</b> now
-I'll "walk" the <b>dog</b> now
-I'll "walk" the <b>dog</b> now
\ No newline at end of file
+++ /dev/null
---TEST--
-Function -- http_build_query
---SKIPIF--
-<?php if (function_exists('http_build_query')) { echo 'skip'; } ?>
---FILE--
-<?php
-require_once 'PHP/Compat.php';
-PHP_Compat::loadFunction('http_build_query');
-
-// Simple
-$data = array('foo'=>'bar',
- 'baz'=>'boom',
- 'cow'=>'milk',
- 'php'=>'hypertext processor');
-
-echo http_build_query($data), "\n";
-
-
-// With an object
-class myClass {
- var $foo;
- var $baz;
-
- function myClass()
- {
- $this->foo = 'bar';
- $this->baz = 'boom';
- }
-}
-
-$data = new myClass();
-echo http_build_query($data), "\n";
-
-
-// With numerically indexed elements
-$data = array('foo', 'bar', 'baz', 'boom', 'cow' => 'milk', 'php' =>'hypertext processor');
-echo http_build_query($data), "\n";
-echo http_build_query($data, 'myvar_'), "\n";
-
-
-// With a complex array
-$data = array('user'=>array('name'=>'Bob Smith',
- 'age'=>47,
- 'sex'=>'M',
- 'dob'=>'5/12/1956'),
- 'pastimes'=>array('golf', 'opera', 'poker', 'rap'),
- 'children'=>array('bobby'=>array('age'=>12,
- 'sex'=>'M'),
- 'sally'=>array('age'=>8,
- 'sex'=>'F')),
- 'CEO');
-
-echo http_build_query($data, 'flags_');
-?>
---EXPECT--
-foo=bar&baz=boom&cow=milk&php=hypertext+processor
-foo=bar&baz=boom
-0=foo&1=bar&2=baz&3=boom&cow=milk&php=hypertext+processor
-myvar_0=foo&myvar_1=bar&myvar_2=baz&myvar_3=boom&cow=milk&php=hypertext+processor
-user[name]=Bob+Smith&user[age]=47&user[sex]=M&user[dob]=5%2F12%2F1956&pastimes[0]=golf&pastimes[1]=opera&pastimes[2]=poker&pastimes[3]=rap&children[bobby][age]=12&children[bobby][sex]=M&children[sally][age]=8&children[sally][sex]=F&flags_0=CEO
\ No newline at end of file
+++ /dev/null
---TEST--
-Function -- image_type_to_mime_type
---SKIPIF--
-<?php if (function_exists('image_type_to_mime_type')) { echo 'skip'; } ?>
---FILE--
-<?php
-require_once 'PHP/Compat.php';
-PHP_Compat::loadFunction('image_type_to_mime_type');
-
-$types = array (
- IMAGETYPE_GIF,
- IMAGETYPE_JPEG,
- IMAGETYPE_PNG,
- IMAGETYPE_SWF,
- IMAGETYPE_PSD,
- IMAGETYPE_BMP,
- IMAGETYPE_TIFF_II,
- IMAGETYPE_TIFF_MM,
- IMAGETYPE_JPC,
- IMAGETYPE_JP2,
- IMAGETYPE_JPX,
- IMAGETYPE_JB2,
- IMAGETYPE_SWC,
- IMAGETYPE_IFF,
- IMAGETYPE_WBMP,
- IMAGETYPE_XBM
-);
-
-foreach ($types as $type) {
- echo image_type_to_mime_type($type), "\n";
-}
-?>
---EXPECT--
-image/gif
-image/jpeg
-image/png
-application/x-shockwave-flash
-image/psd
-image/bmp
-image/tiff
-image/tiff
-application/octet-stream
-image/jp2
-application/octet-stream
-application/octet-stream
-application/x-shockwave-flash
-image/iff
-image/vnd.wap.wbmp
-image/xbm
\ No newline at end of file
+++ /dev/null
---TEST--
-Function -- is_a
---SKIPIF--
-<?php if (function_exists('is_a')) { echo 'skip'; } ?>
---FILE--
-<?php
-require_once 'PHP/Compat.php';
-PHP_Compat::loadFunction('is_a');
-
-class WidgetFactory
-{
- var $oink = 'moo';
-}
-
-$wf = new WidgetFactory();
-
-if (is_a($wf, 'WidgetFactory')) {
- echo 'true';
-}
-?>
---EXPECT--
-true
\ No newline at end of file
+++ /dev/null
---TEST--
-Function -- ob_clean
---SKIPIF--
-<?php if (function_exists('ob_clean')) { echo 'skip'; } ?>
---FILE--
-<?php
-require_once 'PHP/Compat.php';
-PHP_Compat::loadFunction('ob_clean');
-
-ob_start();
-echo 'foo';
-ob_clean();
-echo 'foo';
-ob_end_flush();
-?>
---EXPECT--
-foo
\ No newline at end of file
+++ /dev/null
---TEST--
-Function -- ob_flush
---SKIPIF--
-<?php if (function_exists('ob_flush')) { echo 'skip'; } ?>
---FILE--
-<?php
-require_once 'PHP/Compat.php';
-PHP_Compat::loadFunction('ob_flush');
-
-ob_start();
-echo 'foo';
-ob_flush();
-ob_end_clean();
-?>
---EXPECT--
-foo
\ No newline at end of file
+++ /dev/null
---TEST--
-Function -- ob_get_clean
---SKIPIF--
-<?php if (function_exists('ob_get_clean')) { echo 'skip'; } ?>
---FILE--
-<?php
-require_once 'PHP/Compat.php';
-PHP_Compat::loadFunction('ob_get_clean');
-
-ob_start();
-echo 'foo';
-$buffer = ob_get_clean();
-echo $buffer;
-?>
---EXPECT--
-foo
\ No newline at end of file
+++ /dev/null
---TEST--
-Function -- ob_get_flush
---SKIPIF--
-<?php if (function_exists('ob_get_flush')) { echo 'skip'; } ?>
---FILE--
-<?php
-require_once 'PHP/Compat.php';
-PHP_Compat::loadFunction('ob_get_flush');
-
-ob_start();
-echo 'foo';
-$buffer = ob_get_flush();
-echo $buffer;
-?>
---EXPECT--
-foofoo
\ No newline at end of file
+++ /dev/null
---TEST--
-Function -- php_strip_whitespace
---SKIPIF--
-<?php
-if (function_exists('php_strip_whitespace') ||
- !extension_loaded('tokenizer')) {
-
- echo 'skip';
-}
-?>
---FILE--
-<?php
-require_once 'PHP/Compat.php';
-PHP_Compat::loadFunction('php_strip_whitespace');
-
-// Here is some sample PHP code to write to the file
-$string = '<?php
-// PHP comment here
-
-/*
- * Another PHP comment
- */
-
-echo php_strip_whitespace($_SERVER[\'PHP_SELF\']);
-// Newlines are considered whitespace, and are removed too:
-do_nothing();
-?>';
-
-// Create a temp file
-$tmpfname = tempnam('/tmp', 'phpcompat');
-$fh = fopen($tmpfname, 'w');
-fwrite($fh, $string);
-
-// Test
-echo php_strip_whitespace($tmpfname);
-
-// Close
-fclose($fh);
-?>
---EXPECT--
-<?php
- echo php_strip_whitespace($_SERVER['PHP_SELF']); do_nothing(); ?>
\ No newline at end of file
+++ /dev/null
---TEST--
-Function -- restore_include_path
---SKIPIF--
-<?php if (function_exists('restore_include_path')) { echo 'skip'; } ?>
---FILE--
-<?php
-require_once 'PHP/Compat.php';
-PHP_Compat::loadFunction('restore_include_path');
-
-$orig = ini_get('include_path');
-ini_set('include_path', 'foo');
-echo ini_get('include_path'), "\n";
-
-restore_include_path();
-$new = ini_get('include_path');
-
-if ($orig == $new) {
- echo 'true';
-}
-?>
---EXPECT--
-foo
-true
\ No newline at end of file
+++ /dev/null
---TEST--
-Function -- scandir
---SKIPIF--
-<?php if (function_exists('scandir')) { echo 'skip'; } ?>
---FILE--
-<?php
-require_once 'PHP/Compat.php';
-PHP_Compat::loadFunction('scandir');
-
-// Create a folder and fill it with files
-mkdir('tmp');
-touch('tmp/test1');
-touch('tmp/test2');
-
-// Scan it
-$dir = 'tmp';
-// Not sorted
-$files = scandir($dir);
-// Sorted
-$files2 = scandir($dir, 1);
-
-// List the results
-print_r($files);
-print_r($files2);
-
-// Remove the files
-unlink('tmp/test1');
-unlink('tmp/test2');
-rmdir('tmp');
-?>
---EXPECT--
-Array
-(
- [0] => .
- [1] => ..
- [2] => test1
- [3] => test2
-)
-Array
-(
- [0] => test2
- [1] => test1
- [2] => ..
- [3] => .
-)
\ No newline at end of file
+++ /dev/null
---TEST--
-Function -- set_include_path
---SKIPIF--
-<?php if (function_exists('set_include_path')) { echo 'skip'; } ?>
---FILE--
-<?php
-require_once 'PHP/Compat.php';
-PHP_Compat::loadFunction('set_include_path');
-
-set_include_path('foo');
-echo ini_get('include_path');
-?>
---EXPECT--
-foo
\ No newline at end of file
+++ /dev/null
---TEST--
-Function -- str_ireplace
---SKIPIF--
-<?php if (function_exists('str_ireplace')) { echo 'skip'; } ?>
---FILE--
-<?php
-require_once 'PHP/Compat.php';
-PHP_Compat::loadFunction('str_ireplace');
-
-//
-// Simple
-//
-
-$search = '{object}';
-$replace = 'fence';
-$subject = 'The dog jumped over the {object}';
-
-echo str_ireplace($search, $replace, $subject), "\n";
-
-//
-// Test 1: With subject as array
-//
-
-// As a full array
-$search = '{SUBJECT}';
-$replace = 'Lady';
-$subject = array('A {subject}', 'The {subject}', 'My {subject}');
-print_r(str_ireplace($search, $replace, $subject));
-
-// As a single array
-$search = '{SUBJECT}';
-$replace = 'Lady';
-$subject = array('The dog jumped over the {object}');
-print_r(str_ireplace($search, $replace, $subject));
-
-
-//
-// Test 2: Search as string, replace as array
-//
-
-$search = '{object}';
-$replace = array('cat', 'dog', 'tiger');
-$subject = 'The dog jumped over the {object}';
-// Supress the error, no way of knowing how it'll turn out on the users machine
-echo @str_ireplace($search, $replace, $subject), "\n";
-
-
-//
-// Test 3: Search as array, Replace as string
-//
-
-$search = array('{ANIMAL}', '{OBJECT}', '{THING}');
-$replace = 'frog';
-$subject = 'The {animal} jumped over the {object} and the {thing}...';
-echo str_ireplace($search, $replace, $subject), "\n";
-
-
-//
-// Test 4: Search and Replace as arrays
-//
-
-// Simple
-$search = array('{ANIMAL}', '{OBJECT}');
-$replace = array('frog', 'gate');
-$subject = 'The {animal} jumped over the {object}';
-echo str_ireplace($search, $replace, $subject), "\n";
-
-// More in search
-$search = array('{ANIMAL}', '{OBJECT}', '{THING}');
-$replace = array('frog', 'gate');
-$subject = 'The {animal} jumped over the {object} and the {thing}...';
-echo str_ireplace($search, $replace, $subject), "\n";
-
-// More in replace
-$search = array('{ANIMAL}', '{OBJECT}');
-$replace = array('frog', 'gate', 'door');
-$subject = 'The {animal} jumped over the {object} and the {thing}...';
-echo str_ireplace($search, $replace, $subject), "\n";
-
-
-//
-// Test 5: All arrays
-//
-
-$search = array('{ANIMAL}', '{OBJECT}', '{THING}');
-$replace = array('frog', 'gate', 'beer');
-$subject = array('A {animal}', 'The {object}', 'My {thing}');
-print_r(str_ireplace($search, $replace, $subject));
-
-?>
---EXPECT--
-The dog jumped over the fence
-Array
-(
- [0] => A Lady
- [1] => The Lady
- [2] => My Lady
-)
-Array
-(
- [0] => The dog jumped over the {object}
-)
-The dog jumped over the Array
-The frog jumped over the frog and the frog...
-The frog jumped over the gate
-The frog jumped over the gate and the ...
-The frog jumped over the gate and the {thing}...
-Array
-(
- [0] => A frog
- [1] => The gate
- [2] => My beer
-)
\ No newline at end of file
+++ /dev/null
---TEST--
-Function -- str_rot13
---SKIPIF--
-<?php if (function_exists('str_rot13')) { echo 'skip'; } ?>
---FILE--
-<?php
-require_once 'PHP/Compat.php';
-PHP_Compat::loadFunction('str_rot13');
-
-$str = "The quick brown fox jumped over the lazy dog.";
-echo str_rot13($str);
-?>
---EXPECT--
-Gur dhvpx oebja sbk whzcrq bire gur ynml qbt.
\ No newline at end of file
+++ /dev/null
---TEST--
-Function -- str_shuffle
---SKIPIF--
-<?php if (function_exists('str_shuffle')) { echo 'skip'; } ?>
---FILE--
-<?php
-require_once 'PHP/Compat.php';
-PHP_Compat::loadFunction('str_shuffle');
-
-$string = str_shuffle('ab');
-if ($string == 'ab' ||
- $string == 'ba' ||
- $string == 'aa' ||
- $string == 'bb') {
-
- echo "true";
-}
-?>
---EXPECT--
-true
\ No newline at end of file
+++ /dev/null
---TEST--
-Function -- str_split
---SKIPIF--
-<?php if (function_exists('str_split')) { echo 'skip'; } ?>
---FILE--
-<?php
-require_once 'PHP/Compat.php';
-PHP_Compat::loadFunction('str_split');
-
-$str = "Hello Friend";
-
-// Simple
-$arr = str_split($str);
-print_r($arr);
-
-// With a chunk size specified
-$arr = str_split($str, 3);
-print_r($arr);
-
-// With chunk size bigger than the string
-$arr = str_split($str, 60);
-print_r($arr);
-
-// String that has a remainder less than the chunk size
-$arr = str_split($str, 11);
-print_r($arr);
-?>
---EXPECT--
-Array
-(
- [0] => H
- [1] => e
- [2] => l
- [3] => l
- [4] => o
- [5] =>
- [6] => F
- [7] => r
- [8] => i
- [9] => e
- [10] => n
- [11] => d
-)
-Array
-(
- [0] => Hel
- [1] => lo
- [2] => Fri
- [3] => end
-)
-Array
-(
- [0] => Hello Friend
-)
-Array
-(
- [0] => Hello Frien
- [1] => d
-)
\ No newline at end of file
+++ /dev/null
---TEST--
-Function -- str_word_count
---SKIPIF--
-<?php if (function_exists('str_word_count')) { echo 'skip'; } ?>
---FILE--
-<?php
-require_once 'PHP/Compat.php';
-PHP_Compat::loadFunction('str_word_count');
-
-$str = "Hello friend, you're \r\nsdf\tlooking 3865\t9879 good to\"day, yes \"sir\" you am!";
-var_dump(str_word_count($str));
-print_r(str_word_count($str, 1));
-print_r(str_word_count($str, 2));
-?>
---EXPECT--
-int(12)
-Array
-(
- [0] => Hello
- [1] => friend
- [2] => you're
- [3] => sdf
- [4] => looking
- [5] => good
- [6] => to
- [7] => day
- [8] => yes
- [9] => sir
- [10] => you
- [11] => am
-)
-Array
-(
- [0] => Hello
- [6] => friend
- [14] => you're
- [23] => sdf
- [27] => looking
- [48] => good
- [53] => to
- [56] => day
- [61] => yes
- [66] => sir
- [71] => you
- [75] => am
-)
\ No newline at end of file
+++ /dev/null
---TEST--
-Function -- stripos
---SKIPIF--
-<?php if (function_exists('stripos')) { echo 'skip'; } ?>
---FILE--
-<?php
-require_once 'PHP/Compat.php';
-PHP_Compat::loadFunction('stripos');
-
-$haystack = 'Cat Dinner Dog Lion Mouse Sheep Wolf Cat Dog';
-$needle = 'DOG';
-
-// Simple
-var_dump(stripos($haystack, $needle));
-
-// With offset
-var_dump(stripos($haystack, $needle, 4));
-var_dump(stripos($haystack, $needle, 10));
-var_dump(stripos($haystack, $needle, 15));
-var_dump(stripos($haystack, 'idontexist', 15));
-?>
---EXPECT--
-int(11)
-int(11)
-int(11)
-int(41)
-bool(false)
\ No newline at end of file
+++ /dev/null
---TEST--
-Function -- strpbrk
---SKIPIF--
-<?php if (function_exists('strpbrk')) { echo 'skip'; } ?>
---FILE--
-<?php
-require_once 'PHP/Compat.php';
-PHP_Compat::loadFunction('strpbrk');
-
-$haystack = 'To be or not to be';
-$char_list = 'jhdn';
-
-var_dump(strpbrk($haystack, $char_list));
-?>
---EXPECT--
-string(9) "not to be"
\ No newline at end of file
+++ /dev/null
---TEST--
-Function -- strripos
---SKIPIF--
-<?php if (function_exists('strripos')) { echo 'skip'; } ?>
---FILE--
-<?php
-require_once 'PHP/Compat.php';
-PHP_Compat::loadFunction('strripos');
-
-$haystack = 'Cat Dinner Dog Lion Mouse Sheep Wolf Cat Dog Donut';
-$needle = 'DOG';
-
-// Simple
-var_dump(strripos($haystack, $needle));
-
-// With offset
-var_dump(strripos($haystack, $needle, 3));
-var_dump(strripos($haystack, $needle, 30));
-var_dump(strripos($haystack, $needle, 50));
-var_dump(strripos($haystack, $needle, -1));
-var_dump(strripos($haystack, $needle, -10));
-var_dump(strripos($haystack, $needle, -30));
-var_dump(strripos($haystack, $needle, -50));
-?>
---EXPECT--
-int(41)
-int(41)
-int(41)
-bool(false)
-int(41)
-int(11)
-int(11)
-bool(false)
\ No newline at end of file
+++ /dev/null
---TEST--
-Function -- substr_compare
---SKIPIF--
-<?php if (function_exists('substr_compare')) { echo 'skip'; } ?>
---FILE--
-<?php
-require_once 'PHP/Compat.php';
-PHP_Compat::loadFunction('substr_compare');
-
-echo substr_compare("abcde", "bc", 1, 2), "\n";
-echo substr_compare("abcde", "bcg", 1, 2), "\n";
-echo substr_compare("abcde", "BC", 1, 2, true), "\n";
-echo substr_compare("abcde", "bc", 1, 3), "\n";
-echo substr_compare("abcde", "cd", 1, 2);
-?>
---EXPECT--
-0
-0
-0
-1
--1
\ No newline at end of file
+++ /dev/null
---TEST--
-Function -- var_export
---SKIPIF--
-<?php if (function_exists('var_export')) { echo 'skip'; } ?>
---FILE--
-<?php
-require_once 'PHP/Compat.php';
-PHP_Compat::loadFunction('var_export');
-
-// Simple
-$a = array (1, 2, array ("a", "b", "c"));
-var_export($a);
-echo "\n";
-
-// With return
-echo var_export($a, true);
-?>
---EXPECT--
-array (
- 0 => 1,
- 1 => 2,
- 2 =>
- array (
- 0 => 'a',
- 1 => 'b',
- 2 => 'c',
- ),
-)
-array (
- 0 => 1,
- 1 => 2,
- 2 =>
- array (
- 0 => 'a',
- 1 => 'b',
- 2 => 'c',
- ),
-)
\ No newline at end of file
+++ /dev/null
---TEST--
-Function -- version_compare
---SKIPIF--
-<?php if (function_exists('version_compare')) { echo 'skip'; } ?>
---FILE--
-<?php
-require_once 'PHP/Compat.php';
-PHP_Compat::loadFunction('version_compare');
-
-print "TESTING COMPARE\n";
-$special_forms = array("-dev", "a1", "b1", "RC1", "", "pl1");
-$operators = array(
- "lt", "<",
- "le", "<=",
- "gt", ">",
- "ge", ">=",
- "eq", "=", "==",
- "ne", "<>", "!="
-);
-test("1", "2");
-test("10", "2");
-test("1.0", "1.1");
-test("1.2", "1.0.1");
-foreach ($special_forms as $f1) {
- foreach ($special_forms as $f2) {
- test("1.0$f1", "1.0$f2");
- }
-}
-
-print "TESTING OPERATORS\n";
-foreach ($special_forms as $f1) {
- foreach ($special_forms as $f2) {
- foreach ($operators as $op) {
- $v1 = "1.0$f1";
- $v2 = "1.0$f2";
- $test = version_compare($v1, $v2, $op) ? "true" : "false";
- printf("%7s %2s %-7s : %s\n", $v1, $op, $v2, $test);
- }
- }
-}
-
-function test($v1, $v2) {
- $compare = version_compare($v1, $v2);
- switch ($compare) {
- case -1:
- print "$v1 < $v2\n";
- break;
- case 1:
- print "$v1 > $v2\n";
- break;
- case 0:
- default:
- print "$v1 = $v2\n";
- break;
- }
-}
-
-?>
---EXPECT--
-TESTING COMPARE
-1 < 2
-10 > 2
-1.0 < 1.1
-1.2 > 1.0.1
-1.0-dev = 1.0-dev
-1.0-dev < 1.0a1
-1.0-dev < 1.0b1
-1.0-dev < 1.0RC1
-1.0-dev < 1.0
-1.0-dev < 1.0pl1
-1.0a1 > 1.0-dev
-1.0a1 = 1.0a1
-1.0a1 < 1.0b1
-1.0a1 < 1.0RC1
-1.0a1 < 1.0
-1.0a1 < 1.0pl1
-1.0b1 > 1.0-dev
-1.0b1 > 1.0a1
-1.0b1 = 1.0b1
-1.0b1 < 1.0RC1
-1.0b1 < 1.0
-1.0b1 < 1.0pl1
-1.0RC1 > 1.0-dev
-1.0RC1 > 1.0a1
-1.0RC1 > 1.0b1
-1.0RC1 = 1.0RC1
-1.0RC1 < 1.0
-1.0RC1 < 1.0pl1
-1.0 > 1.0-dev
-1.0 > 1.0a1
-1.0 > 1.0b1
-1.0 > 1.0RC1
-1.0 = 1.0
-1.0 < 1.0pl1
-1.0pl1 > 1.0-dev
-1.0pl1 > 1.0a1
-1.0pl1 > 1.0b1
-1.0pl1 > 1.0RC1
-1.0pl1 > 1.0
-1.0pl1 = 1.0pl1
-TESTING OPERATORS
-1.0-dev lt 1.0-dev : false
-1.0-dev < 1.0-dev : false
-1.0-dev le 1.0-dev : true
-1.0-dev <= 1.0-dev : true
-1.0-dev gt 1.0-dev : false
-1.0-dev > 1.0-dev : false
-1.0-dev ge 1.0-dev : true
-1.0-dev >= 1.0-dev : true
-1.0-dev eq 1.0-dev : true
-1.0-dev = 1.0-dev : true
-1.0-dev == 1.0-dev : true
-1.0-dev ne 1.0-dev : false
-1.0-dev <> 1.0-dev : false
-1.0-dev != 1.0-dev : false
-1.0-dev lt 1.0a1 : true
-1.0-dev < 1.0a1 : true
-1.0-dev le 1.0a1 : true
-1.0-dev <= 1.0a1 : true
-1.0-dev gt 1.0a1 : false
-1.0-dev > 1.0a1 : false
-1.0-dev ge 1.0a1 : false
-1.0-dev >= 1.0a1 : false
-1.0-dev eq 1.0a1 : false
-1.0-dev = 1.0a1 : false
-1.0-dev == 1.0a1 : false
-1.0-dev ne 1.0a1 : true
-1.0-dev <> 1.0a1 : true
-1.0-dev != 1.0a1 : true
-1.0-dev lt 1.0b1 : true
-1.0-dev < 1.0b1 : true
-1.0-dev le 1.0b1 : true
-1.0-dev <= 1.0b1 : true
-1.0-dev gt 1.0b1 : false
-1.0-dev > 1.0b1 : false
-1.0-dev ge 1.0b1 : false
-1.0-dev >= 1.0b1 : false
-1.0-dev eq 1.0b1 : false
-1.0-dev = 1.0b1 : false
-1.0-dev == 1.0b1 : false
-1.0-dev ne 1.0b1 : true
-1.0-dev <> 1.0b1 : true
-1.0-dev != 1.0b1 : true
-1.0-dev lt 1.0RC1 : true
-1.0-dev < 1.0RC1 : true
-1.0-dev le 1.0RC1 : true
-1.0-dev <= 1.0RC1 : true
-1.0-dev gt 1.0RC1 : false
-1.0-dev > 1.0RC1 : false
-1.0-dev ge 1.0RC1 : false
-1.0-dev >= 1.0RC1 : false
-1.0-dev eq 1.0RC1 : false
-1.0-dev = 1.0RC1 : false
-1.0-dev == 1.0RC1 : false
-1.0-dev ne 1.0RC1 : true
-1.0-dev <> 1.0RC1 : true
-1.0-dev != 1.0RC1 : true
-1.0-dev lt 1.0 : true
-1.0-dev < 1.0 : true
-1.0-dev le 1.0 : true
-1.0-dev <= 1.0 : true
-1.0-dev gt 1.0 : false
-1.0-dev > 1.0 : false
-1.0-dev ge 1.0 : false
-1.0-dev >= 1.0 : false
-1.0-dev eq 1.0 : false
-1.0-dev = 1.0 : false
-1.0-dev == 1.0 : false
-1.0-dev ne 1.0 : true
-1.0-dev <> 1.0 : true
-1.0-dev != 1.0 : true
-1.0-dev lt 1.0pl1 : true
-1.0-dev < 1.0pl1 : true
-1.0-dev le 1.0pl1 : true
-1.0-dev <= 1.0pl1 : true
-1.0-dev gt 1.0pl1 : false
-1.0-dev > 1.0pl1 : false
-1.0-dev ge 1.0pl1 : false
-1.0-dev >= 1.0pl1 : false
-1.0-dev eq 1.0pl1 : false
-1.0-dev = 1.0pl1 : false
-1.0-dev == 1.0pl1 : false
-1.0-dev ne 1.0pl1 : true
-1.0-dev <> 1.0pl1 : true
-1.0-dev != 1.0pl1 : true
- 1.0a1 lt 1.0-dev : false
- 1.0a1 < 1.0-dev : false
- 1.0a1 le 1.0-dev : false
- 1.0a1 <= 1.0-dev : false
- 1.0a1 gt 1.0-dev : true
- 1.0a1 > 1.0-dev : true
- 1.0a1 ge 1.0-dev : true
- 1.0a1 >= 1.0-dev : true
- 1.0a1 eq 1.0-dev : false
- 1.0a1 = 1.0-dev : false
- 1.0a1 == 1.0-dev : false
- 1.0a1 ne 1.0-dev : true
- 1.0a1 <> 1.0-dev : true
- 1.0a1 != 1.0-dev : true
- 1.0a1 lt 1.0a1 : false
- 1.0a1 < 1.0a1 : false
- 1.0a1 le 1.0a1 : true
- 1.0a1 <= 1.0a1 : true
- 1.0a1 gt 1.0a1 : false
- 1.0a1 > 1.0a1 : false
- 1.0a1 ge 1.0a1 : true
- 1.0a1 >= 1.0a1 : true
- 1.0a1 eq 1.0a1 : true
- 1.0a1 = 1.0a1 : true
- 1.0a1 == 1.0a1 : true
- 1.0a1 ne 1.0a1 : false
- 1.0a1 <> 1.0a1 : false
- 1.0a1 != 1.0a1 : false
- 1.0a1 lt 1.0b1 : true
- 1.0a1 < 1.0b1 : true
- 1.0a1 le 1.0b1 : true
- 1.0a1 <= 1.0b1 : true
- 1.0a1 gt 1.0b1 : false
- 1.0a1 > 1.0b1 : false
- 1.0a1 ge 1.0b1 : false
- 1.0a1 >= 1.0b1 : false
- 1.0a1 eq 1.0b1 : false
- 1.0a1 = 1.0b1 : false
- 1.0a1 == 1.0b1 : false
- 1.0a1 ne 1.0b1 : true
- 1.0a1 <> 1.0b1 : true
- 1.0a1 != 1.0b1 : true
- 1.0a1 lt 1.0RC1 : true
- 1.0a1 < 1.0RC1 : true
- 1.0a1 le 1.0RC1 : true
- 1.0a1 <= 1.0RC1 : true
- 1.0a1 gt 1.0RC1 : false
- 1.0a1 > 1.0RC1 : false
- 1.0a1 ge 1.0RC1 : false
- 1.0a1 >= 1.0RC1 : false
- 1.0a1 eq 1.0RC1 : false
- 1.0a1 = 1.0RC1 : false
- 1.0a1 == 1.0RC1 : false
- 1.0a1 ne 1.0RC1 : true
- 1.0a1 <> 1.0RC1 : true
- 1.0a1 != 1.0RC1 : true
- 1.0a1 lt 1.0 : true
- 1.0a1 < 1.0 : true
- 1.0a1 le 1.0 : true
- 1.0a1 <= 1.0 : true
- 1.0a1 gt 1.0 : false
- 1.0a1 > 1.0 : false
- 1.0a1 ge 1.0 : false
- 1.0a1 >= 1.0 : false
- 1.0a1 eq 1.0 : false
- 1.0a1 = 1.0 : false
- 1.0a1 == 1.0 : false
- 1.0a1 ne 1.0 : true
- 1.0a1 <> 1.0 : true
- 1.0a1 != 1.0 : true
- 1.0a1 lt 1.0pl1 : true
- 1.0a1 < 1.0pl1 : true
- 1.0a1 le 1.0pl1 : true
- 1.0a1 <= 1.0pl1 : true
- 1.0a1 gt 1.0pl1 : false
- 1.0a1 > 1.0pl1 : false
- 1.0a1 ge 1.0pl1 : false
- 1.0a1 >= 1.0pl1 : false
- 1.0a1 eq 1.0pl1 : false
- 1.0a1 = 1.0pl1 : false
- 1.0a1 == 1.0pl1 : false
- 1.0a1 ne 1.0pl1 : true
- 1.0a1 <> 1.0pl1 : true
- 1.0a1 != 1.0pl1 : true
- 1.0b1 lt 1.0-dev : false
- 1.0b1 < 1.0-dev : false
- 1.0b1 le 1.0-dev : false
- 1.0b1 <= 1.0-dev : false
- 1.0b1 gt 1.0-dev : true
- 1.0b1 > 1.0-dev : true
- 1.0b1 ge 1.0-dev : true
- 1.0b1 >= 1.0-dev : true
- 1.0b1 eq 1.0-dev : false
- 1.0b1 = 1.0-dev : false
- 1.0b1 == 1.0-dev : false
- 1.0b1 ne 1.0-dev : true
- 1.0b1 <> 1.0-dev : true
- 1.0b1 != 1.0-dev : true
- 1.0b1 lt 1.0a1 : false
- 1.0b1 < 1.0a1 : false
- 1.0b1 le 1.0a1 : false
- 1.0b1 <= 1.0a1 : false
- 1.0b1 gt 1.0a1 : true
- 1.0b1 > 1.0a1 : true
- 1.0b1 ge 1.0a1 : true
- 1.0b1 >= 1.0a1 : true
- 1.0b1 eq 1.0a1 : false
- 1.0b1 = 1.0a1 : false
- 1.0b1 == 1.0a1 : false
- 1.0b1 ne 1.0a1 : true
- 1.0b1 <> 1.0a1 : true
- 1.0b1 != 1.0a1 : true
- 1.0b1 lt 1.0b1 : false
- 1.0b1 < 1.0b1 : false
- 1.0b1 le 1.0b1 : true
- 1.0b1 <= 1.0b1 : true
- 1.0b1 gt 1.0b1 : false
- 1.0b1 > 1.0b1 : false
- 1.0b1 ge 1.0b1 : true
- 1.0b1 >= 1.0b1 : true
- 1.0b1 eq 1.0b1 : true
- 1.0b1 = 1.0b1 : true
- 1.0b1 == 1.0b1 : true
- 1.0b1 ne 1.0b1 : false
- 1.0b1 <> 1.0b1 : false
- 1.0b1 != 1.0b1 : false
- 1.0b1 lt 1.0RC1 : true
- 1.0b1 < 1.0RC1 : true
- 1.0b1 le 1.0RC1 : true
- 1.0b1 <= 1.0RC1 : true
- 1.0b1 gt 1.0RC1 : false
- 1.0b1 > 1.0RC1 : false
- 1.0b1 ge 1.0RC1 : false
- 1.0b1 >= 1.0RC1 : false
- 1.0b1 eq 1.0RC1 : false
- 1.0b1 = 1.0RC1 : false
- 1.0b1 == 1.0RC1 : false
- 1.0b1 ne 1.0RC1 : true
- 1.0b1 <> 1.0RC1 : true
- 1.0b1 != 1.0RC1 : true
- 1.0b1 lt 1.0 : true
- 1.0b1 < 1.0 : true
- 1.0b1 le 1.0 : true
- 1.0b1 <= 1.0 : true
- 1.0b1 gt 1.0 : false
- 1.0b1 > 1.0 : false
- 1.0b1 ge 1.0 : false
- 1.0b1 >= 1.0 : false
- 1.0b1 eq 1.0 : false
- 1.0b1 = 1.0 : false
- 1.0b1 == 1.0 : false
- 1.0b1 ne 1.0 : true
- 1.0b1 <> 1.0 : true
- 1.0b1 != 1.0 : true
- 1.0b1 lt 1.0pl1 : true
- 1.0b1 < 1.0pl1 : true
- 1.0b1 le 1.0pl1 : true
- 1.0b1 <= 1.0pl1 : true
- 1.0b1 gt 1.0pl1 : false
- 1.0b1 > 1.0pl1 : false
- 1.0b1 ge 1.0pl1 : false
- 1.0b1 >= 1.0pl1 : false
- 1.0b1 eq 1.0pl1 : false
- 1.0b1 = 1.0pl1 : false
- 1.0b1 == 1.0pl1 : false
- 1.0b1 ne 1.0pl1 : true
- 1.0b1 <> 1.0pl1 : true
- 1.0b1 != 1.0pl1 : true
- 1.0RC1 lt 1.0-dev : false
- 1.0RC1 < 1.0-dev : false
- 1.0RC1 le 1.0-dev : false
- 1.0RC1 <= 1.0-dev : false
- 1.0RC1 gt 1.0-dev : true
- 1.0RC1 > 1.0-dev : true
- 1.0RC1 ge 1.0-dev : true
- 1.0RC1 >= 1.0-dev : true
- 1.0RC1 eq 1.0-dev : false
- 1.0RC1 = 1.0-dev : false
- 1.0RC1 == 1.0-dev : false
- 1.0RC1 ne 1.0-dev : true
- 1.0RC1 <> 1.0-dev : true
- 1.0RC1 != 1.0-dev : true
- 1.0RC1 lt 1.0a1 : false
- 1.0RC1 < 1.0a1 : false
- 1.0RC1 le 1.0a1 : false
- 1.0RC1 <= 1.0a1 : false
- 1.0RC1 gt 1.0a1 : true
- 1.0RC1 > 1.0a1 : true
- 1.0RC1 ge 1.0a1 : true
- 1.0RC1 >= 1.0a1 : true
- 1.0RC1 eq 1.0a1 : false
- 1.0RC1 = 1.0a1 : false
- 1.0RC1 == 1.0a1 : false
- 1.0RC1 ne 1.0a1 : true
- 1.0RC1 <> 1.0a1 : true
- 1.0RC1 != 1.0a1 : true
- 1.0RC1 lt 1.0b1 : false
- 1.0RC1 < 1.0b1 : false
- 1.0RC1 le 1.0b1 : false
- 1.0RC1 <= 1.0b1 : false
- 1.0RC1 gt 1.0b1 : true
- 1.0RC1 > 1.0b1 : true
- 1.0RC1 ge 1.0b1 : true
- 1.0RC1 >= 1.0b1 : true
- 1.0RC1 eq 1.0b1 : false
- 1.0RC1 = 1.0b1 : false
- 1.0RC1 == 1.0b1 : false
- 1.0RC1 ne 1.0b1 : true
- 1.0RC1 <> 1.0b1 : true
- 1.0RC1 != 1.0b1 : true
- 1.0RC1 lt 1.0RC1 : false
- 1.0RC1 < 1.0RC1 : false
- 1.0RC1 le 1.0RC1 : true
- 1.0RC1 <= 1.0RC1 : true
- 1.0RC1 gt 1.0RC1 : false
- 1.0RC1 > 1.0RC1 : false
- 1.0RC1 ge 1.0RC1 : true
- 1.0RC1 >= 1.0RC1 : true
- 1.0RC1 eq 1.0RC1 : true
- 1.0RC1 = 1.0RC1 : true
- 1.0RC1 == 1.0RC1 : true
- 1.0RC1 ne 1.0RC1 : false
- 1.0RC1 <> 1.0RC1 : false
- 1.0RC1 != 1.0RC1 : false
- 1.0RC1 lt 1.0 : true
- 1.0RC1 < 1.0 : true
- 1.0RC1 le 1.0 : true
- 1.0RC1 <= 1.0 : true
- 1.0RC1 gt 1.0 : false
- 1.0RC1 > 1.0 : false
- 1.0RC1 ge 1.0 : false
- 1.0RC1 >= 1.0 : false
- 1.0RC1 eq 1.0 : false
- 1.0RC1 = 1.0 : false
- 1.0RC1 == 1.0 : false
- 1.0RC1 ne 1.0 : true
- 1.0RC1 <> 1.0 : true
- 1.0RC1 != 1.0 : true
- 1.0RC1 lt 1.0pl1 : true
- 1.0RC1 < 1.0pl1 : true
- 1.0RC1 le 1.0pl1 : true
- 1.0RC1 <= 1.0pl1 : true
- 1.0RC1 gt 1.0pl1 : false
- 1.0RC1 > 1.0pl1 : false
- 1.0RC1 ge 1.0pl1 : false
- 1.0RC1 >= 1.0pl1 : false
- 1.0RC1 eq 1.0pl1 : false
- 1.0RC1 = 1.0pl1 : false
- 1.0RC1 == 1.0pl1 : false
- 1.0RC1 ne 1.0pl1 : true
- 1.0RC1 <> 1.0pl1 : true
- 1.0RC1 != 1.0pl1 : true
- 1.0 lt 1.0-dev : false
- 1.0 < 1.0-dev : false
- 1.0 le 1.0-dev : false
- 1.0 <= 1.0-dev : false
- 1.0 gt 1.0-dev : true
- 1.0 > 1.0-dev : true
- 1.0 ge 1.0-dev : true
- 1.0 >= 1.0-dev : true
- 1.0 eq 1.0-dev : false
- 1.0 = 1.0-dev : false
- 1.0 == 1.0-dev : false
- 1.0 ne 1.0-dev : true
- 1.0 <> 1.0-dev : true
- 1.0 != 1.0-dev : true
- 1.0 lt 1.0a1 : false
- 1.0 < 1.0a1 : false
- 1.0 le 1.0a1 : false
- 1.0 <= 1.0a1 : false
- 1.0 gt 1.0a1 : true
- 1.0 > 1.0a1 : true
- 1.0 ge 1.0a1 : true
- 1.0 >= 1.0a1 : true
- 1.0 eq 1.0a1 : false
- 1.0 = 1.0a1 : false
- 1.0 == 1.0a1 : false
- 1.0 ne 1.0a1 : true
- 1.0 <> 1.0a1 : true
- 1.0 != 1.0a1 : true
- 1.0 lt 1.0b1 : false
- 1.0 < 1.0b1 : false
- 1.0 le 1.0b1 : false
- 1.0 <= 1.0b1 : false
- 1.0 gt 1.0b1 : true
- 1.0 > 1.0b1 : true
- 1.0 ge 1.0b1 : true
- 1.0 >= 1.0b1 : true
- 1.0 eq 1.0b1 : false
- 1.0 = 1.0b1 : false
- 1.0 == 1.0b1 : false
- 1.0 ne 1.0b1 : true
- 1.0 <> 1.0b1 : true
- 1.0 != 1.0b1 : true
- 1.0 lt 1.0RC1 : false
- 1.0 < 1.0RC1 : false
- 1.0 le 1.0RC1 : false
- 1.0 <= 1.0RC1 : false
- 1.0 gt 1.0RC1 : true
- 1.0 > 1.0RC1 : true
- 1.0 ge 1.0RC1 : true
- 1.0 >= 1.0RC1 : true
- 1.0 eq 1.0RC1 : false
- 1.0 = 1.0RC1 : false
- 1.0 == 1.0RC1 : false
- 1.0 ne 1.0RC1 : true
- 1.0 <> 1.0RC1 : true
- 1.0 != 1.0RC1 : true
- 1.0 lt 1.0 : false
- 1.0 < 1.0 : false
- 1.0 le 1.0 : true
- 1.0 <= 1.0 : true
- 1.0 gt 1.0 : false
- 1.0 > 1.0 : false
- 1.0 ge 1.0 : true
- 1.0 >= 1.0 : true
- 1.0 eq 1.0 : true
- 1.0 = 1.0 : true
- 1.0 == 1.0 : true
- 1.0 ne 1.0 : false
- 1.0 <> 1.0 : false
- 1.0 != 1.0 : false
- 1.0 lt 1.0pl1 : true
- 1.0 < 1.0pl1 : true
- 1.0 le 1.0pl1 : true
- 1.0 <= 1.0pl1 : true
- 1.0 gt 1.0pl1 : false
- 1.0 > 1.0pl1 : false
- 1.0 ge 1.0pl1 : false
- 1.0 >= 1.0pl1 : false
- 1.0 eq 1.0pl1 : false
- 1.0 = 1.0pl1 : false
- 1.0 == 1.0pl1 : false
- 1.0 ne 1.0pl1 : true
- 1.0 <> 1.0pl1 : true
- 1.0 != 1.0pl1 : true
- 1.0pl1 lt 1.0-dev : false
- 1.0pl1 < 1.0-dev : false
- 1.0pl1 le 1.0-dev : false
- 1.0pl1 <= 1.0-dev : false
- 1.0pl1 gt 1.0-dev : true
- 1.0pl1 > 1.0-dev : true
- 1.0pl1 ge 1.0-dev : true
- 1.0pl1 >= 1.0-dev : true
- 1.0pl1 eq 1.0-dev : false
- 1.0pl1 = 1.0-dev : false
- 1.0pl1 == 1.0-dev : false
- 1.0pl1 ne 1.0-dev : true
- 1.0pl1 <> 1.0-dev : true
- 1.0pl1 != 1.0-dev : true
- 1.0pl1 lt 1.0a1 : false
- 1.0pl1 < 1.0a1 : false
- 1.0pl1 le 1.0a1 : false
- 1.0pl1 <= 1.0a1 : false
- 1.0pl1 gt 1.0a1 : true
- 1.0pl1 > 1.0a1 : true
- 1.0pl1 ge 1.0a1 : true
- 1.0pl1 >= 1.0a1 : true
- 1.0pl1 eq 1.0a1 : false
- 1.0pl1 = 1.0a1 : false
- 1.0pl1 == 1.0a1 : false
- 1.0pl1 ne 1.0a1 : true
- 1.0pl1 <> 1.0a1 : true
- 1.0pl1 != 1.0a1 : true
- 1.0pl1 lt 1.0b1 : false
- 1.0pl1 < 1.0b1 : false
- 1.0pl1 le 1.0b1 : false
- 1.0pl1 <= 1.0b1 : false
- 1.0pl1 gt 1.0b1 : true
- 1.0pl1 > 1.0b1 : true
- 1.0pl1 ge 1.0b1 : true
- 1.0pl1 >= 1.0b1 : true
- 1.0pl1 eq 1.0b1 : false
- 1.0pl1 = 1.0b1 : false
- 1.0pl1 == 1.0b1 : false
- 1.0pl1 ne 1.0b1 : true
- 1.0pl1 <> 1.0b1 : true
- 1.0pl1 != 1.0b1 : true
- 1.0pl1 lt 1.0RC1 : false
- 1.0pl1 < 1.0RC1 : false
- 1.0pl1 le 1.0RC1 : false
- 1.0pl1 <= 1.0RC1 : false
- 1.0pl1 gt 1.0RC1 : true
- 1.0pl1 > 1.0RC1 : true
- 1.0pl1 ge 1.0RC1 : true
- 1.0pl1 >= 1.0RC1 : true
- 1.0pl1 eq 1.0RC1 : false
- 1.0pl1 = 1.0RC1 : false
- 1.0pl1 == 1.0RC1 : false
- 1.0pl1 ne 1.0RC1 : true
- 1.0pl1 <> 1.0RC1 : true
- 1.0pl1 != 1.0RC1 : true
- 1.0pl1 lt 1.0 : false
- 1.0pl1 < 1.0 : false
- 1.0pl1 le 1.0 : false
- 1.0pl1 <= 1.0 : false
- 1.0pl1 gt 1.0 : true
- 1.0pl1 > 1.0 : true
- 1.0pl1 ge 1.0 : true
- 1.0pl1 >= 1.0 : true
- 1.0pl1 eq 1.0 : false
- 1.0pl1 = 1.0 : false
- 1.0pl1 == 1.0 : false
- 1.0pl1 ne 1.0 : true
- 1.0pl1 <> 1.0 : true
- 1.0pl1 != 1.0 : true
- 1.0pl1 lt 1.0pl1 : false
- 1.0pl1 < 1.0pl1 : false
- 1.0pl1 le 1.0pl1 : true
- 1.0pl1 <= 1.0pl1 : true
- 1.0pl1 gt 1.0pl1 : false
- 1.0pl1 > 1.0pl1 : false
- 1.0pl1 ge 1.0pl1 : true
- 1.0pl1 >= 1.0pl1 : true
- 1.0pl1 eq 1.0pl1 : true
- 1.0pl1 = 1.0pl1 : true
- 1.0pl1 == 1.0pl1 : true
- 1.0pl1 ne 1.0pl1 : false
- 1.0pl1 <> 1.0pl1 : false
- 1.0pl1 != 1.0pl1 : false
\ No newline at end of file
+++ /dev/null
---TEST--
-Function -- vprintf
---SKIPIF--
-<?php if (function_exists('vprintf')) { echo 'skip'; } ?>
---FILE--
-<?php
-require_once 'PHP/Compat.php';
-PHP_Compat::loadFunction('vprintf');
-
-$values = array (2, 'car');
-
-$format = "There are %d monkeys in the %s";
-vprintf($format, $values);
-?>
---EXPECT--
-There are 2 monkeys in the car
\ No newline at end of file
+++ /dev/null
---TEST--
-Function -- vsprintf
---SKIPIF--
-<?php if (function_exists('vsprintf')) { echo 'skip'; } ?>
---FILE--
-<?php
-require_once 'PHP/Compat.php';
-PHP_Compat::loadFunction('vsprintf');
-
-$values = array (2, 'car');
-
-$format = "There are %d monkeys in the %s";
-vprintf($format, $values);
-?>
---EXPECT--
-There are 2 monkeys in the car
\ No newline at end of file
+++ /dev/null
---TEST--
-Method -- PHP_Compat::loadConstant
---SKIPIF--
-<?php if (defined('E_STRICT')) { echo 'skip'; } ?>
---FILE--
-<?php
-require_once ('PHP/Compat.php');
-
-// Singular
-$test1 = array ();
-$test1[] = PHP_Compat::loadConstant('invalid');
-$test1[] = PHP_Compat::loadConstant('E_STRICT');
-
-// With an array
-$components = array('invalid', 'also-invalid', 'more-invalid', 'E_STRICT');
-$test2 = PHP_Compat::loadConstant($components);
-
-$results = array_merge($test1, $test2);
-foreach ($results as $result) {
- echo ($result === true) ? 'true' : 'false', "\n";
-}
-?>
---EXPECT--
-false
-true
-false
-false
-false
-false
\ No newline at end of file
+++ /dev/null
---TEST--
-Method -- PHP_Compat::loadFunction
---SKIPIF--
-<?php if (function_exists('str_split') || function_exists('scandir')) { echo 'skip'; } ?>
---FILE--
-<?php
-require_once ('PHP/Compat.php');
-
-// Singular
-$test1 = array ();
-$test1[] = PHP_Compat::loadFunction('invalid');
-$test1[] = PHP_Compat::loadFunction('str_split');
-
-// With an array
-$components = array('invalid', 'also-invalid', 'more-invalid', 'scandir');
-$test2 = PHP_Compat::loadFunction($components);
-
-$results = array_merge($test1, $test2);
-foreach ($results as $result) {
- echo ($result === true) ? 'true' : 'false', "\n";
-}
-?>
---EXPECT--
-false
-true
-false
-false
-false
-true
\ No newline at end of file
+++ /dev/null
-<?php
-
-/**
- * Test script for PHP_Debug 2.1.0 and the HTML_Div renderer
- *
- * @package PHP_Debug
- * @author COil
- * @since V2.1.0 - 6 apr 2006
- * @filesource
- */
-
-error_reporting(E_ALL); // Report all possible errors
-//session_start(); // Start session
-
-
-// Options array for Debug object
-$options = array(
- 'render_type' => 'HTML', // Renderer type
- 'render_mode' => 'Div', // Renderer mode
- 'restrict_access' => false, // Restrict access of debug
- 'allow_url_access' => true, // Allow url access
- 'url_key' => 'key', // Url key
- 'url_pass' => 'nounou', // Url pass
- 'enable_watch' => false, // Enable wath of vars
- 'replace_errorhandler' => true, // Replace the php error handler
- 'lang' => 'FR', // Lang
- 'enable_w3c_validator' => isset($_GET['enable_w3c_validator']) ? $_GET['enable_w3c_validator'] : false, // Validate the output
-
- // Renderer specific
- 'HTML_DIV_view_source_script_name' => 'PHP_Debug_ShowSource.php',
- 'HTML_DIV_remove_templates_pattern' => true,
- 'HTML_DIV_templates_pattern' =>
- array(
- '/home/phpdebug/www/' => '/projectroot/'
- ),
- 'HTML_DIV_images_path' => 'images',
- 'HTML_DIV_css_path' => 'css',
- 'HTML_DIV_js_path' => 'js',
-);
-
-$allowedip = array(
- '127.0.0.1'
-);
-
-// Include main class
-require_once 'PHP/Debug.php';
-
-// Additional ini path for PEAR
-define('ADD_PEAR_ROOT', '/home/phpdebug/www/libs/PEAR');
-set_include_path(ADD_PEAR_ROOT . PATH_SEPARATOR. get_include_path());
-
-echo '<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE html
- PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
- <head>
- <title>Pear::PHP_Debug</title>
- <script type="text/javascript" src="'. $options['HTML_DIV_js_path'] .'/html_div.js"></script>
- <link rel="stylesheet" type="text/css" media="screen" href="'. $options['HTML_DIV_css_path'] .'/html_div.css" />
-';
-?>
- </head>
-<body>
-<h1>PEAR::PHP_Debug -------------------------></h1>
-
-<p>
- <a href="PHP_Debug_HTML_Div_test.php">» HTML_DIV Renderer</a><br/>
- <a href="PHP_Debug_HTML_Div_test.php?enable_w3c_validator=1">» HTML_DIV Renderer with W3C output validation</a><br/>
- <a href="PHP_Debug_HTML_Table_test.php">» HTML_Table Renderer</a><br/>
- <a href="PHP_Debug_test.php">» Test min</a><br/>
- <a href="PHP_Debug_Sources.php">» Show sources</a><br/>
-</p>
-
-<?php
-// Tests variables ============================================================
-
-// One variable that will be watched by PHP_Debug
-$watchedVariable = 1;
-
-// One session variable to test the debugtype = PHP_DebuLine::TYPE_ENV (4)
-$_SESSION['Kikoo'] = "One session variable defined";
-
-
-
-// Debug Object creation =======================================================
-
-$Dbg = new PHP_Debug($options);
-
-
-// Test restrictAccess() function, only IP in param array will see the debug ===
-//$Dbg->restrictAccess($allowedip);
-
-
-// Test add() function =========================================================
-
-// Standard
-$renderer = 'HTML_Div';
-$intro = 'This is the <b>'. $renderer.'_Renderer</b>, client IP is '.
- $_SERVER['REMOTE_ADDR'];
-$Dbg->add($intro);
-
-// Standard, fix end and start time manually
-$debug_line = $Dbg->add('Manual performance monitoring');
-$debug_line->setStartTime();
-for ($i = 0; $i < 20000; $i++) {
- $j = 0;
-}
-$debug_line->setEndTime();
-
-// Application settings ========================================================
-
-// Add an application setting
-$Dbg->addSetting($renderer, 'app_renderer_mode');
-
-// Add a group of application settings
-$Dbg->addSettings($options, 'app_settings');
-
-
-// Test dump() function ========================================================
-
-// dump a variable (integer)
-$foo = 555;
-$Dbg->dump($foo, 'Foo');
-
-// dump a variable (double)
-$foo2 = 37.2;
-$Dbg->dump($foo2, 'Foo2');
-
-
-// dump an array
-$Dbg->dump($options, 'Options');
-
-
-// dump an object
-$testObject = new PHP_DebugLine('info info info inside DebugLine object');
-$testObject = $Dbg->dump($testObject);
-
-// test the automatic return of debug line objects by the public functions
-//$testObject = $Dbg->dump('i am the object');
-//PHP_Debug::dumpVar($testObject, '$testObject', 1);
-
-// dump an object and die the script
-//PHP_Debug::dumpVar($testObject, 'stooooooop', true);
-
-
-// Test setAction() ============================================================
-
-
-// Type 12 : Page action : --> Methode publique a creer
-$action = 'view_test_action';
-$Dbg->setAction($action);
-
-// Test watch() function, watched var is 'watchedVariable' =====================
-
-// /!\ Be carefull the tick directive does not work under windows /!\
-// and make apache crash. To test under unix, remove comments bellow and
-// corresponding brace line 195
-
-//declare (ticks = 1)
-//{
-
- // Watch the variable called 'watchedVariable'
- //$Dbg->watch('watchedVariable');
-
-
- // Stress backtrace function (check line, file, function, class results) ===
-
- function a()
- {
- global $Dbg, $watchedVariable;
- $Dbg->addDebug('call from a() fonction');
- $Dbg->stopTimer();
-
- $watchedVariable = 501;
-
- b();
- }
-
- function b()
- {
- global $Dbg, $watchedVariable;
- $Dbg->add('call from b() fonction');
-
- $watchedVariable = 502;
- }
-
- a();
-
- $Dbg->addDebugFirst('call after b() and a() but adding in 1st');
-
- $watchedVariable = 555;
- $watchedVariable = 'converting from INT to STR';
-
-//} // End of declare {ticks=n} block
-
-
-// Test the add() function with the timer ======================================
-
-$debug_line2 = $Dbg->add('PERF TEST : 10000 iteration');
-
-$y = 0;
-for ($index = 0; $index < 10000; $index++) {
- $y = $y + $index;
-}
-$Dbg->stopTimer();
-$Dbg->dump($debug_line2);
-
-
-// Test the database functions =================================================
-
-// Database related info
-$Dbg->queryRel('Connecting to DATABASE [<b>phpdebug</b>] dns: root:user@mysql');
-$Dbg->stopTimer();
-
-// Query
-$Dbg->query('SELECT * FROM PHP_DEBUG_USERS');
-
-$y = 0;
-for ($index = 0; $index < 10000; $index++) {
- $y = $y + $index;
-}
-$Dbg->stopTimer();
-
-
-
-// Test custom error handler ===================================================
-
-echo $notset; // Will raise a PHP notice
-fopen('not existing!', 'r'); // Will raise a PHP warning
-trigger_error('This is a custom application error !!', E_USER_ERROR);
- // Will raise a custom user error
-$Dbg->error('Bad status of var x in application PHP_Debug');
- // Will add an application error
-
-// Display Debug information (HTML_Table renderer) =============================
-
-$Dbg->display();
-
-// Test __toString(), dumpVar() functions and structure of Debug object ========
-
-//echo $Dbg;
-
-// END =========================================================================
-?>
-
-</body>
-</html>
\ No newline at end of file
+++ /dev/null
-<?php
-
-/**
- * Created on 18 apr 2006
- *
- * Test script for PHP_Debug 2.0.0
- *
- * @package PHP_Debug
- * @author COil
- * @since V2.0.0 - 6 apr 2006
- * @filesource
- */
-
-error_reporting(E_ALL); // Report all possible errors
-//session_start(); // Start session
-
-$renderer = 'HTML_Table';
-
-// Options array for Debug object
-$options = array(
- 'render_type' => 'HTML',
- 'render_mode' => 'Table',
- 'restrict_access' => false,
- 'allow_url_access' => true,
- 'url_key' => 'key',
- 'url_pass' => 'nounou',
- 'enable_watch' => false,
- 'replace_errorhandler' => true,
- 'lang' => 'FR',
- 'HTML_TABLE_view_source_script_name' => 'PHP_Debug_ShowSource.php',
- 'HTML_TABLE_css_path' => 'css'
-);
-
-$allowedip = array(
- '127.0.0.1'
-);
-
-
-require_once 'PHP/Debug.php';
-
-echo '<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE html
- PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
- <head>
- <title>Pear::PHP_Debug</title>
- <link rel="stylesheet" type="text/css" media="screen" href="'. $options['HTML_TABLE_css_path'] .'/html_table.css" />
-';
-?>
- </head>
-<body>
-<h1>PEAR::PHP_Debug</h1>
-<p>
- <a href="http://validator.w3.org/check?uri=referer"><img
- src="http://www.w3.org/Icons/valid-xhtml10"
- alt="Valid XHTML 1.0 Strict" height="31" width="88" /></a>
-</p>
-
-<p>
- <a href="PHP_Debug_HTML_Div_test.php">» HTML_DIV Renderer</a><br/>
- <a href="PHP_Debug_HTML_Div_test.php?enable_w3c_validator=1">» HTML_DIV Renderer with W3C output validation</a><br/>
- <a href="PHP_Debug_HTML_Table_test.php">» HTML_Table Renderer</a><br/>
- <a href="PHP_Debug_test.php">» Test min</a><br/>
- <a href="PHP_Debug_Sources.php">» Show sources</a><br/>
-</p>
-
-<?php
-// Tests variables ============================================================
-
-// One variable that will be watched by PHP_Debug
-$watchedVariable = 1;
-
-// One session variable to test the debugtype = PHP_DebuLine::TYPE_ENV (4)
-$_SESSION['Kikoo'] = 'One session variable defined';
-
-
-// Debug Object creation =======================================================
-
-$Dbg = new PHP_Debug($options);
-
-
-// Test restrictAcess() function, only IP in param array will see the debug ====
-
-//$Dbg->restrictAcess($allowedip);
-
-
-
-// Test add() function =========================================================
-
-// Standard
-$Dbg->add("This is the <b>HTML_Table_Render</b>, client IP is ".
- $_SERVER['REMOTE_ADDR']);
-
-// Standard, fix end and start time manually
-$debug_line = $Dbg->add('Manual performance monitoring');
-$debug_line->setStartTime();
-for ($i = 0; $i < 20000; $i++) {
- $j = 0;
-}
-$debug_line->setEndTime();
-
-// Test dump() function ========================================================
-
-// dump a variable (integer)
-$foo = 555;
-$Dbg->dump($foo, 'Foo');
-
-// dump a variable (double)
-$foo2 = 37.2;
-$Dbg->dump($foo2, 'Foo2');
-
-// dump an array
-//$Dbg->dump($options, 'Options');
-
-// dump an object
-$testObject = new PHP_DebugLine('info info info inside DebugLine object');
-$Dbg->dump($testObject);
-
-// dump an object and die the script
-//PHP_Debug::dumpVar($testObject, 'stooooooop', true);
-
-
-// Test setAction() ============================================================
-
-
-// Type 12 : Page action : --> Methode publique a creer
-$action = 'view_test_action';
-$Dbg->setAction($action);
-
-
-// Test watch() function, watched var is 'watchedVariable' =====================
-
-// /!\ Be carefull the tick directive does not work under windows /!\
-// and make apache crash. To test under unix, remove comments bellow and
-// corresponding brace line 163
-
-//declare (ticks = 1)
-//{
-
- // Watch the variable called 'watchedVariable'
- //$Dbg->watch('watchedVariable');
-
- // Stress backtrace function (check line, file, function, class results) ===
-
- function a()
- {
- global $Dbg, $watchedVariable;
- $Dbg->addDebug('call from a() fonction');
- $Dbg->stopTimer();
-
- $watchedVariable = 501;
-
- b();
- }
-
- function b()
- {
- global $Dbg, $watchedVariable;
- $Dbg->add('call from b() fonction');
-
- $watchedVariable = 502;
- }
-
- a();
-
- $Dbg->addDebugFirst('call after b() and a() but adding in 1st');
-
- $watchedVariable = 555;
- $watchedVariable = 'converting from INT to STR';
-
-//} // End of declare {ticks=n} block
-
-
-// Test the add() function with the timer ======================================
-
-$Dbg->add('PERF TEST : 10000 iteration');
-
-$y = 0;
-for ($index = 0; $index < 10000; $index++) {
- $y = $y + $index;
-}
-$Dbg->stopTimer();
-
-
-// Test the query() function ===================================================
-
-$Dbg->query('SELECT * FROM PHP_DEBUG_USERS');
-
-$y = 0;
-for ($index = 0; $index < 10000; $index++) {
- $y = $y + $index;
-}
-$Dbg->stopTimer();
-
-
-
-// Test custom error handler ===================================================
-
-echo $notset; // Will raise a PHP notice
-fopen('not existing!', 'r'); // Will raise a PHP warning
-trigger_error('This is a custom application error !!', E_USER_ERROR);
- // Will raise a custom user error
-$Dbg->error('Bad status of var x in application PHP_Debug');
- // Will add an application error
-
-
-// Display Debug information (HTML_Table renderer) =============================
-
-$Dbg->display();
-
-
-// Test __toString(), dumpVar() functions and structure of Debug object ========
-
-//echo $Dbg;
-
-
-// END =========================================================================
-?>
-</body>
-</html>
\ No newline at end of file
+++ /dev/null
-<?php
-
-/**
- * This an exemple of showsource file
- *
- * It uses the Pear package TEXT_Highlighter
- *
- * /!\ Don't forget to securise this script /!\
- * - By Ip
- * - By allowed path (as the isAllowedPath() function below)
- *
- * @package PHP_Debug
- * @since V2.0.0 - 26 apr 2006
- * @filesource
- */
-
-
-// View source configuration (to modify with your settings)
-$view_source_options = array(
- 'PEAR_ROOT' => 'W:/var/www/php/PEAR',
- 'CSS_ROOT' => 'css',
- 'ALLOWED_PATH' => array(
- 'W:\var\www\html\phpdebug\\',
- 'W:\var\www\html\phpdebugweb\\',
- 'E:\Works\Projets-DEV\phpdebug\\',
- '/home.10.3/autonet/www/phpdebug/web/',
- '/home/phpdebug/',
- )
-);
-
-// Files that are allowed to be viewed
-$pathPattern = '/^{$path}(.*)(.php)$/';
-
-// Additional include path for Pear (to adapt to your configuration )
-//set_include_path($options['PEAR_ROOT'] . PATH_SEPARATOR. get_include_path());
-// End //
-
-//Include Pear
-require_once 'PEAR.php';
-
-//Include Debug_Renderer_HTML_Table_Config to get the configuration
-require_once 'PHP/Debug.php';
-require_once 'PHP/Debug/Renderer/HTML/TableConfig.php';
-$options = PHP_Debug_Renderer_HTML_TableConfig::singleton()->getConfig();
-
-//Include the class definition of highlighter
-require_once 'Text/Highlighter.php';
-require_once 'Text/Highlighter/Renderer/Html.php';
-
-/**
- * Security test
- */
-function isPathAllowed($file) {
-
- global $view_source_options, $pathPattern;
- $allowed = false;
-
- foreach ($view_source_options['ALLOWED_PATH'] as $path) {
- $pattern = str_replace(
- '{$path}',
- regPath(preg_quote($path)),
- $pathPattern
- );
- if (preg_match($pattern, $file)) {
- $allowed = true;
- }
- }
- return $allowed;
-}
-
-// Add your ip restriction here
-function isIpAllowed() {
- return true;
-}
-
-// Transform path for regex
-function regPath($path) {
- return str_replace(
- array(
- '/',
- '-',
- ),
- array(
- '\/',
- '\-',
- ),
- $path
- );
-}
-
-// Build the array options for the HTML renderer to get the nice file numbering
-$rendOptions = array(
- 'numbers' => $options['HTML_TABLE_view_source_numbers'],
- 'tabsize' => $options['HTML_TABLE_view_source_tabsize'],
-);
-
-
-// Finish parser object creation
-$renderer = new Text_Highlighter_Renderer_Html($rendOptions);
-$phpHighlighter = Text_Highlighter::factory('PHP');
-$phpHighlighter->setRenderer($renderer);
-
-// Now start output, header
-$header = str_replace(
- '<title>PEAR::PHP_Debug</title>',
- '<title>PEAR::PHP_Debug::View_Source::'. $_GET['file']. '</title>',
- $options['HTML_TABLE_simple_header']);
-echo $header;
-echo '
- <link rel="stylesheet" type="text/css" media="screen" href="'. $view_source_options['CSS_ROOT'] .'/view_source.css" />
- </head>
- <body>
-';
-
-// Security check
-if (isPathAllowed($_GET['file']) && isIpAllowed()) {
- if(file_exists($_GET['file'])) {
- echo
- '<div>
- <span class="hl-title">'.
- $_GET['file'].'
- </span>
- </div>';
- echo $phpHighlighter->highlight(file_get_contents($_GET['file']));
- } else {
- echo '<h2>File does not exists</h2>';
- }
-} else {
- echo '<h1>Sorry, your are not allowed to access this path</h1>';
-}
-
-// Footer
-echo $options['HTML_TABLE_simple_footer'];
\ No newline at end of file
+++ /dev/null
-<?php
-
-/**
- * Display package source
- *
- * @package PHP_Debug
- * @filesource
- */
-
-include 'PHP/Debug.php';
-
-echo '<?xml version="1.0" encoding="UTF-8"?>';
-?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
- <head>
- <title>PEAR::PHP_Debug, sources</title>
- </head>
- <body>
- <h1>PHP_Debug, package sources</h1>
- <h2>Sourceforge release : <?php echo PHP_Debug::RELEASE; ?></h2>
- <h2>Pear release : <?php echo PHP_Debug::PEAR_RELEASE; ?></h2>
-<?php
-// Display source code =========================================================
-
-// file
-function showSource($dir, $file)
-{
- $path = $dir. $file;
- echo '<div>';
- echo '<h1>'. $path. '</h1>';
- highlight_file($path);
- echo '</div>'. "\n";
-}
-
-// Dir
-function parseDir($dir, $parent)
-{
- $path = $parent. ($dir['name'] != '/' ? $dir['name']. '/' : '');
- foreach($dir->file as $file) {
- if (in_array($file['role'], array('test', 'php'))) {
- showSource($path, $file['name']);
- }
- }
- foreach($dir->dir as $child) {
- parseDir($child, $path);
- }
- return;
-}
-
-$package = simplexml_load_file('package.xml');
-$dir = '';
-parseDir($package->contents->dir, $dir);
-?>
- </body>
-</html>
\ No newline at end of file
+++ /dev/null
-<?php
-
-/**
- * Minimal test
- *
- * @package PHP_Debug
- * @filesource
- */
-
-echo '<?xml version="1.0" encoding="UTF-8"?>';
-?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
- <head>
- <title>PEAR::PHP_Debug, Hello World !</title>
-<?php
-
-// Options array for Debug object
-$options = array(
- 'HTML_DIV_images_path' => 'images',
- 'HTML_DIV_css_path' => 'css',
- 'HTML_DIV_js_path' => 'js',
-);
-
-/**
- * Include Debug Class
- */
-include_once('PHP/Debug.php');
-
-// Debug object
-$Dbg = new PHP_Debug($options);
-
-?>
- <script type="text/javascript" src="<?php echo $options['HTML_DIV_js_path']; ?>/html_div.js"></script>
- <link rel="stylesheet" type="text/css" media="screen" href="<?php echo $options['HTML_DIV_css_path']; ?>/html_div.css" />
- </head>
- <body>
- <div>
- <a href="http://validator.w3.org/check?uri=referer"><img src="http://www.w3.org/Icons/valid-xhtml10" alt="Valid XHTML 1.0 Strict" height="31" width="88" /></a>
- </div>
-<?php
-
-echo '<div><h1>PEAR::PHP_Debug, Hello World !</h1></div>';
-$Dbg->add('DEBUG INFO');
-$Dbg->display();
-
-?>
- </body>
-</html>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * Contains the Pager_Common class
- *
- * PHP versions 4 and 5
- *
- * LICENSE: Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE FREEBSD PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * @category HTML
- * @package Pager
- * @author Lorenzo Alberton <l.alberton@quipo.it>
- * @author Richard Heyes <richard@phpguru.org>
- * @copyright 2003-2007 Lorenzo Alberton, Richard Heyes
- * @license http://www.debian.org/misc/bsd.license BSD License (3 Clause)
- * @version CVS: $Id: Common.php,v 1.1.1.1 2008/04/28 15:20:46 jamie Exp $
- * @link http://pear.php.net/package/Pager
- */
-
-/**
- * Two constants used to guess the path- and file-name of the page
- * when the user doesn't set any other value
- */
-if (substr($_SERVER['PHP_SELF'], -1) == '/') {
- $http = (isset($_SERVER['HTTPS']) && ('on' == strtolower($_SERVER['HTTPS']))) ? 'https://' : 'http://';
- define('PAGER_CURRENT_FILENAME', '');
- define('PAGER_CURRENT_PATHNAME', $http.$_SERVER['HTTP_HOST'].str_replace('\\', '/', $_SERVER['PHP_SELF']));
-} else {
- define('PAGER_CURRENT_FILENAME', preg_replace('/(.*)\?.*/', '\\1', basename($_SERVER['PHP_SELF'])));
- define('PAGER_CURRENT_PATHNAME', str_replace('\\', '/', dirname($_SERVER['PHP_SELF'])));
-}
-/**
- * Error codes
- */
-define('PAGER_OK', 0);
-define('ERROR_PAGER', -1);
-define('ERROR_PAGER_INVALID', -2);
-define('ERROR_PAGER_INVALID_PLACEHOLDER', -3);
-define('ERROR_PAGER_INVALID_USAGE', -4);
-define('ERROR_PAGER_NOT_IMPLEMENTED', -5);
-
-/**
- * Pager_Common - Common base class for [Sliding|Jumping] Window Pager
- * Extend this class to write a custom paging class
- *
- * @category HTML
- * @package Pager
- * @author Lorenzo Alberton <l.alberton@quipo.it>
- * @author Richard Heyes <richard@phpguru.org>
- * @copyright 2003-2007 Lorenzo Alberton, Richard Heyes
- * @license http://www.debian.org/misc/bsd.license BSD License (3 Clause)
- * @link http://pear.php.net/package/Pager
- */
-class Pager_Common
-{
- // {{{ class vars
-
- /**
- * @var integer number of items
- * @access private
- */
- var $_totalItems;
-
- /**
- * @var integer number of items per page
- * @access private
- */
- var $_perPage = 10;
-
- /**
- * @var integer number of page links for each window
- * @access private
- */
- var $_delta = 10;
-
- /**
- * @var integer current page number
- * @access private
- */
- var $_currentPage = 1;
-
- /**
- * @var integer total pages number
- * @access private
- */
- var $_totalPages = 1;
-
- /**
- * @var string CSS class for links
- * @access private
- */
- var $_linkClass = '';
-
- /**
- * @var string wrapper for CSS class name
- * @access private
- */
- var $_classString = '';
-
- /**
- * @var string path name
- * @access private
- */
- var $_path = PAGER_CURRENT_PATHNAME;
-
- /**
- * @var string file name
- * @access private
- */
- var $_fileName = PAGER_CURRENT_FILENAME;
-
- /**
- * @var boolean If false, don't override the fileName option. Use at your own risk.
- * @access private
- */
- var $_fixFileName = true;
-
- /**
- * @var boolean you have to use FALSE with mod_rewrite
- * @access private
- */
- var $_append = true;
-
- /**
- * @var string specifies which HTTP method to use
- * @access private
- */
- var $_httpMethod = 'GET';
-
- /**
- * @var string specifies which HTML form to use
- * @access private
- */
- var $_formID = '';
-
- /**
- * @var boolean whether or not to import submitted data
- * @access private
- */
- var $_importQuery = true;
-
- /**
- * @var string name of the querystring var for pageID
- * @access private
- */
- var $_urlVar = 'pageID';
-
- /**
- * @var array data to pass through the link
- * @access private
- */
- var $_linkData = array();
-
- /**
- * @var array additional URL vars
- * @access private
- */
- var $_extraVars = array();
-
- /**
- * @var array URL vars to ignore
- * @access private
- */
- var $_excludeVars = array();
-
- /**
- * @var boolean TRUE => expanded mode (for Pager_Sliding)
- * @access private
- */
- var $_expanded = true;
-
- /**
- * @var boolean TRUE => show accesskey attribute on <a> tags
- * @access private
- */
- var $_accesskey = false;
-
- /**
- * @var string extra attributes for the <a> tag
- * @access private
- */
- var $_attributes = '';
-
- /**
- * @var string onclick
- * @access private
- */
- var $_onclick = '';
-
- /**
- * @var string alt text for "first page" (use "%d" placeholder for page number)
- * @access private
- */
- var $_altFirst = 'first page';
-
- /**
- * @var string alt text for "previous page"
- * @access private
- */
- var $_altPrev = 'previous page';
-
- /**
- * @var string alt text for "next page"
- * @access private
- */
- var $_altNext = 'next page';
-
- /**
- * @var string alt text for "last page" (use "%d" placeholder for page number)
- * @access private
- */
- var $_altLast = 'last page';
-
- /**
- * @var string alt text for "page" (use optional "%d" placeholder for page number)
- * @access private
- */
- var $_altPage = 'page';
-
- /**
- * @var string image/text to use as "prev" link
- * @access private
- */
- var $_prevImg = '<< Back';
-
- /**
- * @var string image/text to use as "next" link
- * @access private
- */
- var $_nextImg = 'Next >>';
-
- /**
- * @var string link separator
- * @access private
- */
- var $_separator = '';
-
- /**
- * @var integer number of spaces before separator
- * @access private
- */
- var $_spacesBeforeSeparator = 0;
-
- /**
- * @var integer number of spaces after separator
- * @access private
- */
- var $_spacesAfterSeparator = 1;
-
- /**
- * @var string CSS class name for current page link
- * @access private
- */
- var $_curPageLinkClassName = '';
-
- /**
- * @var string Text before current page link
- * @access private
- */
- var $_curPageSpanPre = '';
-
- /**
- * @var string Text after current page link
- * @access private
- */
- var $_curPageSpanPost = '';
-
- /**
- * @var string Text before first page link
- * @access private
- */
- var $_firstPagePre = '[';
-
- /**
- * @var string Text to be used for first page link
- * @access private
- */
- var $_firstPageText = '';
-
- /**
- * @var string Text after first page link
- * @access private
- */
- var $_firstPagePost = ']';
-
- /**
- * @var string Text before last page link
- * @access private
- */
- var $_lastPagePre = '[';
-
- /**
- * @var string Text to be used for last page link
- * @access private
- */
- var $_lastPageText = '';
-
- /**
- * @var string Text after last page link
- * @access private
- */
- var $_lastPagePost = ']';
-
- /**
- * @var string Will contain the HTML code for the spaces
- * @access private
- */
- var $_spacesBefore = '';
-
- /**
- * @var string Will contain the HTML code for the spaces
- * @access private
- */
- var $_spacesAfter = '';
-
- /**
- * @var string $_firstLinkTitle
- * @access private
- */
- var $_firstLinkTitle = 'first page';
-
- /**
- * @var string $_nextLinkTitle
- * @access private
- */
- var $_nextLinkTitle = 'next page';
-
- /**
- * @var string $_prevLinkTitle
- * @access private
- */
- var $_prevLinkTitle = 'previous page';
-
- /**
- * @var string $_lastLinkTitle
- * @access private
- */
- var $_lastLinkTitle = 'last page';
-
- /**
- * @var string Text to be used for the 'show all' option in the select box
- * @access private
- */
- var $_showAllText = '';
-
- /**
- * @var array data to be paged
- * @access private
- */
- var $_itemData = null;
-
- /**
- * @var boolean If TRUE and there's only one page, links aren't shown
- * @access private
- */
- var $_clearIfVoid = true;
-
- /**
- * @var boolean Use session for storing the number of items per page
- * @access private
- */
- var $_useSessions = false;
-
- /**
- * @var boolean Close the session when finished reading/writing data
- * @access private
- */
- var $_closeSession = false;
-
- /**
- * @var string name of the session var for number of items per page
- * @access private
- */
- var $_sessionVar = 'setPerPage';
-
- /**
- * Pear error mode (when raiseError is called)
- * (see PEAR doc)
- *
- * @var integer $_pearErrorMode
- * @access private
- */
- var $_pearErrorMode = null;
-
- // }}}
- // {{{ public vars
-
- /**
- * @var string Complete set of links
- * @access public
- */
- var $links = '';
-
- /**
- * @var string Complete set of link tags
- * @access public
- */
- var $linkTags = '';
-
- /**
- * @var array Complete set of raw link tags
- * @access public
- */
- var $linkTagsRaw = array();
-
- /**
- * @var array Array with a key => value pair representing
- * page# => bool value (true if key==currentPageNumber).
- * can be used for extreme customization.
- * @access public
- */
- var $range = array();
-
- /**
- * @var array list of available options (safety check)
- * @access private
- */
- var $_allowed_options = array(
- 'totalItems',
- 'perPage',
- 'delta',
- 'linkClass',
- 'path',
- 'fileName',
- 'fixFileName',
- 'append',
- 'httpMethod',
- 'formID',
- 'importQuery',
- 'urlVar',
- 'altFirst',
- 'altPrev',
- 'altNext',
- 'altLast',
- 'altPage',
- 'prevImg',
- 'nextImg',
- 'expanded',
- 'accesskey',
- 'attributes',
- 'onclick',
- 'separator',
- 'spacesBeforeSeparator',
- 'spacesAfterSeparator',
- 'curPageLinkClassName',
- 'curPageSpanPre',
- 'curPageSpanPost',
- 'firstPagePre',
- 'firstPageText',
- 'firstPagePost',
- 'lastPagePre',
- 'lastPageText',
- 'lastPagePost',
- 'firstLinkTitle',
- 'nextLinkTitle',
- 'prevLinkTitle',
- 'lastLinkTitle',
- 'showAllText',
- 'itemData',
- 'clearIfVoid',
- 'useSessions',
- 'closeSession',
- 'sessionVar',
- 'pearErrorMode',
- 'extraVars',
- 'excludeVars',
- 'currentPage',
- );
-
- // }}}
- // {{{ build()
-
- /**
- * Generate or refresh the links and paged data after a call to setOptions()
- *
- * @return void
- * @access public
- */
- function build()
- {
- //reset
- $this->_pageData = array();
- $this->links = '';
- $this->linkTags = '';
- $this->linkTagsRaw = array();
-
- $this->_generatePageData();
- $this->_setFirstLastText();
-
- if ($this->_totalPages > (2 * $this->_delta + 1)) {
- $this->links .= $this->_printFirstPage();
- }
-
- $this->links .= $this->_getBackLink();
- $this->links .= $this->_getPageLinks();
- $this->links .= $this->_getNextLink();
-
- $this->linkTags .= $this->_getFirstLinkTag();
- $this->linkTags .= $this->_getPrevLinkTag();
- $this->linkTags .= $this->_getNextLinkTag();
- $this->linkTags .= $this->_getLastLinkTag();
-
- $this->linkTagsRaw['first'] = $this->_getFirstLinkTag(true);
- $this->linkTagsRaw['prev'] = $this->_getPrevLinkTag(true);
- $this->linkTagsRaw['next'] = $this->_getNextLinkTag(true);
- $this->linkTagsRaw['last'] = $this->_getLastLinkTag(true);
-
- if ($this->_totalPages > (2 * $this->_delta + 1)) {
- $this->links .= $this->_printLastPage();
- }
- }
-
- // }}}
- // {{{ getPageData()
-
- /**
- * Returns an array of current pages data
- *
- * @param integer $pageID Desired page ID (optional)
- *
- * @return array Page data
- * @access public
- */
- function getPageData($pageID = null)
- {
- $pageID = empty($pageID) ? $this->_currentPage : $pageID;
-
- if (!isset($this->_pageData)) {
- $this->_generatePageData();
- }
- if (!empty($this->_pageData[$pageID])) {
- return $this->_pageData[$pageID];
- }
- return array();
- }
-
- // }}}
- // {{{ getPageIdByOffset()
-
- /**
- * Returns pageID for given offset
- *
- * @param integer $index Offset to get pageID for
- *
- * @return integer PageID for given offset
- * @access public
- */
- function getPageIdByOffset($index)
- {
- $msg = 'function "getPageIdByOffset()" not implemented.';
- return $this->raiseError($msg, ERROR_PAGER_NOT_IMPLEMENTED);
- }
-
- // }}}
- // {{{ getOffsetByPageId()
-
- /**
- * Returns offsets for given pageID. Eg, if you
- * pass it pageID one and your perPage limit is 10
- * it will return (1, 10). PageID of 2 would
- * give you (11, 20).
- *
- * @param integer $pageID PageID to get offsets for
- *
- * @return array First and last offsets
- * @access public
- */
- function getOffsetByPageId($pageID = null)
- {
- $pageID = isset($pageID) ? $pageID : $this->_currentPage;
- if (!isset($this->_pageData)) {
- $this->_generatePageData();
- }
-
- if (isset($this->_pageData[$pageID]) || is_null($this->_itemData)) {
- return array(
- max(($this->_perPage * ($pageID - 1)) + 1, 1),
- min($this->_totalItems, $this->_perPage * $pageID)
- );
- }
- return array(0, 0);
- }
-
- // }}}
- // {{{ getPageRangeByPageId()
-
- /**
- * Given a PageId, it returns the limits of the range of pages displayed.
- *
- * @param integer $pageID PageID to get offsets for
- *
- * @return array First and last offsets
- * @access public
- */
- function getPageRangeByPageId($pageID = null)
- {
- $msg = 'function "getPageRangeByPageId()" not implemented.';
- return $this->raiseError($msg, ERROR_PAGER_NOT_IMPLEMENTED);
- }
-
- // }}}
- // {{{ getLinks()
-
- /**
- * Returns back/next/first/last and page links,
- * both as ordered and associative array.
- *
- * NB: in original PEAR::Pager this method accepted two parameters,
- * $back_html and $next_html. Now the only parameter accepted is
- * an integer ($pageID), since the html text for prev/next links can
- * be set in the factory. If a second parameter is provided, then
- * the method act as it previously did. This hack was done to mantain
- * backward compatibility only.
- *
- * @param integer $pageID Optional pageID. If specified, links for that
- * page are provided instead of current one.
- * [ADDED IN NEW PAGER VERSION]
- * @param string $next_html HTML to put inside the next link
- * [deprecated: use the factory instead]
- *
- * @return array back/next/first/last and page links
- * @access public
- */
- function getLinks($pageID=null, $next_html='')
- {
- $msg = 'function "getLinks()" not implemented.';
- return $this->raiseError($msg, ERROR_PAGER_NOT_IMPLEMENTED);
- }
-
- // }}}
- // {{{ getCurrentPageID()
-
- /**
- * Returns ID of current page
- *
- * @return integer ID of current page
- * @access public
- */
- function getCurrentPageID()
- {
- return $this->_currentPage;
- }
-
- // }}}
- // {{{ getNextPageID()
-
- /**
- * Returns next page ID. If current page is last page
- * this function returns FALSE
- *
- * @return mixed Next page ID or false
- * @access public
- */
- function getNextPageID()
- {
- return ($this->getCurrentPageID() == $this->numPages() ? false : $this->getCurrentPageID() + 1);
- }
-
- // }}}
- // {{{ getPreviousPageID()
-
- /**
- * Returns previous page ID. If current page is first page
- * this function returns FALSE
- *
- * @return mixed Previous page ID or false
- * @access public
- */
- function getPreviousPageID()
- {
- return $this->isFirstPage() ? false : $this->getCurrentPageID() - 1;
- }
-
- // }}}
- // {{{ numItems()
-
- /**
- * Returns number of items
- *
- * @return integer Number of items
- * @access public
- */
- function numItems()
- {
- return $this->_totalItems;
- }
-
- // }}}
- // {{{ numPages()
-
- /**
- * Returns number of pages
- *
- * @return integer Number of pages
- * @access public
- */
- function numPages()
- {
- return (int)$this->_totalPages;
- }
-
- // }}}
- // {{{ isFirstPage()
-
- /**
- * Returns whether current page is first page
- *
- * @return bool First page or not
- * @access public
- */
- function isFirstPage()
- {
- return ($this->_currentPage < 2);
- }
-
- // }}}
- // {{{ isLastPage()
-
- /**
- * Returns whether current page is last page
- *
- * @return bool Last page or not
- * @access public
- */
- function isLastPage()
- {
- return ($this->_currentPage == $this->_totalPages);
- }
-
- // }}}
- // {{{ isLastPageComplete()
-
- /**
- * Returns whether last page is complete
- *
- * @return bool Last age complete or not
- * @access public
- */
- function isLastPageComplete()
- {
- return !($this->_totalItems % $this->_perPage);
- }
-
- // }}}
- // {{{ _generatePageData()
-
- /**
- * Calculates all page data
- *
- * @return void
- * @access private
- */
- function _generatePageData()
- {
- // Been supplied an array of data?
- if (!is_null($this->_itemData)) {
- $this->_totalItems = count($this->_itemData);
- }
- $this->_totalPages = ceil((float)$this->_totalItems / (float)$this->_perPage);
- $i = 1;
- if (!empty($this->_itemData)) {
- foreach ($this->_itemData as $key => $value) {
- $this->_pageData[$i][$key] = $value;
- if (count($this->_pageData[$i]) >= $this->_perPage) {
- $i++;
- }
- }
- } else {
- $this->_pageData = array();
- }
-
- //prevent URL modification
- $this->_currentPage = min($this->_currentPage, $this->_totalPages);
- }
-
- // }}}
- // {{{ _renderLink()
-
- /**
- * Renders a link using the appropriate method
- *
- * @param string $altText Alternative text for this link (title property)
- * @param string $linkText Text contained by this link
- *
- * @return string The link in string form
- * @access private
- */
- function _renderLink($altText, $linkText)
- {
- if ($this->_httpMethod == 'GET') {
- if ($this->_append) {
- $href = '?' . $this->_http_build_query_wrapper($this->_linkData);
- } else {
- $href = str_replace('%d', $this->_linkData[$this->_urlVar], $this->_fileName);
- }
- $onclick = '';
- if (array_key_exists($this->_urlVar, $this->_linkData)) {
- $onclick = str_replace('%d', $this->_linkData[$this->_urlVar], $this->_onclick);
- }
- return sprintf('<a href="%s"%s%s%s%s title="%s">%s</a>',
- htmlentities($this->_url . $href),
- empty($this->_classString) ? '' : ' '.$this->_classString,
- empty($this->_attributes) ? '' : ' '.$this->_attributes,
- empty($this->_accesskey) ? '' : ' accesskey="'.$this->_linkData[$this->_urlVar].'"',
- empty($onclick) ? '' : ' onclick="'.$onclick.'"',
- $altText,
- $linkText
- );
- } elseif ($this->_httpMethod == 'POST') {
- return sprintf("<a href='javascript:void(0)' onclick='%s'%s%s%s title='%s'>%s</a>",
- $this->_generateFormOnClick($this->_url, $this->_linkData),
- empty($this->_classString) ? '' : ' '.$this->_classString,
- empty($this->_attributes) ? '' : ' '.$this->_attributes,
- empty($this->_accesskey) ? '' : ' accesskey=\''.$this->_linkData[$this->_urlVar].'\'',
- $altText,
- $linkText
- );
- }
- return '';
- }
-
- // }}}
- // {{{ _generateFormOnClick()
-
- /**
- * Mimics http_build_query() behavior in the way the data
- * in $data will appear when it makes it back to the server.
- * For example:
- * $arr = array('array' => array(array('hello', 'world'),
- * 'things' => array('stuff', 'junk'));
- * http_build_query($arr)
- * and _generateFormOnClick('foo.php', $arr)
- * will yield
- * $_REQUEST['array'][0][0] === 'hello'
- * $_REQUEST['array'][0][1] === 'world'
- * $_REQUEST['array']['things'][0] === 'stuff'
- * $_REQUEST['array']['things'][1] === 'junk'
- *
- * However, instead of generating a query string, it generates
- * Javascript to create and submit a form.
- *
- * @param string $formAction where the form should be submitted
- * @param array $data the associative array of names and values
- *
- * @return string A string of javascript that generates a form and submits it
- * @access private
- */
- function _generateFormOnClick($formAction, $data)
- {
- // Check we have an array to work with
- if (!is_array($data)) {
- trigger_error(
- '_generateForm() Parameter 1 expected to be Array or Object. Incorrect value given.',
- E_USER_WARNING
- );
- return false;
- }
-
- if (!empty($this->_formID)) {
- $str = 'var form = document.getElementById("'.$this->_formID.'"); var input = ""; ';
- } else {
- $str = 'var form = document.createElement("form"); var input = ""; ';
- }
-
- // We /shouldn't/ need to escape the URL ...
- $str .= sprintf('form.action = "%s"; ', htmlentities($formAction));
- $str .= sprintf('form.method = "%s"; ', $this->_httpMethod);
- foreach ($data as $key => $val) {
- $str .= $this->_generateFormOnClickHelper($val, $key);
- }
-
- if (empty($this->_formID)) {
- $str .= 'document.getElementsByTagName("body")[0].appendChild(form);';
- }
-
- $str .= 'form.submit(); return false;';
- return $str;
- }
-
- // }}}
- // {{{ _generateFormOnClickHelper
-
- /**
- * This is used by _generateFormOnClick().
- * Recursively processes the arrays, objects, and literal values.
- *
- * @param mixed $data Data that should be rendered
- * @param string $prev The name so far
- *
- * @return string A string of Javascript that creates form inputs
- * representing the data
- * @access private
- */
- function _generateFormOnClickHelper($data, $prev = '')
- {
- $str = '';
- if (is_array($data) || is_object($data)) {
- // foreach key/visible member
- foreach ((array)$data as $key => $val) {
- // append [$key] to prev
- $tempKey = sprintf('%s[%s]', $prev, $key);
- $str .= $this->_generateFormOnClickHelper($val, $tempKey);
- }
- } else { // must be a literal value
- // escape newlines and carriage returns
- $search = array("\n", "\r");
- $replace = array('\n', '\n');
- $escapedData = str_replace($search, $replace, $data);
- // am I forgetting any dangerous whitespace?
- // would a regex be faster?
- // if it's already encoded, don't encode it again
- if (!$this->_isEncoded($escapedData)) {
- $escapedData = urlencode($escapedData);
- }
- $escapedData = htmlentities($escapedData, ENT_QUOTES, 'UTF-8');
-
- $str .= 'input = document.createElement("input"); ';
- $str .= 'input.type = "hidden"; ';
- $str .= sprintf('input.name = "%s"; ', $prev);
- $str .= sprintf('input.value = "%s"; ', $escapedData);
- $str .= 'form.appendChild(input); ';
- }
- return $str;
- }
-
- // }}}
- // {{{ _getLinksData()
-
- /**
- * Returns the correct link for the back/pages/next links
- *
- * @return array Data
- * @access private
- */
- function _getLinksData()
- {
- $qs = array();
- if ($this->_importQuery) {
- if ($this->_httpMethod == 'POST') {
- $qs = $_POST;
- } elseif ($this->_httpMethod == 'GET') {
- $qs = $_GET;
- }
- }
- foreach ($this->_excludeVars as $exclude) {
- if (array_key_exists($exclude, $qs)) {
- unset($qs[$exclude]);
- }
- }
- if (count($this->_extraVars)) {
- $this->_recursive_urldecode($this->_extraVars);
- $qs = array_merge($qs, $this->_extraVars);
- }
- if (count($qs) && get_magic_quotes_gpc()) {
- $this->_recursive_stripslashes($qs);
- }
- return $qs;
- }
-
- // }}}
- // {{{ _recursive_stripslashes()
-
- /**
- * Helper method
- *
- * @param string|array &$var variable to clean
- *
- * @return void
- * @access private
- */
- function _recursive_stripslashes(&$var)
- {
- if (is_array($var)) {
- foreach (array_keys($var) as $k) {
- $this->_recursive_stripslashes($var[$k]);
- }
- } else {
- $var = stripslashes($var);
- }
- }
-
- // }}}
- // {{{ _recursive_urldecode()
-
- /**
- * Helper method
- *
- * @param string|array &$var variable to decode
- *
- * @return void
- * @access private
- */
- function _recursive_urldecode(&$var)
- {
- if (is_array($var)) {
- foreach (array_keys($var) as $k) {
- $this->_recursive_urldecode($var[$k]);
- }
- } else {
- $trans_tbl = array_flip(get_html_translation_table(HTML_ENTITIES));
- $var = strtr($var, $trans_tbl);
- }
- }
-
- // }}}
- // {{{ _getBackLink()
-
- /**
- * Returns back link
- *
- * @param string $url URL to use in the link [deprecated: use the factory instead]
- * @param string $link HTML to use as the link [deprecated: use the factory instead]
- *
- * @return string The link
- * @access private
- */
- function _getBackLink($url='', $link='')
- {
- //legacy settings... the preferred way to set an option
- //now is passing it to the factory
- if (!empty($url)) {
- $this->_path = $url;
- }
- if (!empty($link)) {
- $this->_prevImg = $link;
- }
- $back = '';
- if ($this->_currentPage > 1) {
- $this->_linkData[$this->_urlVar] = $this->getPreviousPageID();
- $back = $this->_renderLink($this->_altPrev, $this->_prevImg)
- . $this->_spacesBefore . $this->_spacesAfter;
- }
- return $back;
- }
-
- // }}}
- // {{{ _getPageLinks()
-
- /**
- * Returns pages link
- *
- * @param string $url URL to use in the link [deprecated: use the factory instead]
- *
- * @return string Links
- * @access private
- */
- function _getPageLinks($url='')
- {
- $msg = 'function "_getPageLinks()" not implemented.';
- return $this->raiseError($msg, ERROR_PAGER_NOT_IMPLEMENTED);
- }
-
- // }}}
- // {{{ _getNextLink()
-
- /**
- * Returns next link
- *
- * @param string $url URL to use in the link [deprecated: use the factory instead]
- * @param string $link HTML to use as the link [deprecated: use the factory instead]
- *
- * @return string The link
- * @access private
- */
- function _getNextLink($url='', $link='')
- {
- //legacy settings... the preferred way to set an option
- //now is passing it to the factory
- if (!empty($url)) {
- $this->_path = $url;
- }
- if (!empty($link)) {
- $this->_nextImg = $link;
- }
- $next = '';
- if ($this->_currentPage < $this->_totalPages) {
- $this->_linkData[$this->_urlVar] = $this->getNextPageID();
- $next = $this->_spacesAfter
- . $this->_renderLink($this->_altNext, $this->_nextImg)
- . $this->_spacesBefore . $this->_spacesAfter;
- }
- return $next;
- }
-
- // }}}
- // {{{ _getFirstLinkTag()
-
- /**
- * Returns first link tag
- *
- * @param bool $raw should tag returned as array
- *
- * @return mixed string with html link tag or separated as array
- * @access private
- */
- function _getFirstLinkTag($raw = false)
- {
- if ($this->isFirstPage() || ($this->_httpMethod != 'GET')) {
- return $raw ? array() : '';
- }
- if ($raw) {
- return array(
- 'url' => $this->_getLinkTagUrl(1),
- 'title' => $this->_firstLinkTitle
- );
- }
- return sprintf('<link rel="first" href="%s" title="%s" />'."\n",
- $this->_getLinkTagUrl(1),
- $this->_firstLinkTitle
- );
- }
-
- // }}}
- // {{{ _getPrevLinkTag()
-
- /**
- * Returns previous link tag
- *
- * @param bool $raw should tag returned as array
- *
- * @return mixed string with html link tag or separated as array
- * @access private
- */
- function _getPrevLinkTag($raw = false)
- {
- if ($this->isFirstPage() || ($this->_httpMethod != 'GET')) {
- return $raw ? array() : '';
- }
- if ($raw) {
- return array(
- 'url' => $this->_getLinkTagUrl($this->getPreviousPageID()),
- 'title' => $this->_prevLinkTitle
- );
- }
- return sprintf('<link rel="previous" href="%s" title="%s" />'."\n",
- $this->_getLinkTagUrl($this->getPreviousPageID()),
- $this->_prevLinkTitle
- );
- }
-
- // }}}
- // {{{ _getNextLinkTag()
-
- /**
- * Returns next link tag
- *
- * @param bool $raw should tag returned as array
- *
- * @return mixed string with html link tag or separated as array
- * @access private
- */
- function _getNextLinkTag($raw = false)
- {
- if ($this->isLastPage() || ($this->_httpMethod != 'GET')) {
- return $raw ? array() : '';
- }
- if ($raw) {
- return array(
- 'url' => $this->_getLinkTagUrl($this->getNextPageID()),
- 'title' => $this->_nextLinkTitle
- );
- }
- return sprintf('<link rel="next" href="%s" title="%s" />'."\n",
- $this->_getLinkTagUrl($this->getNextPageID()),
- $this->_nextLinkTitle
- );
- }
-
- // }}}
- // {{{ _getLastLinkTag()
-
- /**
- * Returns last link tag
- *
- * @param bool $raw should tag returned as array
- *
- * @return mixed string with html link tag or separated as array
- * @access private
- */
- function _getLastLinkTag($raw = false)
- {
- if ($this->isLastPage() || ($this->_httpMethod != 'GET')) {
- return $raw ? array() : '';
- }
- if ($raw) {
- return array(
- 'url' => $this->_getLinkTagUrl($this->_totalPages),
- 'title' => $this->_lastLinkTitle
- );
- }
- return sprintf('<link rel="last" href="%s" title="%s" />'."\n",
- $this->_getLinkTagUrl($this->_totalPages),
- $this->_lastLinkTitle
- );
- }
-
- // }}}
- // {{{ _getLinkTagUrl()
-
- /**
- * Helper method
- *
- * @param integer $pageID page ID
- *
- * @return string the link tag url
- * @access private
- */
- function _getLinkTagUrl($pageID)
- {
- $this->_linkData[$this->_urlVar] = $pageID;
- if ($this->_append) {
- $href = '?' . $this->_http_build_query_wrapper($this->_linkData);
- } else {
- $href = str_replace('%d', $this->_linkData[$this->_urlVar], $this->_fileName);
- }
- return htmlentities($this->_url . $href);
- }
-
- // }}}
- // {{{ getPerPageSelectBox()
-
- /**
- * Returns a string with a XHTML SELECT menu,
- * useful for letting the user choose how many items per page should be
- * displayed. If parameter useSessions is TRUE, this value is stored in
- * a session var. The string isn't echoed right now so you can use it
- * with template engines.
- *
- * @param integer $start starting value for the select menu
- * @param integer $end ending value for the select menu
- * @param integer $step step between values in the select menu
- * @param boolean $showAllData If true, perPage is set equal to totalItems.
- * @param array $extraParams (or string $optionText for BC reasons)
- * - 'optionText': text to show in each option.
- * Use '%d' where you want to see the number of pages selected.
- * - 'attributes': (html attributes) Tag attributes or
- * HTML attributes (id="foo" pairs), will be inserted in the
- * <select> tag
- *
- * @return string xhtml select box
- * @access public
- */
- function getPerPageSelectBox($start=5, $end=30, $step=5, $showAllData=false, $extraParams=array())
- {
- include_once 'Pager/HtmlWidgets.php';
- $widget =& new Pager_HtmlWidgets($this);
- return $widget->getPerPageSelectBox($start, $end, $step, $showAllData, $extraParams);
- }
-
- // }}}
- // {{{ getPageSelectBox()
-
- /**
- * Returns a string with a XHTML SELECT menu with the page numbers,
- * useful as an alternative to the links
- *
- * @param array $params - 'optionText': text to show in each option.
- * Use '%d' where you want to see the number
- * of pages selected.
- * - 'autoSubmit': if TRUE, add some js code
- * to submit the form on the onChange event
- * @param string $extraAttributes (html attributes) Tag attributes or
- * HTML attributes (id="foo" pairs), will be
- * inserted in the <select> tag
- *
- * @return string xhtml select box
- * @access public
- */
- function getPageSelectBox($params = array(), $extraAttributes = '')
- {
- include_once 'Pager/HtmlWidgets.php';
- $widget =& new Pager_HtmlWidgets($this);
- return $widget->getPageSelectBox($params, $extraAttributes);
- }
-
- // }}}
- // {{{ _printFirstPage()
-
- /**
- * Print [1]
- *
- * @return string String with link to 1st page,
- * or empty string if this is the 1st page.
- * @access private
- */
- function _printFirstPage()
- {
- if ($this->isFirstPage()) {
- return '';
- }
- $this->_linkData[$this->_urlVar] = 1;
- return $this->_renderLink(
- str_replace('%d', 1, $this->_altFirst),
- $this->_firstPagePre . $this->_firstPageText . $this->_firstPagePost
- ) . $this->_spacesBefore . $this->_spacesAfter;
- }
-
- // }}}
- // {{{ _printLastPage()
-
- /**
- * Print [numPages()]
- *
- * @return string String with link to last page,
- * or empty string if this is the 1st page.
- * @access private
- */
- function _printLastPage()
- {
- if ($this->isLastPage()) {
- return '';
- }
- $this->_linkData[$this->_urlVar] = $this->_totalPages;
- return $this->_renderLink(
- str_replace('%d', $this->_totalPages, $this->_altLast),
- $this->_lastPagePre . $this->_lastPageText . $this->_lastPagePost
- );
- }
-
- // }}}
- // {{{ _setFirstLastText()
-
- /**
- * sets the private _firstPageText, _lastPageText variables
- * based on whether they were set in the options
- *
- * @return void
- * @access private
- */
- function _setFirstLastText()
- {
- if ($this->_firstPageText == '') {
- $this->_firstPageText = '1';
- }
- if ($this->_lastPageText == '') {
- $this->_lastPageText = $this->_totalPages;
- }
- }
-
- // }}}
- // {{{ _http_build_query_wrapper()
-
- /**
- * This is a slightly modified version of the http_build_query() function;
- * it heavily borrows code from PHP_Compat's http_build_query().
- * The main change is the usage of htmlentities instead of urlencode,
- * since it's too aggressive
- *
- * @param array $data array of querystring values
- *
- * @return string
- * @access private
- */
- function _http_build_query_wrapper($data)
- {
- $data = (array)$data;
- if (empty($data)) {
- return '';
- }
- $separator = ini_get('arg_separator.output');
- if ($separator == '&') {
- $separator = '&'; //the string is escaped by htmlentities anyway...
- }
- $tmp = array ();
- foreach ($data as $key => $val) {
- if (is_scalar($val)) {
- //array_push($tmp, $key.'='.$val);
- $val = urlencode($val);
- array_push($tmp, $key .'='. str_replace('%2F', '/', $val));
- continue;
- }
- // If the value is an array, recursively parse it
- if (is_array($val)) {
- array_push($tmp, $this->__http_build_query($val, htmlentities($key)));
- continue;
- }
- }
- return implode($separator, $tmp);
- }
-
- // }}}
- // {{{ __http_build_query()
-
- /**
- * Helper function
- *
- * @param array $array array of querystring values
- * @param string $name key
- *
- * @return string
- * @access private
- */
- function __http_build_query($array, $name)
- {
- $tmp = array ();
- $separator = ini_get('arg_separator.output');
- if ($separator == '&') {
- $separator = '&'; //the string is escaped by htmlentities anyway...
- }
- foreach ($array as $key => $value) {
- if (is_array($value)) {
- //array_push($tmp, $this->__http_build_query($value, sprintf('%s[%s]', $name, $key)));
- array_push($tmp, $this->__http_build_query($value, $name.'%5B'.$key.'%5D'));
- } elseif (is_scalar($value)) {
- //array_push($tmp, sprintf('%s[%s]=%s', $name, htmlentities($key), htmlentities($value)));
- array_push($tmp, $name.'%5B'.htmlentities($key).'%5D='.htmlentities($value));
- } elseif (is_object($value)) {
- //array_push($tmp, $this->__http_build_query(get_object_vars($value), sprintf('%s[%s]', $name, $key)));
- array_push($tmp, $this->__http_build_query(get_object_vars($value), $name.'%5B'.$key.'%5D'));
- }
- }
- return implode($separator, $tmp);
- }
-
- // }}}
- // {{{ _isEncoded()
-
- /**
- * Helper function
- * Check if a string is an encoded multibyte string
- *
- * @param string $string string to check
- *
- * @return boolean
- * @access private
- */
-
- function _isEncoded($string)
- {
- $hexchar = '&#[\dA-Fx]{2,};';
- return preg_match("/^(\s|($hexchar))*$/Uims", $string) ? true : false;
- }
-
- // }}}
- // {{{ raiseError()
-
- /**
- * conditionally includes PEAR base class and raise an error
- *
- * @param string $msg Error message
- * @param integer $code Error code
- *
- * @return PEAR_Error
- * @access private
- */
- function raiseError($msg, $code)
- {
- include_once 'PEAR.php';
- if (empty($this->_pearErrorMode)) {
- $this->_pearErrorMode = PEAR_ERROR_RETURN;
- }
- return PEAR::raiseError($msg, $code, $this->_pearErrorMode);
- }
-
- // }}}
- // {{{ setOptions()
-
- /**
- * Set and sanitize options
- *
- * @param mixed $options An associative array of option names and their values
- *
- * @return integer error code (PAGER_OK on success)
- * @access public
- */
- function setOptions($options)
- {
- foreach ($options as $key => $value) {
- if (in_array($key, $this->_allowed_options) && (!is_null($value))) {
- $this->{'_' . $key} = $value;
- }
- }
-
- //autodetect http method
- if (!isset($options['httpMethod'])
- && !isset($_GET[$this->_urlVar])
- && isset($_POST[$this->_urlVar])
- ) {
- $this->_httpMethod = 'POST';
- } else {
- $this->_httpMethod = strtoupper($this->_httpMethod);
- }
-
- $this->_fileName = ltrim($this->_fileName, '/'); //strip leading slash
- $this->_path = rtrim($this->_path, '/'); //strip trailing slash
-
- if ($this->_append) {
- if ($this->_fixFileName) {
- $this->_fileName = PAGER_CURRENT_FILENAME; //avoid possible user error;
- }
- $this->_url = $this->_path.(!empty($this->_path) ? '/' : '').$this->_fileName;
- } else {
- $this->_url = $this->_path;
- if (0 != strncasecmp($this->_fileName, 'javascript', 10)) {
- $this->_url .= (!empty($this->_path) ? '/' : '');
- }
- if (false === strpos($this->_fileName, '%d')) {
- trigger_error($this->errorMessage(ERROR_PAGER_INVALID_USAGE), E_USER_WARNING);
- }
- }
- if (false === strpos($this->_altPage, '%d')) {
- //by default, append page number at the end
- $this->_altPage .= ' %d';
- }
-
- $this->_classString = '';
- if (strlen($this->_linkClass)) {
- $this->_classString = 'class="'.$this->_linkClass.'"';
- }
-
- if (strlen($this->_curPageLinkClassName)) {
- $this->_curPageSpanPre .= '<span class="'.$this->_curPageLinkClassName.'">';
- $this->_curPageSpanPost = '</span>' . $this->_curPageSpanPost;
- }
-
- $this->_perPage = max($this->_perPage, 1); //avoid possible user errors
-
- if ($this->_useSessions && !isset($_SESSION)) {
- session_start();
- }
- if (!empty($_REQUEST[$this->_sessionVar])) {
- $this->_perPage = max(1, (int)$_REQUEST[$this->_sessionVar]);
- if ($this->_useSessions) {
- $_SESSION[$this->_sessionVar] = $this->_perPage;
- }
- }
-
- if (!empty($_SESSION[$this->_sessionVar]) && $this->_useSessions) {
- $this->_perPage = $_SESSION[$this->_sessionVar];
- }
-
- if ($this->_closeSession) {
- session_write_close();
- }
-
- $this->_spacesBefore = str_repeat(' ', $this->_spacesBeforeSeparator);
- $this->_spacesAfter = str_repeat(' ', $this->_spacesAfterSeparator);
-
- if (isset($_REQUEST[$this->_urlVar]) && empty($options['currentPage'])) {
- $this->_currentPage = (int)$_REQUEST[$this->_urlVar];
- }
- $this->_currentPage = max($this->_currentPage, 1);
- $this->_linkData = $this->_getLinksData();
-
- return PAGER_OK;
- }
-
- // }}}
- // {{{ getOption()
-
- /**
- * Return the current value of a given option
- *
- * @param string $name option name
- *
- * @return mixed option value
- * @access public
- */
- function getOption($name)
- {
- if (!in_array($name, $this->_allowed_options)) {
- $msg = 'invalid option: '.$name;
- return $this->raiseError($msg, ERROR_PAGER_INVALID);
- }
- return $this->{'_' . $name};
- }
-
- // }}}
- // {{{ getOptions()
-
- /**
- * Return an array with all the current pager options
- *
- * @return array list of all the pager options
- * @access public
- */
- function getOptions()
- {
- $options = array();
- foreach ($this->_allowed_options as $option) {
- $options[$option] = $this->{'_' . $option};
- }
- return $options;
- }
-
- // }}}
- // {{{ errorMessage()
-
- /**
- * Return a textual error message for a PAGER error code
- *
- * @param integer $code error code
- *
- * @return string error message
- * @access public
- */
- function errorMessage($code)
- {
- static $errorMessages;
- if (!isset($errorMessages)) {
- $errorMessages = array(
- ERROR_PAGER => 'unknown error',
- ERROR_PAGER_INVALID => 'invalid',
- ERROR_PAGER_INVALID_PLACEHOLDER => 'invalid format - use "%d" as placeholder.',
- ERROR_PAGER_INVALID_USAGE => 'if $options[\'append\'] is set to false, '
- .' $options[\'fileName\'] MUST contain the "%d" placeholder.',
- ERROR_PAGER_NOT_IMPLEMENTED => 'not implemented'
- );
- }
-
- return (isset($errorMessages[$code]) ?
- $errorMessages[$code] : $errorMessages[ERROR_PAGER]);
- }
-
- // }}}
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * Contains the Pager_HtmlWidgets class
- *
- * PHP versions 4 and 5
- *
- * LICENSE: Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE FREEBSD PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * @category HTML
- * @package Pager
- * @author Lorenzo Alberton <l.alberton@quipo.it>
- * @copyright 2003-2007 Lorenzo Alberton
- * @license http://www.debian.org/misc/bsd.license BSD License (3 Clause)
- * @version CVS: $Id: HtmlWidgets.php,v 1.1.1.1 2008/04/28 15:20:46 jamie Exp $
- * @link http://pear.php.net/package/Pager
- */
-
-/**
- * Pager_HtmlWidgets
- *
- * @category HTML
- * @package Pager
- * @author Lorenzo Alberton <l.alberton@quipo.it>
- * @copyright 2003-2007 Lorenzo Alberton
- * @license http://www.debian.org/misc/bsd.license BSD License (3 Clause)
- * @link http://pear.php.net/package/Pager
- */
-class Pager_HtmlWidgets
-{
- var $pager = null;
-
- // {{{ constructor
-
- /**
- * Constructor
- *
- * @param object &$pager Pager instance
- */
- function Pager_HtmlWidgets(&$pager)
- {
- $this->pager =& $pager;
- }
-
- // }}}
- // {{{ getPerPageSelectBox()
-
- /**
- * Returns a string with a XHTML SELECT menu,
- * useful for letting the user choose how many items per page should be
- * displayed. If parameter useSessions is TRUE, this value is stored in
- * a session var. The string isn't echoed right now so you can use it
- * with template engines.
- *
- * @param integer $start starting value for the select menu
- * @param integer $end ending value for the select menu
- * @param integer $step step between values in the select menu
- * @param boolean $showAllData If true, perPage is set equal to totalItems.
- * @param array $extraParams (or string $optionText for BC reasons)
- * - 'optionText': text to show in each option.
- * Use '%d' where you want to see the number of pages selected.
- * - 'attributes': (html attributes) Tag attributes or
- * HTML attributes (id="foo" pairs), will be inserted in the
- * <select> tag
- * - 'checkMaxLimit': if true, Pager checks if $end is bigger
- * than $totalItems, and doesn't show the extra select options
- *
- * @return string xhtml select box
- * @access public
- */
- function getPerPageSelectBox($start=5, $end=30, $step=5, $showAllData=false, $extraParams=array())
- {
- // FIXME: needs POST support
- $optionText = '%d';
- $attributes = '';
- $checkMaxLimit = false;
- if (is_string($extraParams)) {
- //old behavior, BC maintained
- $optionText = $extraParams;
- } else {
- if (array_key_exists('optionText', $extraParams)) {
- $optionText = $extraParams['optionText'];
- }
- if (array_key_exists('attributes', $extraParams)) {
- $attributes = $extraParams['attributes'];
- }
- if (array_key_exists('checkMaxLimit', $extraParams)) {
- $checkMaxLimit = $extraParams['checkMaxLimit'];
- }
- }
-
- if (!strstr($optionText, '%d')) {
- return $this->pager->raiseError(
- $this->pager->errorMessage(ERROR_PAGER_INVALID_PLACEHOLDER),
- ERROR_PAGER_INVALID_PLACEHOLDER
- );
- }
- $start = (int)$start;
- $end = (int)$end;
- $step = (int)$step;
- if (!empty($_SESSION[$this->pager->_sessionVar])) {
- $selected = (int)$_SESSION[$this->pager->_sessionVar];
- } else {
- $selected = $this->pager->_perPage;
- }
-
- if ($checkMaxLimit && $this->pager->_totalItems > 0 && $this->pager->_totalItems < $end) {
- $end = $this->pager->_totalItems;
- }
-
- $tmp = '<select name="'.$this->pager->_sessionVar.'"';
- if (!empty($attributes)) {
- $tmp .= ' '.$attributes;
- }
- $tmp .= '>';
- $last = $start;
- for ($i=$start; $i<=$end; $i+=$step) {
- $last = $i;
- $tmp .= '<option value="'.$i.'"';
- if ($i == $selected) {
- $tmp .= ' selected="selected"';
- }
- $tmp .= '>'.sprintf($optionText, $i).'</option>';
- }
- if ($showAllData && $last != $this->pager->_totalItems) {
- $tmp .= '<option value="'.$this->pager->_totalItems.'"';
- if ($this->pager->_totalItems == $selected) {
- $tmp .= ' selected="selected"';
- }
- $tmp .= '>';
- if (empty($this->pager->_showAllText)) {
- $tmp .= str_replace('%d', $this->pager->_totalItems, $optionText);
- } else {
- $tmp .= $this->pager->_showAllText;
- }
- $tmp .= '</option>';
- }
- $tmp .= '</select>';
- return $tmp;
- }
-
- // }}}
- // {{{ getPageSelectBox()
-
- /**
- * Returns a string with a XHTML SELECT menu with the page numbers,
- * useful as an alternative to the links
- *
- * @param array $params - 'optionText': text to show in each option.
- * Use '%d' where you want to see the number
- * of pages selected.
- * - 'autoSubmit': if TRUE, add some js code
- * to submit the form on the onChange event
- * @param string $extraAttributes (html attributes) Tag attributes or
- * HTML attributes (id="foo" pairs), will be
- * inserted in the <select> tag
- *
- * @return string xhtml select box
- * @access public
- */
- function getPageSelectBox($params = array(), $extraAttributes = '')
- {
- $optionText = '%d';
- if (array_key_exists('optionText', $params)) {
- $optionText = $params['optionText'];
- }
-
- if (!strstr($optionText, '%d')) {
- return $this->pager->raiseError(
- $this->pager->errorMessage(ERROR_PAGER_INVALID_PLACEHOLDER),
- ERROR_PAGER_INVALID_PLACEHOLDER
- );
- }
-
- $tmp = '<select name="'.$this->pager->_urlVar.'"';
- if (!empty($extraAttributes)) {
- $tmp .= ' '.$extraAttributes;
- }
- if (!empty($params['autoSubmit'])) {
- if ($this->pager->_httpMethod == 'GET') {
- $selector = '\' + '.'this.options[this.selectedIndex].value + \'';
- if ($this->pager->_append) {
- $href = '?' . $this->pager->_http_build_query_wrapper($this->pager->_linkData);
- $href = htmlentities($this->pager->_url). preg_replace(
- '/(&|&|\?)('.$this->pager->_urlVar.'=)(\d+)/',
- '\\1\\2'.$selector,
- htmlentities($href)
- );
- } else {
- $href = htmlentities($this->pager->_url . str_replace('%d', $selector, $this->pager->_fileName));
- }
- $tmp .= ' onchange="document.location.href=\''
- . $href .'\''
- . '"';
- } elseif ($this->pager->_httpMethod == 'POST') {
- $tmp .= " onchange='"
- . $this->pager->_generateFormOnClick($this->pager->_url, $this->pager->_linkData)
- . "'";
- $tmp = preg_replace(
- '/(input\.name = \"'.$this->pager->_urlVar.'\"; input\.value =) \"(\d+)\";/',
- '\\1 this.options[this.selectedIndex].value;',
- $tmp
- );
- }
- }
- $tmp .= '>';
- $start = 1;
- $end = $this->pager->numPages();
- $selected = $this->pager->getCurrentPageID();
- for ($i=$start; $i<=$end; $i++) {
- $tmp .= '<option value="'.$i.'"';
- if ($i == $selected) {
- $tmp .= ' selected="selected"';
- }
- $tmp .= '>'.sprintf($optionText, $i).'</option>';
- }
- $tmp .= '</select>';
- return $tmp;
- }
-
- // }}}
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * Contains the Pager_Jumping class
- *
- * PHP versions 4 and 5
- *
- * LICENSE: Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE FREEBSD PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * @category HTML
- * @package Pager
- * @author Lorenzo Alberton <l.alberton@quipo.it>
- * @author Richard Heyes <richard@phpguru.org>
- * @copyright 2003-2008 Lorenzo Alberton, Richard Heyes
- * @license http://www.debian.org/misc/bsd.license BSD License (3 Clause)
- * @version CVS: $Id: Jumping.php,v 1.1.1.1 2008/04/28 15:20:46 jamie Exp $
- * @link http://pear.php.net/package/Pager
- */
-
-/**
- * require PEAR::Pager_Common base class
- */
-require_once 'Pager/Common.php';
-
-/**
- * Pager_Jumping - Generic data paging class ("jumping window" style)
- * Handles paging a set of data. For usage see the example.php provided.
- *
- * @category HTML
- * @package Pager
- * @author Lorenzo Alberton <l.alberton@quipo.it>
- * @author Richard Heyes <richard@phpguru.org>
- * @copyright 2003-2008 Lorenzo Alberton, Richard Heyes
- * @license http://www.debian.org/misc/bsd.license BSD License (3 Clause)
- * @link http://pear.php.net/package/Pager
- */
-class Pager_Jumping extends Pager_Common
-{
- // {{{ Pager_Jumping()
-
- /**
- * Constructor
- *
- * @param array $options Associative array of option names and their values
- *
- * @access public
- */
- function Pager_Jumping($options = array())
- {
- $err = $this->setOptions($options);
- if ($err !== PAGER_OK) {
- return $this->raiseError($this->errorMessage($err), $err);
- }
- $this->build();
- }
-
- // }}}
- // {{{ getPageIdByOffset()
-
- /**
- * Returns pageID for given offset
- *
- * @param integer $index Offset to get pageID for
- *
- * @return int PageID for given offset
- */
- function getPageIdByOffset($index)
- {
- if (!isset($this->_pageData)) {
- $this->_generatePageData();
- }
-
- if (($index % $this->_perPage) > 0) {
- $pageID = ceil((float)$index / (float)$this->_perPage);
- } else {
- $pageID = $index / $this->_perPage;
- }
- return $pageID;
- }
-
- // }}}
- // {{{ getPageRangeByPageId()
-
- /**
- * Given a PageId, it returns the limits of the range of pages displayed.
- * While getOffsetByPageId() returns the offset of the data within the
- * current page, this method returns the offsets of the page numbers interval.
- * E.g., if you have pageId=3 and delta=10, it will return (1, 10).
- * PageID of 8 would give you (1, 10) as well, because 1 <= 8 <= 10.
- * PageID of 11 would give you (11, 20).
- * If the method is called without parameter, pageID is set to currentPage#.
- *
- * @param integer $pageid PageID to get offsets for
- *
- * @return array First and last offsets
- * @access public
- */
- function getPageRangeByPageId($pageid = null)
- {
- $pageid = isset($pageid) ? (int)$pageid : $this->_currentPage;
- if (isset($this->_pageData[$pageid]) || is_null($this->_itemData)) {
- // I'm sure I'm missing something here, but this formula works
- // so I'm using it until I find something simpler.
- $start = ((($pageid + (($this->_delta - ($pageid % $this->_delta))) % $this->_delta) / $this->_delta) - 1) * $this->_delta +1;
- return array(
- max($start, 1),
- min($start+$this->_delta-1, $this->_totalPages)
- );
- } else {
- return array(0, 0);
- }
- }
-
- // }}}
- // {{{ getLinks()
-
- /**
- * Returns back/next/first/last and page links,
- * both as ordered and associative array.
- *
- * NB: in original PEAR::Pager this method accepted two parameters,
- * $back_html and $next_html. Now the only parameter accepted is
- * an integer ($pageID), since the html text for prev/next links can
- * be set in the constructor. If a second parameter is provided, then
- * the method act as it previously did. This hack's only purpose is to
- * mantain backward compatibility.
- *
- * @param integer $pageID Optional pageID. If specified, links for that
- * page are provided instead of current one.
- * [ADDED IN NEW PAGER VERSION]
- * @param string $next_html HTML to put inside the next link
- * [deprecated: use the factory instead]
- *
- * @return array Back/pages/next links
- */
- function getLinks($pageID=null, $next_html='')
- {
- //BC hack
- if (!empty($next_html)) {
- $back_html = $pageID;
- $pageID = null;
- } else {
- $back_html = '';
- }
-
- if (!is_null($pageID)) {
- $this->links = '';
- if ($this->_totalPages > $this->_delta) {
- $this->links .= $this->_printFirstPage();
- }
-
- $_sav = $this->_currentPage;
- $this->_currentPage = $pageID;
-
- $this->links .= $this->_getBackLink('', $back_html);
- $this->links .= $this->_getPageLinks();
- $this->links .= $this->_getNextLink('', $next_html);
- if ($this->_totalPages > $this->_delta) {
- $this->links .= $this->_printLastPage();
- }
- }
-
- $back = str_replace(' ', '', $this->_getBackLink());
- $next = str_replace(' ', '', $this->_getNextLink());
- $pages = $this->_getPageLinks();
- $first = $this->_printFirstPage();
- $last = $this->_printLastPage();
- $all = $this->links;
- $linkTags = $this->linkTags;
- $linkTagsRaw = $this->linkTagsRaw;
-
- if (!is_null($pageID)) {
- $this->_currentPage = $_sav;
- }
-
- return array(
- $back,
- $pages,
- trim($next),
- $first,
- $last,
- $all,
- $linkTags,
- 'back' => $back,
- 'pages' => $pages,
- 'next' => $next,
- 'first' => $first,
- 'last' => $last,
- 'all' => $all,
- 'linktags' => $linkTags,
- 'linkTagsRaw' => linkTagsRaw,
- );
- }
-
- // }}}
- // {{{ _getPageLinks()
-
- /**
- * Returns pages link
- *
- * @param string $url URL to use in the link
- * [deprecated: use the constructor instead]
- *
- * @return string Links
- * @access private
- */
- function _getPageLinks($url = '')
- {
- //legacy setting... the preferred way to set an option now
- //is adding it to the constuctor
- if (!empty($url)) {
- $this->_path = $url;
- }
-
- //If there's only one page, don't display links
- if ($this->_clearIfVoid && ($this->_totalPages < 2)) {
- return '';
- }
-
- $links = '';
- $limits = $this->getPageRangeByPageId($this->_currentPage);
-
- for ($i=$limits[0]; $i<=min($limits[1], $this->_totalPages); $i++) {
- if ($i != $this->_currentPage) {
- $this->range[$i] = false;
- $this->_linkData[$this->_urlVar] = $i;
- $links .= $this->_renderLink(str_replace('%d', $i, $this->_altPage), $i);
- } else {
- $this->range[$i] = true;
- $links .= $this->_curPageSpanPre . $i . $this->_curPageSpanPost;
- }
- $links .= $this->_spacesBefore
- . (($i != $this->_totalPages) ? $this->_separator.$this->_spacesAfter : '');
- }
- return $links;
- }
-
- // }}}
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * Contains the Pager class
- *
- * PHP versions 4 and 5
- *
- * LICENSE: Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE FREEBSD PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * @category HTML
- * @package Pager
- * @author Lorenzo Alberton <l.alberton@quipo.it>
- * @author Richard Heyes <richard@phpguru.org>
- * @copyright 2003-2008 Lorenzo Alberton, Richard Heyes
- * @license http://www.debian.org/misc/bsd.license BSD License (3 Clause)
- * @version CVS: $Id: Pager.php,v 1.1.1.1 2008/04/28 15:20:46 jamie Exp $
- * @link http://pear.php.net/package/Pager
- */
-
-/**
- * Pager - Wrapper class for [Sliding|Jumping]-window Pager
- * Usage examples can be found in the PEAR manual
- *
- * @category HTML
- * @package Pager
- * @author Lorenzo Alberton <l.alberton@quipo.it>
- * @author Richard Heyes <richard@phpguru.org>
- * @copyright 2003-2008 Lorenzo Alberton, Richard Heyes
- * @license http://www.debian.org/misc/bsd.license BSD License (3 Clause)
- * @link http://pear.php.net/package/Pager
- */
-class Pager
-{
- // {{{ Pager()
-
- /**
- * Constructor
- *
- * -------------------------------------------------------------------------
- * VALID options are (default values are set some lines before):
- * - mode (string): "Jumping" or "Sliding" -window - It determines
- * pager behaviour. See the manual for more details
- * - totalItems (int): # of items to page.
- * - perPage (int): # of items per page.
- * - delta (int): # of page #s to show before and after the current
- * one
- * - linkClass (string): name of CSS class used for link styling.
- * - append (bool): if true pageID is appended as GET value to the
- * URL - if false it is embedded in the URL
- * according to "fileName" specs
- * - httpMethod (string): Specifies the HTTP method to use. Valid values
- * are 'GET' or 'POST'
- * according to "fileName" specs
- * - importQuery (bool): if true (default behaviour), variables and
- * values are imported from the submitted data
- * (query string) and used in the generated links
- * otherwise they're ignored completely
- * - path (string): complete path to the page (without the page name)
- * - fileName (string): name of the page, with a %d if append=true
- * - urlVar (string): name of pageNumber URL var, for example "pageID"
- * - altPrev (string): alt text to display for prev page, on prev link.
- * - altNext (string): alt text to display for next page, on next link.
- * - altPage (string): alt text to display before the page number.
- * - prevImg (string): sth (it can be text such as "<< PREV" or an
- * <img/> as well...) to display instead of "<<".
- * - nextImg (string): same as prevImg, used for NEXT link, instead of
- * the default value, which is ">>".
- * - separator (string): what to use to separate numbers (can be an
- * <img/>, a comma, an hyphen, or whatever.
- * - spacesBeforeSeparator
- * (int): number of spaces before the separator.
- * - firstPagePre (string):
- * string used before first page number (can be an
- * <img/>, a "{", an empty string, or whatever.
- * - firstPageText (string):
- * string used in place of first page number
- * - firstPagePost (string):
- * string used after first page number (can be an
- * <img/>, a "}", an empty string, or whatever.
- * - lastPagePre (string):
- * similar to firstPagePre.
- * - lastPageText (string):
- * similar to firstPageText.
- * - lastPagePost (string):
- * similar to firstPagePost.
- * - spacesAfterSeparator
- * (int): number of spaces after the separator.
- * - firstLinkTitle (string):
- * string used as title in <link rel="first"> tag
- * - lastLinkTitle (string):
- * string used as title in <link rel="last"> tag
- * - prevLinkTitle (string):
- * string used as title in <link rel="prev"> tag
- * - nextLinkTitle (string):
- * string used as title in <link rel="next"> tag
- * - curPageLinkClassName
- * (string): name of CSS class used for current page link.
- * - clearIfVoid(bool): if there's only one page, don't display pager.
- * - extraVars (array): additional URL vars to be added to the querystring
- * - excludeVars (array): URL vars to be excluded in the querystring
- * - itemData (array): array of items to page.
- * - useSessions (bool): if true, number of items to display per page is
- * stored in the $_SESSION[$_sessionVar] var.
- * - closeSession (bool): if true, the session is closed just after R/W.
- * - sessionVar (string): name of the session var for perPage value.
- * A value != from default can be useful when
- * using more than one Pager istance in the page.
- * - pearErrorMode (constant):
- * PEAR_ERROR mode for raiseError().
- * Default is PEAR_ERROR_RETURN.
- * -------------------------------------------------------------------------
- * REQUIRED options are:
- * - fileName IF append==false (default is true)
- * - itemData OR totalItems (if itemData is set, totalItems is overwritten)
- * -------------------------------------------------------------------------
- *
- * @param mixed $options Associative array of option names and their values
- *
- * @access public
- */
- function Pager($options = array())
- {
- //this check evaluates to true on 5.0.0RC-dev,
- //so i'm using another one, for now...
- //if (version_compare(phpversion(), '5.0.0') == -1) {
- if (get_class($this) == 'pager') { //php4 lowers class names
- // assign factoried method to this for PHP 4
- eval('$this = Pager::factory($options);');
- } else { //php5 is case sensitive
- $msg = 'Pager constructor is deprecated.'
- .' You must use the "Pager::factory($params)" method'
- .' instead of "new Pager($params)"';
- trigger_error($msg, E_USER_ERROR);
- }
- }
-
- // }}}
- // {{{ factory()
-
- /**
- * Return a pager based on $mode and $options
- *
- * @param array $options Optional parameters for the storage class
- *
- * @return object Storage object
- * @static
- * @access public
- */
- function &factory($options = array())
- {
- $mode = (isset($options['mode']) ? ucfirst($options['mode']) : 'Jumping');
- $classname = 'Pager_' . $mode;
- $classfile = 'Pager' . DIRECTORY_SEPARATOR . $mode . '.php';
-
- // Attempt to include a custom version of the named class, but don't treat
- // a failure as fatal. The caller may have already included their own
- // version of the named class.
- if (!class_exists($classname)) {
- include_once $classfile;
- }
-
- // If the class exists, return a new instance of it.
- if (class_exists($classname)) {
- $pager = new $classname($options);
- return $pager;
- }
-
- $null = null;
- return $null;
- }
-
- // }}}
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/**
- * Dummy file, used to maintain backward compatibility.
- * The real file was moved to the PEAR root directory
- *
- * PHP versions 4 and 5
- *
- * @category HTML
- * @package Pager
- * @author Lorenzo Alberton <l.alberton@quipo.it>
- * @author Richard Heyes <richard@phpguru.org>
- * @copyright 2003-2007 Lorenzo Alberton, Richard Heyes
- * @license http://www.debian.org/misc/bsd.license BSD License (3 Clause)
- * @version CVS: $Id: Pager_savebc.php,v 1.1.1.1 2008/04/28 15:20:46 jamie Exp $
- * @link http://pear.php.net/package/Pager
- */
-
-require_once 'Pager.php';
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * Contains the Pager_Sliding class
- *
- * PHP versions 4 and 5
- *
- * LICENSE: Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE FREEBSD PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * @category HTML
- * @package Pager
- * @author Lorenzo Alberton <l.alberton@quipo.it>
- * @copyright 2003-2008 Lorenzo Alberton
- * @license http://www.debian.org/misc/bsd.license BSD License (3 Clause)
- * @version CVS: $Id: Sliding.php,v 1.1.1.1 2008/04/28 15:20:46 jamie Exp $
- * @link http://pear.php.net/package/Pager
- */
-
-/**
- * require PEAR::Pager_Common base class
- */
-require_once 'Pager/Common.php';
-
-/**
- * Pager_Sliding - Generic data paging class ("sliding window" style)
- * Usage examples can be found in the PEAR manual
- *
- * @category HTML
- * @package Pager
- * @author Lorenzo Alberton <l.alberton@quipo.it>
- * @copyright 2003-2008 Lorenzo Alberton
- * @license http://www.debian.org/misc/bsd.license BSD License (3 Clause)
- * @link http://pear.php.net/package/Pager
- */
-class Pager_Sliding extends Pager_Common
-{
- // {{{ Pager_Sliding()
-
- /**
- * Constructor
- *
- * @param array $options Associative array of option names and their values
- *
- * @access public
- */
- function Pager_Sliding($options = array())
- {
- //set default Pager_Sliding options
- $this->_delta = 2;
- $this->_prevImg = '«';
- $this->_nextImg = '»';
- $this->_separator = '|';
- $this->_spacesBeforeSeparator = 3;
- $this->_spacesAfterSeparator = 3;
- $this->_curPageSpanPre = '<b>';
- $this->_curPageSpanPost = '</b>';
-
- //set custom options
- $err = $this->setOptions($options);
- if ($err !== PAGER_OK) {
- return $this->raiseError($this->errorMessage($err), $err);
- }
- $this->build();
- }
-
- // }}}
- // {{{ getPageIdByOffset()
-
- /**
- * "Overload" PEAR::Pager method. VOID. Not needed here...
- *
- * @param integer $index Offset to get pageID for
- *
- * @return void
- * @deprecated
- * @access public
- */
- function getPageIdByOffset($index)
- {
- }
-
- // }}}
- // {{{ getPageRangeByPageId()
-
- /**
- * Given a PageId, it returns the limits of the range of pages displayed.
- * While getOffsetByPageId() returns the offset of the data within the
- * current page, this method returns the offsets of the page numbers interval.
- * E.g., if you have pageId=5 and delta=2, it will return (3, 7).
- * PageID of 9 would give you (4, 8).
- * If the method is called without parameter, pageID is set to currentPage#.
- *
- * @param integer $pageid PageID to get offsets for
- *
- * @return array First and last offsets
- * @access public
- */
- function getPageRangeByPageId($pageid = null)
- {
- $pageid = isset($pageid) ? (int)$pageid : $this->_currentPage;
- if (!isset($this->_pageData)) {
- $this->_generatePageData();
- }
- if (isset($this->_pageData[$pageid]) || is_null($this->_itemData)) {
- if ($this->_expanded) {
- $min_surplus = ($pageid <= $this->_delta) ? ($this->_delta - $pageid + 1) : 0;
- $max_surplus = ($pageid >= ($this->_totalPages - $this->_delta)) ?
- ($pageid - ($this->_totalPages - $this->_delta)) : 0;
- } else {
- $min_surplus = $max_surplus = 0;
- }
- return array(
- max($pageid - $this->_delta - $max_surplus, 1),
- min($pageid + $this->_delta + $min_surplus, $this->_totalPages)
- );
- }
- return array(0, 0);
- }
-
- // }}}
- // {{{ getLinks()
-
- /**
- * Returns back/next/first/last and page links,
- * both as ordered and associative array.
- *
- * @param integer $pageID Optional pageID. If specified, links for that page
- * are provided instead of current one.
- * @param string $dummy used to comply with parent signature (leave empty)
- *
- * @return array back/pages/next/first/last/all links
- * @access public
- */
- function getLinks($pageID = null, $dummy='')
- {
- if (!is_null($pageID)) {
- $_sav = $this->_currentPage;
- $this->_currentPage = $pageID;
-
- $this->links = '';
- if ($this->_totalPages > (2 * $this->_delta + 1)) {
- $this->links .= $this->_printFirstPage();
- }
- $this->links .= $this->_getBackLink();
- $this->links .= $this->_getPageLinks();
- $this->links .= $this->_getNextLink();
- if ($this->_totalPages > (2 * $this->_delta + 1)) {
- $this->links .= $this->_printLastPage();
- }
- }
-
- $back = str_replace(' ', '', $this->_getBackLink());
- $next = str_replace(' ', '', $this->_getNextLink());
- $pages = $this->_getPageLinks();
- $first = $this->_printFirstPage();
- $last = $this->_printLastPage();
- $all = $this->links;
- $linkTags = $this->linkTags;
- $linkTagsRaw = $this->linkTagsRaw;
-
- if (!is_null($pageID)) {
- $this->_currentPage = $_sav;
- }
-
- return array(
- $back,
- $pages,
- trim($next),
- $first,
- $last,
- $all,
- $linkTags,
- 'back' => $back,
- 'pages' => $pages,
- 'next' => $next,
- 'first' => $first,
- 'last' => $last,
- 'all' => $all,
- 'linktags' => $linkTags,
- 'linkTagsRaw' => $linkTagsRaw,
- );
- }
-
- // }}}
- // {{{ _getPageLinks()
-
- /**
- * Returns pages link
- *
- * @param string $url URL string [deprecated]
- *
- * @return string Links
- * @access private
- */
- function _getPageLinks($url = '')
- {
- //legacy setting... the preferred way to set an option now
- //is adding it to the constuctor
- if (!empty($url)) {
- $this->_path = $url;
- }
-
- //If there's only one page, don't display links
- if ($this->_clearIfVoid && ($this->_totalPages < 2)) {
- return '';
- }
-
- $links = '';
- if ($this->_totalPages > (2 * $this->_delta + 1)) {
- if ($this->_expanded) {
- if (($this->_totalPages - $this->_delta) <= $this->_currentPage) {
- $expansion_before = $this->_currentPage - ($this->_totalPages - $this->_delta);
- } else {
- $expansion_before = 0;
- }
- for ($i = $this->_currentPage - $this->_delta - $expansion_before; $expansion_before; $expansion_before--, $i++) {
- $print_separator_flag = ($i != $this->_currentPage + $this->_delta); // && ($i != $this->_totalPages - 1)
-
- $this->range[$i] = false;
- $this->_linkData[$this->_urlVar] = $i;
- $links .= $this->_renderLink(str_replace('%d', $i, $this->_altPage), $i)
- . $this->_spacesBefore
- . ($print_separator_flag ? $this->_separator.$this->_spacesAfter : '');
- }
- }
-
- $expansion_after = 0;
- for ($i = $this->_currentPage - $this->_delta; ($i <= $this->_currentPage + $this->_delta) && ($i <= $this->_totalPages); $i++) {
- if ($i < 1) {
- ++$expansion_after;
- continue;
- }
-
- // check when to print separator
- $print_separator_flag = (($i != $this->_currentPage + $this->_delta) && ($i != $this->_totalPages));
-
- if ($i == $this->_currentPage) {
- $this->range[$i] = true;
- $links .= $this->_curPageSpanPre . $i . $this->_curPageSpanPost;
- } else {
- $this->range[$i] = false;
- $this->_linkData[$this->_urlVar] = $i;
- $links .= $this->_renderLink(str_replace('%d', $i, $this->_altPage), $i);
- }
- $links .= $this->_spacesBefore
- . ($print_separator_flag ? $this->_separator.$this->_spacesAfter : '');
- }
-
- if ($this->_expanded && $expansion_after) {
- $links .= $this->_separator . $this->_spacesAfter;
- for ($i = $this->_currentPage + $this->_delta +1; $expansion_after; $expansion_after--, $i++) {
- $print_separator_flag = ($expansion_after != 1);
- $this->range[$i] = false;
- $this->_linkData[$this->_urlVar] = $i;
- $links .= $this->_renderLink(str_replace('%d', $i, $this->_altPage), $i)
- . $this->_spacesBefore
- . ($print_separator_flag ? $this->_separator.$this->_spacesAfter : '');
- }
- }
-
- } else {
- //if $this->_totalPages <= (2*Delta+1) show them all
- for ($i=1; $i<=$this->_totalPages; $i++) {
- if ($i != $this->_currentPage) {
- $this->range[$i] = false;
- $this->_linkData[$this->_urlVar] = $i;
- $links .= $this->_renderLink(str_replace('%d', $i, $this->_altPage), $i);
- } else {
- $this->range[$i] = true;
- $links .= $this->_curPageSpanPre . $i . $this->_curPageSpanPost;
- }
- $links .= $this->_spacesBefore
- . (($i != $this->_totalPages) ? $this->_separator.$this->_spacesAfter : '');
- }
- }
- return $links;
- }
-
- // }}}
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * A framework for authentication and authorization in PHP applications
- *
- * LiveUser_Admin is meant to be used with the LiveUser package.
- * It is composed of all the classes necessary to administrate
- * data used by LiveUser.
- *
- * You'll be able to add/edit/delete/get things like:
- * * Rights
- * * Users
- * * Groups
- * * Areas
- * * Applications
- * * Subgroups
- * * ImpliedRights
- *
- * And all other entities within LiveUser.
- *
- * At the moment we support the following storage containers:
- * * DB
- * * MDB
- * * MDB2
- *
- * But it takes no time to write up your own storage container,
- * so if you like to use native mysql functions straight, then it's possible
- * to do so in under a hour!
- *
- * PHP version 4 and 5
- *
- * LICENSE: This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library 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
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
- * MA 02111-1307 USA
- *
- *
- * @category authentication
- * @package LiveUser_Admin
- * @author Markus Wolff <wolff@21st.de>
- * @author Helgi Þormar Þorbjörnsson <dufuz@php.net>
- * @author Lukas Smith <smith@pooteeweet.org>
- * @author Arnaud Limbourg <arnaud@php.net>
- * @author Christian Dickmann <dickmann@php.net>
- * @author Matt Scifo <mscifo@php.net>
- * @author Bjoern Kraus <krausbn@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version CVS: $Id: Complex.php,v 1.1.1.1 2008/04/28 15:20:46 jamie Exp $
- * @link http://pear.php.net/LiveUser_Admin
- */
-
-/**
- * Require the parent class definition
- */
-require_once 'LiveUser/Admin/Perm/Medium.php';
-
-/**
- * Complex permission administration class that extends the Medium class with the
- * ability to manage subgroups, implied rights and area admins
- *
- * This class provides a set of functions for implementing a user
- * permission management system on live websites. All authorisation
- * backends/containers must be extensions of this base class.
- *
- * @category authentication
- * @package LiveUser_Admin
- * @author Christian Dickmann <dickmann@php.net>
- * @author Markus Wolff <wolff@21st.de>
- * @author Matt Scifo <mscifo@php.net>
- * @author Helgi �rmar �rbj�nsson <dufuz@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version Release: @package_version@
- * @link http://pear.php.net/LiveUser_Admin
- */
-class LiveUser_Admin_Perm_Complex extends LiveUser_Admin_Perm_Medium
-{
- /**
- * Constructor
- *
- * @return void
- *
- * @access protected
- */
- function LiveUser_Admin_Perm_Complex()
- {
- $this->LiveUser_Admin_Perm_Medium();
- $this->selectable_tables['getRights'][] = 'right_implied';
- $this->selectable_tables['getAreas'][] = 'area_admin_areas';
- $this->selectable_tables['getGroups'][] = 'group_subgroups';
- }
-
- /**
- * Assign subgroup to parent group.
- *
- * First checks if groupId and subgroupId are the same then if
- * the child group is already assigned to the parent group and last if
- * the child group does have a parent group already assigned to it.
- * (Just to difference between what kinda error was hit)
- *
- * If so it returns false and pushes the error into stack.
- *
- * The expected parameter array is of the form
- * <code>
- * $lua->perm->assignSubGroup(
- * array('group_id' => 'id', 'subgroup_id' => 'id')
- * );
- * </code>
- *
- * @param array containing the subgroup_id and group_id
- * @return bool false on error, true on success
- *
- * @access public
- */
- function assignSubGroup($data)
- {
- // Checking if the supplied data is valid:
- // you can't assign a group as it's own subgroup
- if ($data['subgroup_id'] == $data['group_id']) {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR, 'exception',
- array('msg' => 'Parent group id is the same as the subgroup id')
- );
- return false;
- }
-
- // Check if the group is already assigned to this group (retrieve the group_id).
- // It also checks if the group exists (if not: return false).
- $filter = array('subgroup_id' => $data['subgroup_id']);
- $result = $this->_storage->selectCount('group_subgroups', 'group_id', $filter);
- if ($result === false) {
- return false;
- }
-
- // Do the actual check
- if ($result == $data['group_id']) {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR, 'exception',
- array('msg' => 'This child group is already a Parent of this group')
- );
- return false;
- }
-
- // Assign the group as a subgroup.
- $result = $this->_storage->insert('group_subgroups', $data);
- // todo: notify observer
- return $result;
- }
-
- /**
- * Unassign subgroup(s) from group(s)
- *
- * @param array key values pairs (value may be a string or an array)
- * This will construct the WHERE clause of your update
- * Be careful, if you leave this blank no WHERE clause
- * will be used and all groups will be affected by the remove
- * @return int|bool false on error, the affected rows on success
- *
- * @access public
- */
- function unassignSubGroup($filters)
- {
- // Perform a delete on the group_subgroups table (no data sanity checks required).
- $result = $this->_storage->delete('group_subgroups', $filters);
- // todo: notify observer
- return $result;
- }
-
- /**
- * Imply Right
- *
- * @param array containing the implied_right_id and right_id
- * @return bool false on error, true on success
- *
- * @access public
- */
- function implyRight($data)
- {
- // Check if the implied_right_id is the same as the right_id (you can't imply itself)
- if (array_key_exists('right_id', $data)
- && array_key_exists('implied_right_id', $data)
- && $data['implied_right_id'] == $data['right_id']
- ) {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR, 'exception',
- array('msg' => 'Right id is the same as the implied right id')
- );
- return false;
- }
-
- // Prepare the params for a check on the implied_right existing and already being implied
- $params = array(
- 'fields' => array(
- 'right_id'
- ),
- 'filters' => array(
- 'implied_right_id' => $data['implied_right_id'],
- 'right_id' => $data['right_id']
- )
- );
-
- $result = $this->_getImpliedRight($params);
- if ($result === false) {
- return false;
- }
-
- // Check if the implied right is already implied
- if (!empty($result)) {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR, 'exception',
- array('msg' => 'This implied right is already implied from this right')
- );
- return false;
- }
-
- // It all checks out, imply the right. It something goes wrong with the insert return false.
- $result = $this->_storage->insert('right_implied', $data);
- if ($result === false) {
- return false;
- }
-
- // Update the implied status of this right, the has_implied column in the database should now report 1
- $filter = array('right_id' => $data['right_id']);
- $this->_updateImpliedStatus($filter);
-
- // todo: notify observer
- return $result;
- }
-
- /**
- * Unimply right(s)
- *
- * @param array key values pairs (value may be a string or an array)
- * This will construct the WHERE clause of your update
- * Be careful, if you leave this blank no WHERE clause
- * will be used and all groups will be affected by the remove
- * @param bool determines if the implied rights field in the rights table
- * should be updated or not
- * @return int|bool false on error, the affected rows on success
- *
- * @access public
- */
- function unimplyRight($filters, $update = true)
- {
- // Generate the implied_filters. If an error occures, return it (being 0 or false).
- $implied_filters = $this->_makeRemoveFilter($filters, 'implied_right_id', 'getRights');
- if (!$implied_filters) {
- return $implied_filters;
- }
-
- if ($update) {
- // Generate the rights_filter for updating the has_implied column in the rights table
- $right_filters = $this->_makeRemoveFilter($filters, 'right_id', 'getRights');
- if (!$right_filters) {
- return $right_filters;
- }
- }
-
- // Unimply the right (perform a delete on the right_implied table) based on the implied_filters
- $result = $this->_storage->delete('right_implied', $implied_filters);
- if ($result === false) {
- return false;
- }
-
- if ($update) {
- // Update the has_implied status in the rights table, based on the right_filters
- $this->_updateImpliedStatus($right_filters);
- }
-
- // todo: notify observer
- return $result;
- }
-
- /**
- * Add Area Admin
- *
- * @param array containing the area_id and perm_user_id
- * @return bool false on error, true on success
- *
- * @access public
- */
- function addAreaAdmin($data)
- {
- // needs more sanity checking, check if the perm_id is really perm_type 3 and so on
- // make sure when removing rights or updating them that if the user goes down
- // below perm_type 3 that a entry from area_admin_areas is removed
-
- // Prepare the params for retrieving the userinfo (checking if the user actually exists).
- $params = array(
- 'fields' => array(
- 'perm_type'
- ),
- 'filters' => array(
- 'perm_user_id' => $data['perm_user_id']
- ),
- 'select' => 'one',
- );
-
- $result = parent::getUsers($params);
- if ($result === false) {
- return false;
- }
-
- // Check if the user has sufficient rights to become an area admin
- if (!$result || $result < 3) {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR, 'exception',
- array('msg' => 'The user doesn\'t exist or does not have perm_type >= 3')
- );
- return false;
- }
-
- // Make the user area admin for this area.
- $result = $this->_storage->insert('area_admin_areas', $data);
-
- // todo: notify observer
- return $result;
- }
-
- /**
- * Remove Area Admin(s)
- *
- * @param array key values pairs (value may be a string or an array)
- * This will construct the WHERE clause of your update
- * Be careful, if you leave this blank no WHERE clause
- * will be used and all groups will be affected by the remove
- * @return int|bool false on error, the affected rows on success
- *
- * @access public
- */
- function removeAreaAdmin($filters)
- {
- // Delete the user from the area_admin_areas table based on the filters provided.
- $result = $this->_storage->delete('area_admin_areas', $filters);
- if ($result === false) {
- return false;
- }
-
- // todo: notify observer
- return $result;
- }
-
- /**
- * Remove areas and all their relevant relations
- *
- * @param array key values pairs (value may be a string or an array)
- * This will construct the WHERE clause of your update
- * Be careful, if you leave this blank no WHERE clause
- * will be used and all areas will be affected by the remove
- * @return int|bool false on error, the affected rows on success
- *
- * @access public
- */
- function removeArea($filters)
- {
- // Generate the remove filters, return 0 or false immediatly
- $filters = $this->_makeRemoveFilter($filters, 'area_id', 'getAreas');
- if (!$filters) {
- return $filters;
- }
-
- // Remove the area admin (leave no mess behind in the tables) using the filters (containing only the area_id).
- $result = $this->removeAreaAdmin($filters);
- if ($result === false) {
- return false;
- }
-
- // Remove the area using the Perm:Simple container.
- $result = parent::removeArea($filters);
-
- // todo: notify observer
- return $result;
- }
-
- /**
- * Remove rights and all their relevant relations
- *
- * @param array key values pairs (value may be a string or an array)
- * This will construct the WHERE clause of your update
- * Be careful, if you leave this blank no WHERE clause
- * will be used and all rights will be affected by the remove
- * @return int|bool false on error, the affected rows on success
- *
- * @access public
- */
- function removeRight($filters)
- {
- // First take care of any mess which may possibly be left behind (the implied_rights table).
- $result = $this->unimplyRight($filters, false);
- if ($result === false) {
- return false;
- }
-
- // Remove the right.
- $result = parent::removeRight($filters);
- if ($result === false) {
- return false;
- }
-
- // Update the has_implied status (clean up the database so no invalid information is left behind).
- $this->_updateImpliedStatus($filters);
-
- // todo: notify observer
- return $result;
- }
-
- /**
- * Get SubGroups
- *
- * @param array containing key-value pairs for:
- * 'fields' - ordered array containing the fields to fetch
- * if empty all fields from the user table are fetched
- * 'filters' - key values pairs (value may be a string or an array)
- * 'orders' - key value pairs (values 'ASC' or 'DESC')
- * 'rekey' - if set to true, returned array will have the
- * first column as its first dimension
- * 'group' - if set to true and $rekey is set to true, then
- * all values with the same first column will be
- * wrapped in an array
- * 'limit' - number of rows to select
- * 'offset' - first row to select
- * 'select' - determines what query method to use:
- * 'one' -> queryOne, 'row' -> queryRow,
- * 'col' -> queryCol, 'all' ->queryAll (default)
- * @return bool|array false on failure or array with selected data
- *
- * @access private
- */
- function _getSubGroups($params = array())
- {
- // Define the tables which can be included the the query and define the root table.
- $selectable_tables = array('group_subgroups');
- $root_table = 'group_subgroups';
-
- $data = $this->_makeGet($params, $root_table, $selectable_tables);
- return $data;
- }
-
- /**
- * Get Implied Rights
- *
- * @param array containing key-value pairs for:
- * 'fields' - ordered array containing the fields to fetch
- * if empty all fields from the user table are fetched
- * 'filters' - key values pairs (value may be a string or an array)
- * 'orders' - key value pairs (values 'ASC' or 'DESC')
- * 'rekey' - if set to true, returned array will have the
- * first column as its first dimension
- * 'group' - if set to true and $rekey is set to true, then
- * all values with the same first column will be
- * wrapped in an array
- * 'limit' - number of rows to select
- * 'offset' - first row to select
- * 'select' - determines what query method to use:
- * 'one' -> queryOne, 'row' -> queryRow,
- * 'col' -> queryCol, 'all' ->queryAll (default)
- * @return bool|array false on failure or array with selected data
- *
- * @access private
- */
- function _getImpliedRight($params = array())
- {
- // Define the tables which can be included the the query and define the root table.
- $selectable_tables = array('right_implied');
- $root_table = 'right_implied';
-
- $data = $this->_makeGet($params, $root_table, $selectable_tables);
- return $data;
- }
-
- /**
- * Remove groups and all their relevant relations
- *
- * @param array key values pairs (value may be a string or an array)
- * This will construct the WHERE clause of your update
- * Be careful, if you leave this blank no WHERE clause
- * will be used and all groups will be affected by the removed
- * @return int|bool false on error, the affected rows on success
- *
- * @access public
- */
- function removeGroup($filters)
- {
- // If recursive is set, prepare a params array, get the subgroups and if there are any
- // do a recursive call (again providing the recursive param, in case there are more subgroups).
- if (array_key_exists('recursive', $filters)) {
- $param = array(
- 'fields' => array(
- 'subgroup_id'
- ),
- 'filters' => array(
- 'group_id' => $filters['group_id']
- )
- );
- $result = $this->_getSubGroups($param);
- if ($result === false) {
- return false;
- }
-
- // Loop through the available subgroups and remove them.
- foreach ($result as $subGroupId) {
- $filter = array('group_id' => $subGroupId['subgroup_id'], 'recursive' => true);
- $result = $this->removeGroup($filter);
- if ($result === false) {
- return false;
- }
- }
- unset($filters['recursive']);
- }
-
- // Unassign any subgroups that may have been assigned to this group. (clean up the database)
- $result = $this->unassignSubGroup($filters);
- if ($result === false) {
- return false;
- }
-
- // Remove the group using Perm:Medium.
- return parent::removeGroup($filters);
- }
-
- /**
- * Updates implied status
- *
- * @param array key values pairs (value may be a string or an array)
- * This will construct the WHERE clause of your update
- * Be careful, if you leave this blank no WHERE clause
- * will be used and all rights will be affected by the update
- * @return bool denotes success or failure
- *
- * @access private
- */
- function _updateImpliedStatus($filters)
- {
- // Prepare the params array for getting the rights which will be updated, based on the provided filters array.
- $params = array(
- 'fields' => array('right_id'),
- 'filters' => $filters,
- 'select' => 'col',
- );
-
- // Get the rights.
- $rights = $this->getRights($params);
- if ($rights === false) {
- return false;
- }
-
- // Prepare the filters for fetching the amount of rights.
- $filters = array('right_id' => $rights);
-
- // Count the rights which are included in the right_implied table.
- $count = $this->_storage->selectCount('right_implied', 'right_id', $filters);
- if ($count === false) {
- return false;
- }
-
- // Update the has_implied with true of false (if count has a value true, otherwise false)
- $data = array('has_implied' => (bool)$count);
-
- // Perform the update.
- $result = $this->updateRight($data, $filters);
- if ($result === false) {
- return false;
- }
-
- // todo: notify observer
- return $result;
- }
-
- /**
- * Get parent of a subgroup
- *
- * @param Id of the subgroup_id that is used to fetch the parent
- * @return bool|int false on failure or integer with the parent group_id
- *
- * @access public
- */
- function getParentGroup($subGroupId)
- {
- // Prepare the params array for the _getSubGroups().
- $params = array(
- 'fields' => array(
- 'group_id'
- ),
- 'filters' => array(
- 'subgroup_id' => $subGroupId
- ),
- 'select' => 'one'
- );
- $result = $this->_getSubGroups($params);
-
- return $result;
- }
-
- /**
- * Fetches groups
- *
- * @param array containing key-value pairs for:
- * 'fields' - ordered array containing the fields to fetch
- * if empty all fields from the user table are fetched
- * 'filters' - key values pairs (value may be a string or an array)
- * 'orders' - key value pairs (values 'ASC' or 'DESC')
- * 'rekey' - if set to true, returned array will have the
- * first column as its first dimension
- * 'group' - if set to true and $rekey is set to true, then
- * all values with the same first column will be
- * wrapped in an array
- * 'limit' - number of rows to select
- * 'offset' - first row to select
- * 'select' - determines what query method to use:
- * 'one' -> queryOne, 'row' -> queryRow,
- * 'col' -> queryCol, 'all' ->queryAll (default)
- * 'selectable_tables' - array list of tables that may be
- * joined to in this query, the first element is
- * the root table from which the joins are done
- * 'subgroups' - filter array if all subgroups should be
- fetched into a flat array
- * 'hierarchy' - filter array if all subgroups should be
- fetched into a nested array (overwrites 'subgroups')
- *
- * note that 'hierarchy' requires 'rekey' enabled, 'group' is disabled,
- * 'select' set to 'all' and the first field needs to be 'group_id'
- * @return bool|array false on failure or array with selected data
- *
- * @access public
- */
- function getGroups($params = array())
- {
- if (!array_key_exists('subgroups', $params)
- && !array_key_exists('hierarchy', $params)
- ) {
- // Don't have to deal with subgroups
- return parent::getGroups($params);
- }
-
- $params = LiveUser_Admin_Storage::setSelectDefaultParams($params);
-
- if (array_key_exists('hierarchy', $params)) {
- return $this->_getGroupsWithHierarchy($params);
- }
-
- return $this->_getGroupsWithSubgroups($params);
- }
-
- /**
- * Fetches groups with their subgroups into a flat structure
- *
- * @param array containing key-value pairs for:
- * 'fields' - ordered array containing the fields to fetch
- * if empty all fields from the user table are fetched
- * 'filters' - key values pairs (value may be a string or an array)
- * 'orders' - key value pairs (values 'ASC' or 'DESC')
- * 'rekey' - if set to true, returned array will have the
- * first column as its first dimension
- * 'group' - if set to true and $rekey is set to true, then
- * all values with the same first column will be
- * wrapped in an array
- * 'limit' - number of rows to select
- * 'offset' - first row to select
- * 'select' - determines what query method to use:
- * 'one' -> queryOne, 'row' -> queryRow,
- * 'col' -> queryCol, 'all' ->queryAll (default)
- * 'selectable_tables' - array list of tables that may be
- * joined to in this query, the first element is
- * the root table from which the joins are done
- * 'subgroups' - filter array if all subgroups should be
- fetched into a flat array
- * @return bool|array false on failure or array with selected data
- *
- * @access private
- */
- function _getGroupsWithSubgroups($params)
- {
- if ($params['select'] == 'one' || $params['select'] == 'row') {
- // Don't allow 'subgroups' with 'select' if 'one' or 'row'
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR, 'exception',
- array('msg' => 'Setting "subgroups" requires select to be set to "col" or "all"')
- );
- return false;
- }
-
- $subgroups = is_array($params['subgroups']) ? $params['subgroups'] : array();
-
- // Prepare the params for the getGroups call on Perm::Medium.
- $tmp_params = array(
- 'fields' => array('group_id'),
- 'select' => 'col',
- 'filters' => $subgroups,
- );
-
- $result = parent::getGroups($tmp_params);
- if (!$result) {
- return $result;
- }
-
- $subgroup_ids = $result;
-
- // Retrieve all the group_ids from all the subgroups in a do-while loop.
- do {
- // Prepare the params for the getGroups call on Perm::Medium.
- $tmp_params = array(
- 'fields' => array(
- 'subgroup_id',
- ),
- 'filters' => $subgroups,
- 'select' => 'col',
- );
-
- // Do not include groups that have already been fetched
- $tmp_params['filters']['subgroup_id'] = array(
- 'op' => 'NOT IN',
- 'value' => $result,
- );
-
- // Merge 'group_id' filter if needed
- if (array_key_exists('group_id', $tmp_params['filters'])
- && (!is_array($params['filters']['group_id'])
- || !array_key_exists('value', $params['filters']['group_id'])
- )
- ) {
- $tmp_params['filters']['group_id'] = array_intersect(
- $subgroup_ids,
- (array)$params['subgroups']['group_id']
- );
- } else {
- $tmp_params['filters']['group_id'] = $subgroup_ids;
- }
-
- $subgroup_ids = $this->getGroups($tmp_params);
- if ($subgroup_ids === false) {
- return false;
- }
-
- $result = array_merge($result, (array)$subgroup_ids);
- // If there were more subgroups, loop again and try to retrieve the subgroups under the current subgroup.
- } while(!empty($subgroup_ids));
-
- // Merge 'group_id' filter if needed
- if (array_key_exists('filters', $params)
- && array_key_exists('group_id', $params['filters'])
- && (!is_array($params['filters']['group_id'])
- || !array_key_exists('value', $params['filters']['group_id'])
- )
- ) {
- $params['filters']['group_id'] = array_intersect($result, (array)$params['filters']['group_id']);
- } else {
- $params['filters']['group_id'] = $result;
- }
- return parent::getGroups($params);
- }
-
- /**
- * Fetches groups with their subgroups into a hierarchal structure
- *
- * @param array containing key-value pairs for:
- * 'fields' - ordered array containing the fields to fetch
- * if empty all fields from the user table are fetched
- * 'filters' - key values pairs (value may be a string or an array)
- * 'orders' - key value pairs (values 'ASC' or 'DESC')
- * 'rekey' - if set to true, returned array will have the
- * first column as its first dimension
- * 'group' - if set to true and $rekey is set to true, then
- * all values with the same first column will be
- * wrapped in an array
- * 'limit' - number of rows to select
- * 'offset' - first row to select
- * 'select' - determines what query method to use:
- * 'one' -> queryOne, 'row' -> queryRow,
- * 'col' -> queryCol, 'all' ->queryAll (default)
- * 'selectable_tables' - array list of tables that may be
- * joined to in this query, the first element is
- * the root table from which the joins are done
- * 'hierarchy' - filter array if all subgroups should be
- fetched into a nested array
- * @return bool|array false on failure or array with selected data
- *
- * @access private
- */
- function _getGroupsWithHierarchy($params)
- {
- // Sanity checks on the provided params.
- if (!$params['rekey'] || $params['group'] || $params['select'] != 'all'
- || (reset($params['fields']) !== 'group_id' && reset($params['fields']) !== '*')
- ) {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR, 'exception',
- array('msg' => "Setting 'hierarchy' is only allowed if 'rekey' is enabled, ".
- "'group' is disabled, 'select' is 'all' and the first field is 'group_id'")
- );
- return false;
- }
-
- // Get the initial groups.
- $groups = parent::getGroups($params);
- if (!$groups) {
- return $groups;
- }
-
- // Get the the subgroup id's for these initials groups.
- $tmp_params = array(
- 'fields' => array(
- 'group_id',
- 'subgroup_id',
- ),
- 'filters' => array('group_id' => array_keys($groups)),
- 'rekey' => true,
- 'group' => true,
- );
-
- $subgroups = $this->getGroups($tmp_params);
- if ($subgroups === false) {
- return false;
- }
-
- $hierarchy = is_array($params['hierarchy']) ? $params['hierarchy'] : array();
-
- // Loop through the subgroups. In each loop, perform a recursive
- // call the the subgroup_ids that are assigned to the current group.
- foreach ($subgroups as $group_id => $subgroup_ids) {
- $params['filters'] = $hierarchy;
- // Merge 'group_id' filter with 'hierachy' if needed
- if (array_key_exists('group_id', $params['filters'])
- && (!is_array($params['filters']['group_id'])
- || !array_key_exists('value', $params['filters']['group_id'])
- )
- ) {
- $params['filters']['group_id'] = array_intersect(
- $subgroup_ids,
- (array)$params['filters']['group_id']
- );
- } else {
- $params['filters']['group_id'] = $subgroup_ids;
- }
- $subgroup_data = $this->_getGroupsWithHierarchy($params);
- if ($subgroup_data === false) {
- return false;
- }
- $groups[$group_id]['subgroups'] = $subgroup_data;
- }
-
- return $groups;
- }
-
- /**
- * Fetches rights
- *
- * @param array containing key-value pairs for:
- * 'fields' - ordered array containing the fields to fetch
- * if empty all fields from the user table are fetched
- * 'filters' - key values pairs (value may be a string or an array)
- * 'orders' - key value pairs (values 'ASC' or 'DESC')
- * 'rekey' - if set to true, returned array will have the
- * first column as its first dimension
- * 'group' - if set to true and $rekey is set to true, then
- * all values with the same first column will be
- * wrapped in an array
- * 'limit' - number of rows to select
- * 'offset' - first row to select
- * 'select' - determines what query method to use:
- * 'one' -> queryOne, 'row' -> queryRow,
- * 'col' -> queryCol, 'all' ->queryAll (default)
- * 'selectable_tables' - array list of tables that may be
- * joined to in this query, the first element is
- * the root table from which the joins are done
- * 'by_group' - if joins should be done using the 'userrights'
- * (false default) or through the 'grouprights'
- * and 'groupusers' tables (true)
- * 'inherited' - filter array to fetch all rughts from
- (sub)group membership
- * 'implied' - filter array for fetching implied rights
- * 'hierarchy' - filter array for fetching implied rights
- into a nested array (overwrites 'implied')
- * @return bool|array false on failure or array with selected data
- *
- * @access public
- */
- function getRights($params = array())
- {
- // Determine of 'inherited', 'implied' or 'hierarchy' is set
- // 'hierarchy' means that 'implied' also is set
- $inherited = array_key_exists('inherited', $params);
- if (array_key_exists('hierarchy', $params)) {
- $hierarchy = $implied = true;
- $params['implied'] = $params['hierarchy'];
- } else {
- $implied = array_key_exists('implied', $params);
- $hierarchy = false;
- }
-
- // Sanity check on the provided params if the inherited of implied param is set.
- if ($inherited || $implied) {
- $params = LiveUser_Admin_Storage::setSelectDefaultParams($params);
-
- if (!$params['rekey'] || $params['group'] || $params['select'] !== 'all'
- || (reset($params['fields']) !== 'right_id' && reset($params['fields']) !== '*')
- ) {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR, 'exception',
- array('msg' => "Setting 'inherited', 'implied' or 'hierarchy'".
- " is only allowed if 'rekey' is enabled, 'group' is disabled".
- ", 'select' is 'all' and the first field is 'right_id'")
- );
- return false;
- }
-
- // Extra sanity check on the provided params if the implied param is set
- // (has_implied should be included in the fields.
- if ($implied && !in_array('has_implied', $params['fields'])) {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR, 'exception',
- array('msg' => "Setting 'implied' or 'hierarchy' requires that 'has_implied' field needs to be in the select list")
- );
- return false;
- }
- }
-
- // handle select, fields and rekey
- $rights = parent::getRights($params);
- if ($rights === false) {
- return false;
- }
-
- // read rights inherited by (sub)groups
- if ($inherited) {
- // todo: consider adding a NOT IN filter
- $inherited_rights = $this->_getInheritedRights($params);
- if ($inherited_rights === false) {
- return false;
- }
-
- if (!empty($inherited_rights)) {
- // Loop through the resulting inherited rights, check if they already exist in the current rights array
- // If not: set the type to inherited and add it to the rights array.
- foreach ($inherited_rights as $right_id => $right) {
- if (isset($rights[$right_id])) {
- continue;
- }
-
- $right['_type'] = 'inherited';
- $rights[$right_id] = $right;
- }
- }
- }
-
- // if the result was empty or no additional work is needed
- if (empty($rights) || !$implied) {
- return $rights;
- }
-
- if ($implied) {
- $_rights = $rights;
- $rights = array();
-
- // Loop through the current rights array (backupped in _rights) and
- // set the type to granted if the type isn't set yet.
- foreach ($_rights as $right_id => $right) {
- if (!array_key_exists('_type', $right)) {
- $right['_type'] = 'granted';
- }
- $rights[$right_id] = $right;
- // If has_implied isn't true, continue (no work to do).
- if (!$right['has_implied']) {
- continue;
- }
-
- // todo: consider adding a NOT IN filter
- $implied_rights = $this->_getImpliedRights($params, $right_id);
- if ($implied_rights === false) {
- return false;
- } elseif (empty($implied_rights)) {
- continue;
- }
-
- // Loop through the resulting rights, set the type and order the array based
- // on the params['implied'] value.
- foreach ($implied_rights as $implied_right_id => $right) {
- if (isset($rights[$implied_right_id])) {
- continue;
- }
-
- $right['_type'] = 'implied';
-
- // If hierarchy: add the resulting rights to the right they belong to (in implied_rights)
- if ($hierarchy) {
- $rights[$right_id]['implied_rights'][$implied_right_id] = $right;
- } else {
- $rights[$implied_right_id] = $right;
- }
- }
- }
-
- return $rights;
- }
-
- $params = LiveUser_Admin_Storage::setSelectDefaultParams($params);
-
- // If the select is set to all (or not set at all) and more than one field is set,
- // set the type to granted if it isn't set.
- if ($params['select'] == 'all'
- && (count($params['fields']) > 1 || reset($params['fields']) === '*')
- ) {
- foreach ($rights as $right_id => $right) {
- if (!isset($rights[$right_id]['_type']) || !$rights[$right_id]['_type']) {
- $rights[$right_id]['_type'] = 'granted';
- }
- }
- }
-
- return $rights;
- }
-
- /**
- * Fetches implied rights for a given right
- *
- * @param array containing key-value pairs for:
- * 'fields' - ordered array containing the fields to fetch
- * if empty all fields from the user table are fetched
- * 'filters' - key values pairs (value may be a string or an array)
- * 'orders' - key value pairs (values 'ASC' or 'DESC')
- * 'rekey' - if set to true, returned array will have the
- * first column as its first dimension
- * 'group' - if set to true and $rekey is set to true, then
- * all values with the same first column will be
- * wrapped in an array
- * 'limit' - number of rows to select
- * 'offset' - first row to select
- * 'select' - determines what query method to use:
- * 'one' -> queryOne, 'row' -> queryRow,
- * 'col' -> queryCol, 'all' ->queryAll (default)
- * 'selectable_tables' - array list of tables that may be
- * joined to in this query, the first element is
- * the root table from which the joins are done
- * 'by_group' - if joins should be done using the 'userrights'
- * (false default) or through the 'grouprights'
- * and 'groupusers' tables (true)
- * 'implied' - filter array for fetching implied rights
- * @return bool|array false on failure or array with selected data
- *
- * @access private
- */
- function _getImpliedRights($params, $right_id)
- {
- // Define the selectable tables and define the root table.
- $selectable_tables = array('right_implied', 'rights');
- $root_table = 'right_implied';
-
- $param = array(
- 'fields' => array('implied_right_id'),
- 'select' => 'col',
- 'filters' => array('right_id' => $right_id),
- );
-
- // Get the implied_right right_id's.
- // If there are no implied rights (or an error occured), return.
- $result = $this->_makeGet($param, $root_table, $selectable_tables);
- if (!$result) {
- return $result;
- }
-
- // Merge 'right_id' filter with 'implied' if needed
- $params['filters'] = is_array($params['implied']) ? $params['implied'] : array();
- if (array_key_exists('right_id', $params['filters'])
- && (!is_array($params['filters']['right_id'])
- || !array_key_exists('value', $params['filters']['right_id'])
- )
- ) {
- $params['filters']['right_id'] = array_intersect($result, (array)$params['filters']['right_id']);
- } else {
- $params['filters']['right_id'] = $result;
- }
- return $this->getRights($params);
- }
-
- /**
- * Fetches all rights gained through subgroup memberships
- *
- * @param array containing key-value pairs for:
- * 'fields' - ordered array containing the fields to fetch
- * if empty all fields from the user table are fetched
- * 'filters' - key values pairs (value may be a string or an array)
- * 'orders' - key value pairs (values 'ASC' or 'DESC')
- * 'rekey' - if set to true, returned array will have the
- * first column as its first dimension
- * 'group' - if set to true and $rekey is set to true, then
- * all values with the same first column will be
- * wrapped in an array
- * 'limit' - number of rows to select
- * 'offset' - first row to select
- * 'select' - determines what query method to use:
- * 'one' -> queryOne, 'row' -> queryRow,
- * 'col' -> queryCol, 'all' ->queryAll (default)
- * 'selectable_tables' - array list of tables that may be
- * joined to in this query, the first element is
- * the root table from which the joins are done
- * 'by_group' - if joins should be done using the 'userrights'
- * (false default) or through the 'grouprights'
- * and 'groupusers' tables (true)
- * 'inherited' - filter array to fetch all rughts from
- (sub)group membership
- * @return bool|array false on failure or array with selected data
- *
- * @access private
- */
- function _getInheritedRights($params)
- {
- // Prepare the params with the provided fiters in the params array.
- $param = array(
- 'fields' => array('group_id'),
- 'select' => 'col',
- 'filters' => is_array($params['inherited']) ? $params['inherited'] : array(),
- 'subgroups' => is_array($params['inherited']) ? $params['inherited'] : array(),
- );
-
- // Get the groups based on the params.
- // If there are no subgroups (or an error occured), return.
- $result = $this->getGroups($param);
- if (!$result) {
- return $result;
- }
-
- // Merge 'group_id' filter if needed
- if (array_key_exists('filters', $params)
- && array_key_exists('group_id', $params['filters'])
- && (!is_array($params['filters']['group_id'])
- || !array_key_exists('value', $params['filters']['group_id'])
- )
- ) {
- $params['filters']['group_id'] = array_intersect($result, (array)$params['filters']['group_id']);
- } else {
- $params['filters']['group_id'] = $result;
- }
- $params['by_group'] = true;
- unset($params['inherited']);
- return $this->getRights($params);
- }
-}
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * A framework for authentication and authorization in PHP applications
- *
- * LiveUser_Admin is meant to be used with the LiveUser package.
- * It is composed of all the classes necessary to administrate
- * data used by LiveUser.
- *
- * You'll be able to add/edit/delete/get things like:
- * * Rights
- * * Users
- * * Groups
- * * Areas
- * * Applications
- * * Subgroups
- * * ImpliedRights
- *
- * And all other entities within LiveUser.
- *
- * At the moment we support the following storage containers:
- * * DB
- * * MDB
- * * MDB2
- *
- * But it takes no time to write up your own storage container,
- * so if you like to use native mysql functions straight, then it's possible
- * to do so in under a hour!
- *
- * PHP version 4 and 5
- *
- * LICENSE: This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library 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
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
- * MA 02111-1307 USA
- *
- *
- * @category authentication
- * @package LiveUser_Admin
- * @author Markus Wolff <wolff@21st.de>
- * @author Helgi Þormar Þorbjörnsson <dufuz@php.net>
- * @author Lukas Smith <smith@pooteeweet.org>
- * @author Arnaud Limbourg <arnaud@php.net>
- * @author Christian Dickmann <dickmann@php.net>
- * @author Matt Scifo <mscifo@php.net>
- * @author Bjoern Kraus <krausbn@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version $Id: Medium.php,v 1.1.1.1 2008/04/28 15:20:46 jamie Exp $
- * @link http://pear.php.net/LiveUser_Admin
- */
-
-define('LIVEUSER_GROUP_TYPE_ALL', 1);
-define('LIVEUSER_GROUP_TYPE_ROLE', 2);
-define('LIVEUSER_GROUP_TYPE_USER', 3);
-
- /**
- * Require parent class definition.
- */
-require_once 'LiveUser/Admin/Perm/Simple.php';
-
-/**
- * Medium permission administration class that extends the Simple class with the
- * ability to create, update, remove and assign groups.
- *
- * This class provides a set of functions for implementing a user
- * permission management system on live websites. All authorisation
- * backends/containers must be extensions of this base class.
- *
- * @category authentication
- * @package LiveUser_Admin
- * @author Markus Wolff <wolff@21st.de>
- * @author Bjoern Kraus <krausbn@php.net>
- * @author Helgi Þormar Þorbjörnsson <dufuz@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version Release: @package_version@
- * @link http://pear.php.net/LiveUser_Admin
- */
-class LiveUser_Admin_Perm_Medium extends LiveUser_Admin_Perm_Simple
-{
- /**
- * Constructor
- *
- * @return void
- *
- * @access protected
- */
- function LiveUser_Admin_Perm_Medium()
- {
- // Define the required tables for the Medium container. Used by the query builder
- $this->LiveUser_Admin_Perm_Simple();
- $this->selectable_tables['getUsers'][] = 'groupusers';
- $this->selectable_tables['getGroups'] = array('groups', 'groupusers', 'grouprights', 'rights', 'translations');
- $this->withFieldMethodMap['group_id'] = 'getGroups';
- }
-
- /**
- * Add a group
- *
- * @param array containing atleast the key-value-pairs of all required
- * columns in the group table
- * @return int|bool false on error, true (or new id) on success
- *
- * @access public
- */
- function addGroup($data)
- {
- $result = $this->_storage->insert('groups', $data);
- // todo: notify observer
- return $result;
- }
-
- /**
- * Update groups
- *
- * @param array containing the key value pairs of columns to update
- * @param array key values pairs (value may be a string or an array)
- * This will construct the WHERE clause of your update
- * Be careful, if you leave this blank no WHERE clause
- * will be used and all groups will be affected by the update
- * @return int|bool false on error, the affected rows on success
- *
- * @access public
- */
- function updateGroup($data, $filters)
- {
- $result = $this->_storage->update('groups', $data, $filters);
- // todo: notify observer
- return $result;
- }
-
- /**
- * Remove groups and all their relevant relations
- *
- * @param array key values pairs (value may be a string or an array)
- * This will construct the WHERE clause of your update
- * Be careful, if you leave this blank no WHERE clause
- * will be used and all groups will be affected by the removed
- * @return int|bool false on error, the affected rows on success
- *
- * @access public
- */
- function removeGroup($filters)
- {
- // Prepare the filters. Based on the provided filters a new array will be
- // created with the corresponding group_id's. If the filters are empty,
- // cause an error or just have no result 0 or false will be returned
- $filters = $this->_makeRemoveFilter($filters, 'group_id', 'getGroups');
- if (!$filters) {
- return $filters;
- }
-
- // Clean up the database so no unnessacary information is left behind (members, granted rights)
- // Remove all the users that are members of this group.
- $result = $this->removeUserFromGroup($filters);
- if ($result === false) {
- return false;
- }
-
- // Remove the group.
- $result = $this->revokeGroupRight($filters);
- if ($result === false) {
- return false;
- }
-
- $result = $this->_storage->delete('groups', $filters);
- // todo: notify observer
- return $result;
- }
-
- /**
- * Grant group a right
- *
- * <code>
- * // grant user id 13 the right NEWS_CHANGE
- * $data = array(
- * 'right_id' => NEWS_CHANGE,
- * 'group_id' => 13
- * );
- * $lua->perm->grantGroupRight($data);
- * </code>
- *
- * @param array containing the group_id and right_id and optionally a right_level
- * @return
- *
- * @access public
- */
- function grantGroupRight($data)
- {
- // Sanity check on the right level, if not set, use the default
- if (!array_key_exists('right_level', $data)) {
- $data['right_level'] = LIVEUSER_MAX_LEVEL;
- }
-
- // check if the group has already been granted that right
- $filters = array(
- 'group_id' => $data['group_id'],
- 'right_id' => $data['right_id'],
- );
-
- $count = $this->_storage->selectCount('grouprights', 'right_id', $filters);
-
- // It did already.. Add an error to the stack.
- if ($count > 0) {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR, 'exception',
- array('msg' => 'This group with id '.$data['group_id'].
- ' has already been granted the right id '.$data['right_id'])
- );
- return false;
- }
-
- $result = $this->_storage->insert('grouprights', $data);
- // todo: notify observer
- return $result;
- }
-
- /**
- * Update right(s) for the given group(s)
- *
- * @param array containing the key value pairs of columns to update
- * @param array key values pairs (value may be a string or an array)
- * This will construct the WHERE clause of your update
- * Be careful, if you leave this blank no WHERE clause
- * will be used and all groups will be affected by the update
- * @return int|bool false on error, the affected rows on success
- *
- * @access public
- */
- function updateGroupRight($data, $filters)
- {
- $result = $this->_storage->update('grouprights', $data, $filters);
- // todo: notify observer
- return $result;
- }
-
- /**
- * Revoke (remove) right(s) from the group(s)
- *
- * @param array key values pairs (value may be a string or an array)
- * This will construct the WHERE clause of your update
- * Be careful, if you leave this blank no WHERE clause
- * will be used and all groups will be affected by the remove
- * @return int|bool false on error, the affected rows on success
- *
- * @access public
- */
- function revokeGroupRight($filters)
- {
- $result = $this->_storage->delete('grouprights', $filters);
- // todo: notify observer
- return $result;
- }
-
- /**
- * Add a user to agroup
- *
- * @param array containing the perm_user_id and group_id
- * @return
- *
- * @access public
- */
- function addUserToGroup($data)
- {
- // check if the userhas already been granted added to that group
- $filters = array(
- 'perm_user_id' => $data['perm_user_id'],
- 'group_id' => $data['group_id'],
- );
-
- $count = $this->_storage->selectCount('groupusers', 'group_id', $filters);
-
- // It already had been added. Return true.
- if ($count > 0) {
- return true;
- }
-
- $result = $this->_storage->insert('groupusers', $data);
- // todo: notify observer
- return $result;
- }
-
- /**
- * Remove user(s) from group(s)
- *
- * @param array key values pairs (value may be a string or an array)
- * This will construct the WHERE clause of your update
- * Be careful, if you leave this blank no WHERE clause
- * will be used and all users will be affected by the remove
- * @return int|bool false on error, the affected rows on success
- *
- * @access public
- */
- function removeUserFromGroup($filters)
- {
- $result = $this->_storage->delete('groupusers', $filters);
- // todo: notify observer
- return $result;
- }
-
- /**
- * Fetches rights
- *
- * @param array containing key-value pairs for:
- * 'fields' - ordered array containing the fields to fetch
- * if empty all fields from the user table are fetched
- * 'filters' - key values pairs (value may be a string or an array)
- * 'orders' - key value pairs (values 'ASC' or 'DESC')
- * 'rekey' - if set to true, returned array will have the
- * first column as its first dimension
- * 'group' - if set to true and $rekey is set to true, then
- * all values with the same first column will be
- * wrapped in an array
- * 'limit' - number of rows to select
- * 'offset' - first row to select
- * 'select' - determines what query method to use:
- * 'one' -> queryOne, 'row' -> queryRow,
- * 'col' -> queryCol, 'all' ->queryAll (default)
- * 'selectable_tables' - array list of tables that may be
- * joined to in this query, the first element is
- * the root table from which the joins are done
- * 'by_group' - if joins should be done using the 'userrights'
- * (false default) or through the 'grouprights'
- * and 'groupusers' tables (true)
- * @return bool|array false on failure or array with selected data
- *
- * @access public
- */
- function getRights($params = array())
- {
- $selectable_tables = $this->_findSelectableTables('getRights' , $params);
- $root_table = reset($selectable_tables);
-
- // If the by_group is present, and the grouprights table is not in the selectable_tables:
- if (array_key_exists('by_group', $params)
- && $params['by_group']
- && !in_array('grouprights', $selectable_tables)
- ) {
- unset($params['by_group']);
- $key = array_search('userrights', $selectable_tables);
- if ($key) {
- // add the groupusers, replace the userrights with
- // the grouprights and prepend the root table
- $selectable_tables[0] = 'groupusers';
- $selectable_tables[$key] = 'grouprights';
- array_unshift($selectable_tables, $root_table);
- } else {
- // add the groupusers, prepend the grouprights and the root table
- $selectable_tables[0] = 'groupusers';
- array_unshift($selectable_tables, 'grouprights');
- array_unshift($selectable_tables, $root_table);
- }
- }
-
- return $this->_makeGet($params, $root_table, $selectable_tables);
- }
-
- /**
- * Remove rights and all their relevant relations
- *
- * @param array key values pairs (value may be a string or an array)
- * This will construct the WHERE clause of your update
- * Be careful, if you leave this blank no WHERE clause
- * will be used and all rights will be affected by the remove
- * @return int|bool false on error, the affected rows on success
- *
- * @access public
- */
- function removeRight($filters)
- {
- $filters = $this->_makeRemoveFilter($filters, 'right_id', 'getRights');
- if (!$filters) {
- return $filters;
- }
-
- $result = $this->revokeGroupRight($filters);
- if ($result === false) {
- return false;
- }
-
- return parent::removeRight($filters);
- }
-
- /**
- * Remove users and all their relevant relations
- *
- * @param array key values pairs (value may be a string or an array)
- * This will construct the WHERE clause of your update
- * Be careful, if you leave this blank no WHERE clause
- * will be used and all users will be affected by the removed
- * @return int|bool false on error, the affected rows on success
- *
- * @access public
- */
- function removeUser($filters)
- {
- // Prepare the filters. Based on the provided filters a new array will be
- // created with the corresponding perm_user_id's. If the filters are empty,
- // cause an error or just have no result 0 or false will be returned
- $filters = $this->_makeRemoveFilter($filters, 'perm_user_id', 'getUsers');
- if (!$filters) {
- return $filters;
- }
-
- // Remove the users from any group it might be a member of.
- // If an error occures, return false.
- $result = $this->removeUserFromGroup($filters);
- if ($result === false) {
- return false;
- }
-
- // remove the user using Perm Simple.
- return parent::removeUser($filters);
- }
-
- /**
- * Fetches groups
- *
- * @param array containing key-value pairs for:
- * 'fields' - ordered array containing the fields to fetch
- * if empty all fields from the user table are fetched
- * 'filters' - key values pairs (value may be a string or an array)
- * 'orders' - key value pairs (values 'ASC' or 'DESC')
- * 'rekey' - if set to true, returned array will have the
- * first column as its first dimension
- * 'group' - if set to true and $rekey is set to true, then
- * all values with the same first column will be
- * wrapped in an array
- * 'limit' - number of rows to select
- * 'offset' - first row to select
- * 'select' - determines what query method to use:
- * 'one' -> queryOne, 'row' -> queryRow,
- * 'col' -> queryCol, 'all' ->queryAll (default)
- * 'selectable_tables' - array list of tables that may be
- * joined to in this query, the first element is
- * the root table from which the joins are done
- * @return bool|array false on failure or array with selected data
- *
- * @access public
- */
- function getGroups($params = array())
- {
- $selectable_tables = $this->_findSelectableTables('getGroups' , $params);
- $root_table = reset($selectable_tables);
-
- return $this->_makeGet($params, $root_table, $selectable_tables);
- }
-}
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * A framework for authentication and authorization in PHP applications
- *
- * LiveUser_Admin is meant to be used with the LiveUser package.
- * It is composed of all the classes necessary to administrate
- * data used by LiveUser.
- *
- * You'll be able to add/edit/delete/get things like:
- * * Rights
- * * Users
- * * Groups
- * * Areas
- * * Applications
- * * Subgroups
- * * ImpliedRights
- *
- * And all other entities within LiveUser.
- *
- * At the moment we support the following storage containers:
- * * DB
- * * MDB
- * * MDB2
- *
- * But it takes no time to write up your own storage container,
- * so if you like to use native mysql functions straight, then it's possible
- * to do so in under a hour!
- *
- * PHP version 4 and 5
- *
- * LICENSE: This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library 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
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
- * MA 02111-1307 USA
- *
- *
- * @category authentication
- * @package LiveUser_Admin
- * @author Markus Wolff <wolff@21st.de>
- * @author Helgi Þormar Þorbjörnsson <dufuz@php.net>
- * @author Lukas Smith <smith@pooteeweet.org>
- * @author Arnaud Limbourg <arnaud@php.net>
- * @author Christian Dickmann <dickmann@php.net>
- * @author Matt Scifo <mscifo@php.net>
- * @author Bjoern Kraus <krausbn@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version CVS: $Id: Simple.php,v 1.1.1.1 2008/04/28 15:20:46 jamie Exp $
- * @link http://pear.php.net/LiveUser_Admin
- */
-
-require_once 'LiveUser/Perm/Simple.php';
-
-/**
- * Simple permission administration class that features support for
- * creating, updating, removing and assigning:
- * - users
- * - rights
- * - areas (categorize rights)
- * - applications (categorize areas)
- * - translations (for rights, areas, applications and groups)
- *
- * This class provides a set of functions for implementing a user
- * permission management system on live websites. All authorisation
- * backends/containers must be extensions of this base class.
- *
- * @category authentication
- * @package LiveUser_Admin
- * @author Markus Wolff <wolff@21st.de>
- * @author Bjoern Kraus <krausbn@php.net>
- * @author Helgi Þormar Þorbjörnsson <dufuz@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version Release: @package_version@
- * @link http://pear.php.net/LiveUser_Admin
- */
-class LiveUser_Admin_Perm_Simple
-{
- /**
- * Error stack
- *
- * @var object PEAR_ErrorStack
- * @access public
- */
- var $stack = null;
-
- /**
- * Storage Container
- *
- * @var object
- * @access private
- */
- var $_storage = null;
-
- /**
- * Key (method names), with array lists of selectable tables for the given method
- *
- * @var array
- * @access public
- */
- var $selectable_tables = array(
- 'getUsers' => array('perm_users', 'userrights', 'rights'),
- 'getRights' => array('rights', 'userrights', 'areas', 'applications', 'translations'),
- 'getAreas' => array('areas', 'applications', 'translations'),
- 'getApplications' => array('applications', 'translations'),
- 'getTranslations' => array('translations'),
- );
-
- /**
- * Key (field name), with method names as values to determine what method
- * should be called to get data when the 'with' option is used in a get*() method
- *
- * @var array
- * @access public
- */
- var $withFieldMethodMap = array(
- 'perm_user_id' => 'getUsers',
- 'right_id' => 'getRights',
- 'area_id' => 'getAreas',
- 'application_id' => 'getApplications',
- );
-
- /**
- * Constructor
- *
- * @return void
- *
- * @access protected
- */
- function LiveUser_Admin_Perm_Simple()
- {
- // Create the error stack, retrieve the errors using LiveUser_Admin->getErrors().
- $this->stack = &PEAR_ErrorStack::singleton('LiveUser_Admin');
- }
-
- /**
- * Initialize the storage container
- *
- * @param array array containing the configuration.
- * @return bool true on success or false on failure
- *
- * @access public
- */
- function init(&$conf)
- {
- // Sanity check, is there a storage container defined in the configuration.
- if (!array_key_exists('storage', $conf)) {
- $this->stack->push(LIVEUSER_ADMIN_ERROR, 'exception',
- array('msg' => 'Missing storage configuration array'));
- return false;
- }
-
- // Set the config to class vars.
- if (is_array($conf)) {
- $keys = array_keys($conf);
- foreach ($keys as $key) {
- if (isset($this->$key)) {
- $this->$key =& $conf[$key];
- }
- }
- }
-
- // Create the storage class, if and error occures, add it to the stack and return false.
- $this->_storage =& LiveUser::storageFactory($conf['storage'], 'LiveUser_Admin_Perm_');
- if ($this->_storage === false) {
- end($conf['storage']);
- $key = key($conf['storage']);
- $this->stack->push(LIVEUSER_ERROR, 'exception',
- array('msg' => 'Could not instanciate perm storage container: '.$key));
- return false;
- }
-
- return true;
- }
-
- /**
- * Add a user
- *
- * @param array containing atleast the key-value-pairs of all required
- * columns in the perm_users table
- * @return int|bool false on error, true (or new id) on success
- *
- * @access public
- */
- function addUser($data)
- {
- // Sanity check. If not present, set the perm_type to the default value.
- if (!array_key_exists('perm_type', $data)) {
- $data['perm_type'] = LIVEUSER_USER_TYPE_ID;
- }
-
- $result = $this->_storage->insert('perm_users', $data);
- // todo: notify observer
- return $result;
- }
-
- /**
- * Update users
- *
- * @param array containing the key value pairs of columns to update
- * @param array key values pairs (value may be a string or an array)
- * This will construct the WHERE clause of your update
- * Be careful, if you leave this blank no WHERE clause
- * will be used and all users will be affected by the update
- * @return int|bool false on error, the affected rows on success
- *
- * @access public
- */
- function updateUser($data, $filters)
- {
- $result = $this->_storage->update('perm_users', $data, $filters);
- // todo: notify observer
- return $result;
- }
-
- /**
- * Remove users and all their relevant relations
- *
- * @param array key values pairs (value may be a string or an array)
- * This will construct the WHERE clause of your update
- * Be careful, if you leave this blank no WHERE clause
- * will be used and all users will be affected by the removed
- * @return int|bool false on error, the affected rows on success
- *
- * @access public
- */
- function removeUser($filters)
- {
- // Prepare the filters. Based on the provided filters a new array will be
- // created with the corresponding perm_user_id's. If the filters are empty,
- // cause an error or just have no result 0 or false will be returned
- $filters = $this->_makeRemoveFilter($filters, 'perm_user_id', 'getUsers');
- if (!$filters) {
- return $filters;
- }
-
- // Revoke all the rights this user might have (clean up the database).
- $result = $this->revokeUserRight($filters);
- if ($result === false) {
- return false;
- }
-
- $result = $this->_storage->delete('perm_users', $filters);
- // todo: notify observer
- return $result;
- }
-
- /**
- * Add a right
- *
- * @param array containing atleast the key-value-pairs of all required
- * columns in the rights table
- * @return int|bool false on error, true (or new id) on success
- *
- * @access public
- */
- function addRight($data)
- {
- $result = $this->_storage->insert('rights', $data);
- // todo: notify observer
- return $result;
- }
-
- /**
- * Update rights
- *
- * @param array containing the key value pairs of columns to update
- * @param array key values pairs (value may be a string or an array)
- * This will construct the WHERE clause of your update
- * Be careful, if you leave this blank no WHERE clause
- * will be used and all rights will be affected by the update
- * @return int|bool false on error, the affected rows on success
- *
- * @access public
- */
- function updateRight($data, $filters)
- {
- $result = $this->_storage->update('rights', $data, $filters);
- // todo: notify observer
- return $result;
- }
-
- /**
- * Remove rights and all their relevant relations
- *
- * @param array key values pairs (value may be a string or an array)
- * This will construct the WHERE clause of your update
- * Be careful, if you leave this blank no WHERE clause
- * will be used and all rights will be affected by the remove
- * @return int|bool false on error, the affected rows on success
- *
- * @access public
- */
- function removeRight($filters)
- {
- // Prepare the filters. Based on the provided filters a new array will be
- // created with the corresponding right_id's. If the filters are empty,
- // cause an error or just have no result 0 or false will be returned
- $filters = $this->_makeRemoveFilter($filters, 'right_id', 'getRights');
- if (!$filters) {
- return $filters;
- }
-
- // Revoke this right from any user it might have been assigned to (clean up database)
- $result = $this->revokeUserRight($filters);
- if ($result === false) {
- return false;
- }
-
- $result = $this->_storage->delete('rights', $filters);
- // todo: notify observer
- return $result;
- }
-
- /**
- * Add an area
- *
- * @param array containing atleast the key-value-pairs of all required
- * columns in the areas table
- * @return int|bool false on error, true (or new id) on success
- *
- * @access public
- */
- function addArea($data)
- {
- $result = $this->_storage->insert('areas', $data);
- // todo: notify observer
- return $result;
- }
-
- /**
- * Update areas
- *
- * @param array associative array in the form of $fieldname => $data
- * @param array associative array in the form of $fieldname => $data
- * This will construct the WHERE clause of your update
- * Be careful, if you leave this blank no WHERE clause
- * will be used and all areas will be affected by the update
- * @return int|bool false on error, the affected rows on success
- *
- * @access public
- */
- function updateArea($data, $filters)
- {
- $result = $this->_storage->update('areas', $data, $filters);
- // todo: notify observer
- return $result;
- }
-
- /**
- * Remove areas and all their relevant relations
- *
- * @param array key values pairs (value may be a string or an array)
- * This will construct the WHERE clause of your update
- * Be careful, if you leave this blank no WHERE clause
- * will be used and all areas will be affected by the remove
- * @return int|bool false on error, the affected rows on success
- *
- * @access public
- */
- function removeArea($filters)
- {
- // Prepare the filters. Based on the provided filters a new array will be
- // created with the corresponding area_id's. If the filters are empty,
- // cause an error or just have no result 0 or false will be returned
- $filters = $this->_makeRemoveFilter($filters, 'area_id', 'getAreas');
- if (!$filters) {
- return $filters;
- }
-
- // Remove all the rights that are part of this area.
- $result = $this->removeRight($filters);
- if ($result === false) {
- return false;
- }
-
- $result = $this->_storage->delete('areas', $filters);
- // todo: notify observer
- return $result;
- }
-
- /**
- * Add an application
- *
- * @param array containing atleast the key-value-pairs of all required
- * columns in the applications table
- * @return int|bool false on error, true (or new id) on success
- *
- * @access public
- */
- function addApplication($data)
- {
- $result = $this->_storage->insert('applications', $data);
- // todo: notify observer
- return $result;
- }
-
- /**
- * Update applications
- *
- * @param array containing the key value pairs of columns to update
- * @param array key values pairs (value may be a string or an array)
- * This will construct the WHERE clause of your update
- * Be careful, if you leave this blank no WHERE clause
- * will be used and all applictions will be affected by the update
- * @return int|bool false on error, the affected rows on success
- *
- * @access public
- */
- function updateApplication($data, $filters)
- {
- $result = $this->_storage->update('applications', $data, $filters);
- // todo: notify observer
- return $result;
- }
-
- /**
- * Remove applications and all their relevant relations
- *
- * @param array key values pairs (value may be a string or an array)
- * This will construct the WHERE clause of your update
- * Be careful, if you leave this blank no WHERE clause
- * will be used and all applications will be affected by the remove
- * @return int|bool false on error, the affected rows on success
- *
- * @access public
- */
- function removeApplication($filters)
- {
- // Prepare the filters. Based on the provided filters a new array will be
- // created with the corresponding application_id's. If the filters are empty,
- // cause an error or just have no result 0 or false will be returned
- $filters = $this->_makeRemoveFilter($filters, 'application_id', 'getApplications');
- if (!$filters) {
- return $filters;
- }
-
- // Remove all the area's that are part of this application
- $result = $this->removeArea($filters);
- if ($result === false) {
- return false;
- }
-
- $result = $this->_storage->delete('applications', $filters);
- // todo: notify observer
- return $result;
- }
-
- /**
- * Grant user a right
- *
- * <code>
- * // grant user id 13 the right NEWS_CHANGE
- * $data = array(
- * 'right_id' => NEWS_CHANGE,
- * 'perm_user_id' => 13
- * );
- * $lua->perm->grantUserRight($data);
- * </code>
- *
- * @param array containing the perm_user_id and right_id and optionally a right_level
- * @return
- *
- * @access public
- */
- function grantUserRight($data)
- {
- // Sanity check. Set the right_level to it's default value if it's not set.
- if (!array_key_exists('right_level', $data)) {
- $data['right_level'] = LIVEUSER_MAX_LEVEL;
- }
-
- // check if already exists
- $filters = array(
- 'perm_user_id' => $data['perm_user_id'],
- 'right_id' => $data['right_id'],
- );
-
- $count = $this->_storage->selectCount('userrights', 'right_id', $filters);
-
- // The user already has this right, adding an error to the stack and return false.
- if ($count > 0) {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR, 'exception',
- array('msg' => 'This user with perm id '.$data['perm_user_id'].
- ' has already been granted the right id '.$data['right_id'])
- );
- return false;
- }
-
- $result = $this->_storage->insert('userrights', $data);
- // todo: notify observer
- return $result;
- }
-
- /**
- * Update right(s) for the given user(s)
- *
- * @param array containing the key value pairs of columns to update
- * @param array key values pairs (value may be a string or an array)
- * This will construct the WHERE clause of your update
- * Be careful, if you leave this blank no WHERE clause
- * will be used and all users will be affected by the update
- * @return int|bool false on error, the affected rows on success
- *
- * @access public
- */
- function updateUserRight($data, $filters)
- {
- $result = $this->_storage->update('userrights', $data, $filters);
- // todo: notify observer
- return $result;
- }
-
- /**
- * Revoke (remove) right(s) from the user(s)
- *
- * @param array key values pairs (value may be a string or an array)
- * This will construct the WHERE clause of your update
- * Be careful, if you leave this blank no WHERE clause
- * will be used and all users will be affected by the remove
- * @return int|bool false on error, the affected rows on success
- *
- * @access public
- */
- function revokeUserRight($filters)
- {
- $result = $this->_storage->delete('userrights', $filters);
- // todo: notify observer
- return $result;
- }
-
- /**
- * Add a translation
- *
- * @param array containing atleast the key-value-pairs of all required
- * columns in the users table
- * @return int|bool false on error, true (or new id) on success
- *
- * @access public
- */
- function addTranslation($data)
- {
- $result = $this->_storage->insert('translations', $data);
- // todo: notify observer
- return $result;
- }
-
- /**
- * Update translations
- *
- * @param array containing the key value pairs of columns to update
- * @param array key values pairs (value may be a string or an array)
- * This will construct the WHERE clause of your update
- * Be careful, if you leave this blank no WHERE clause
- * will be used and all translations will be affected by the update
- * @return int|bool false on error, the affected rows on success
- *
- * @access public
- */
- function updateTranslation($data, $filters)
- {
- $result = $this->_storage->update('translations', $data, $filters);
- // todo: notify observer
- return $result;
- }
-
- /**
- * Remove translations and all their relevant relations
- *
- * @param array key values pairs (value may be a string or an array)
- * This will construct the WHERE clause of your update
- * Be careful, if you leave this blank no WHERE clause
- * will be used and all translations will be affected by the remove
- * @return int|bool false on error, the affected rows on success
- *
- * @access public
- */
- function removeTranslation($filters)
- {
- // Prepare the filters. Based on the provided filters a new array will be
- // created with the corresponding translation_id's. If the filters are empty,
- // cause an error or just have no result 0 or false will be returned
- $filters = $this->_makeRemoveFilter($filters, 'translation_id', 'getTranslations');
- if (!$filters) {
- return $filters;
- }
-
- $result = $this->_storage->delete('translations', $filters);
- // todo: notify observer
- return $result;
- }
-
- /**
- * Makes the filters used by the remove functions and also
- * checks if there is actually something that needs removing.
- *
- * @param array key values pairs (value may be a string or an array)
- * This will construct the WHERE clause of your update
- * Be careful, if you leave this blank no WHERE clause
- * will be used and all users will be affected by the update
- * @param string name of the column for which we require a filter to be set
- * @param string name of the method that should be used to determine the filter
- * @return int|array|bool 0, an array containing the filter for the key
- * or false on error
- *
- * @access private
- */
- function _makeRemoveFilter($filters, $key, $method)
- {
- // Do not allow people to delete the entire contents of a given table
- if (empty($filters) || !is_array($filters)) {
- return 0;
- }
-
- // todo: if all filters apply to the given table only then we can probably skip running the select ..
-
- // Rewrite filter to only include the provided key, since we cannot
- // rely on joins in delete for all backends
- if (!isset($filters[$key]) || count($filters) > 1) {
- // Prepare the params for fetching the column provided. It should
- // return an array with only the keys.
- $params = array(
- 'fields' => array($key),
- 'filters' => $filters,
- 'select' => 'col',
- );
- $result = $this->$method($params);
- if ($result === false) {
- return false;
- }
-
- if (empty($result)) {
- return 0;
- }
-
- // Rebuild the filters array.
- $filters = array($key => $result);
- }
- return $filters;
- }
-
- /**
- * This function finds the list of selectable tables either from the params
- * or from the selectable_tables property using the method parameter
- *
- * @param string name of the method
- * @param array containing the parameters passed to a get*() method
- * @return array contains the selectable tables
- *
- * @access private
- */
- function _findSelectableTables($method, $params = array())
- {
- $selectable_tables = array();
- // Check if the provided params might already have the selectable tables.
- // If so, return them, else fetch them through this->selectable_tables.
- if (array_key_exists('selectable_tables', $params)) {
- $selectable_tables = $params['selectable_tables'];
- } elseif (array_key_exists($method, $this->selectable_tables)) {
- $selectable_tables = $this->selectable_tables[$method];
- }
- return $selectable_tables;
- }
-
- /**
- * This function holds up most of the heat for all the get* functions.
- *
- * @param array containing key-value pairs for:
- * 'fields' - ordered array containing the fields to fetch
- * if empty all fields from the user table are fetched
- * 'filters' - key values pairs (value may be a string or an array)
- * 'orders' - key value pairs (values 'ASC' or 'DESC')
- * 'rekey' - if set to true, returned array will have the
- * first column as its first dimension
- * 'group' - if set to true and $rekey is set to true, then
- * all values with the same first column will be
- * wrapped in an array
- * 'limit' - number of rows to select
- * 'offset' - first row to select
- * 'select' - determines what query method to use:
- * 'one' -> queryOne, 'row' -> queryRow,
- * 'col' -> queryCol, 'all' ->queryAll (default)
- * @param string name of the table from which to start looking
- * for join points
- * @param array list of tables that may be joined to
- * @return bool|array false on failure or array with selected data
- *
- * @access private
- */
- function _makeGet($params, $root_table, $selectable_tables)
- {
- // Ensure that default params are set
- $params = LiveUser_Admin_Storage::setSelectDefaultParams($params);
-
- $data = $this->_storage->select($params['select'], $params['fields'],
- $params['filters'], $params['orders'], $params['rekey'], $params['group'],
- $params['limit'], $params['offset'], $root_table, $selectable_tables);
-
- // If 'with' is set and the result data is not empty
- if (!empty($params['with']) && !empty($data)) {
- if ($params['select'] != 'all') {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR, 'exception',
- array('msg' => 'Using "with" requires "select" to be set to "all"')
- );
- return false;
- }
- // Check if all with keys were fetched
- $missing = array_diff(array_keys($params['with']), array_keys(reset($data)));
- if (!empty($missing)) {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR, 'exception',
- array('msg' => 'The following "with" elements are not included in the result: '.implode(', ', $missing))
- );
- return false;
- }
- foreach ($data as $key => $row) {
- foreach ($params['with'] as $field => $with_params) {
- $with_params['filters'][$field] = $row[$field];
- $method = $this->withFieldMethodMap[$field];
- // remove "_id" from the field name (group_id => group)
- $data_key = preg_replace('/(.+)_id/', '\\1s', $field);
- $data[$key][$data_key] = $this->$method($with_params);
- }
- }
- }
-
- return $data;
- }
-
- /**
- * Fetches users
- *
- * @param array containing key-value pairs for:
- * 'fields' - ordered array containing the fields to fetch
- * if empty all fields from the user table are fetched
- * 'filters' - key values pairs (value may be a string or an array)
- * 'orders' - key value pairs (values 'ASC' or 'DESC')
- * 'rekey' - if set to true, returned array will have the
- * first column as its first dimension
- * 'group' - if set to true and $rekey is set to true, then
- * all values with the same first column will be
- * wrapped in an array
- * 'limit' - number of rows to select
- * 'offset' - first row to select
- * 'select' - determines what query method to use:
- * 'one' -> queryOne, 'row' -> queryRow,
- * 'col' -> queryCol, 'all' ->queryAll (default)
- * 'selectable_tables' - array list of tables that may be
- * joined to in this query, the first element is
- * the root table from which the joins are done
- * @return bool|array false on failure or array with selected data
- *
- * @access public
- */
- function getUsers($params = array())
- {
- $selectable_tables = $this->_findSelectableTables('getUsers', $params);
- $root_table = reset($selectable_tables);
-
- return $this->_makeGet($params, $root_table, $selectable_tables);
- }
-
- /**
- * Fetches rights
- *
- * @param array containing key-value pairs for:
- * 'fields' - ordered array containing the fields to fetch
- * if empty all fields from the user table are fetched
- * 'filters' - key values pairs (value may be a string or an array)
- * 'orders' - key value pairs (values 'ASC' or 'DESC')
- * 'rekey' - if set to true, returned array will have the
- * first column as its first dimension
- * 'group' - if set to true and $rekey is set to true, then
- * all values with the same first column will be
- * wrapped in an array
- * 'limit' - number of rows to select
- * 'offset' - first row to select
- * 'select' - determines what query method to use:
- * 'one' -> queryOne, 'row' -> queryRow,
- * 'col' -> queryCol, 'all' ->queryAll (default)
- * 'selectable_tables' - array list of tables that may be
- * joined to in this query, the first element is
- * the root table from which the joins are done
- * @return bool|array false on failure or array with selected data
- *
- * @access public
- */
- function getRights($params = array())
- {
- $selectable_tables = $this->_findSelectableTables('getRights' , $params);
- $root_table = reset($selectable_tables);
-
- return $this->_makeGet($params, $root_table, $selectable_tables);
- }
-
- /**
- * Fetches areas
- *
- * @param array containing key-value pairs for:
- * 'fields' - ordered array containing the fields to fetch
- * if empty all fields from the user table are fetched
- * 'filters' - key values pairs (value may be a string or an array)
- * 'orders' - key value pairs (values 'ASC' or 'DESC')
- * 'rekey' - if set to true, returned array will have the
- * first column as its first dimension
- * 'group' - if set to true and $rekey is set to true, then
- * all values with the same first column will be
- * wrapped in an array
- * 'limit' - number of rows to select
- * 'offset' - first row to select
- * 'select' - determines what query method to use:
- * 'one' -> queryOne, 'row' -> queryRow,
- * 'col' -> queryCol, 'all' ->queryAll (default)
- * 'selectable_tables' - array list of tables that may be
- * joined to in this query, the first element is
- * the root table from which the joins are done
- * @return bool|array false on failure or array with selected data
- *
- * @access public
- */
- function getAreas($params = array())
- {
- $selectable_tables = $this->_findSelectableTables('getAreas' , $params);
- $root_table = reset($selectable_tables);
-
- return $this->_makeGet($params, $root_table, $selectable_tables);
- }
-
- /**
- * Fetches applications
- *
- * @param array containing key-value pairs for:
- * 'fields' - ordered array containing the fields to fetch
- * if empty all fields from the user table are fetched
- * 'filters' - key values pairs (value may be a string or an array)
- * 'orders' - key value pairs (values 'ASC' or 'DESC')
- * 'rekey' - if set to true, returned array will have the
- * first column as its first dimension
- * 'group' - if set to true and $rekey is set to true, then
- * all values with the same first column will be
- * wrapped in an array
- * 'limit' - number of rows to select
- * 'offset' - first row to select
- * 'select' - determines what query method to use:
- * 'one' -> queryOne, 'row' -> queryRow,
- * 'col' -> queryCol, 'all' ->queryAll (default)
- * 'selectable_tables' - array list of tables that may be
- * joined to in this query, the first element is
- * the root table from which the joins are done
- * @return bool|array false on failure or array with selected data
- *
- * @access public
- */
- function getApplications($params = array())
- {
- $selectable_tables = $this->_findSelectableTables('getApplications' , $params);
- $root_table = reset($selectable_tables);
-
- return $this->_makeGet($params, $root_table, $selectable_tables);
- }
-
- /**
- * Fetches translations
- *
- * @param array containing key-value pairs for:
- * 'fields' - ordered array containing the fields to fetch
- * if empty all fields from the user table are fetched
- * 'filters' - key values pairs (value may be a string or an array)
- * 'orders' - key value pairs (values 'ASC' or 'DESC')
- * 'rekey' - if set to true, returned array will have the
- * first column as its first dimension
- * 'group' - if set to true and $rekey is set to true, then
- * all values with the same first column will be
- * wrapped in an array
- * 'limit' - number of rows to select
- * 'offset' - first row to select
- * 'select' - determines what query method to use:
- * 'one' -> queryOne, 'row' -> queryRow,
- * 'col' -> queryCol, 'all' ->queryAll (default)
- * 'selectable_tables' - array list of tables that may be
- * joined to in this query, the first element is
- * the root table from which the joins are done
- * @return bool|array false on failure or array with selected data
- *
- * @access public
- */
- function getTranslations($params = array())
- {
- $selectable_tables = $this->_findSelectableTables('getTranslations' , $params);
- $root_table = reset($selectable_tables);
-
- return $this->_makeGet($params, $root_table, $selectable_tables);
- }
-
- /**
- * Generate the constants to a file or define them directly.
- *
- * $type can be either 'constant' or 'array'. Constant will result in
- * defining constants while array results in defining an array.
- *
- * $options can contain
- * 'prefix' => prefix for the generated (qualified) names
- * 'area' => specific area id to grab rights from
- * 'application' => specific application id to grab rights from
- * 'filters' => specific set of filters to use (overwrites area/application)
- * 'by_group' => if joins should be done using the 'userrights' (false default)
- * or through the 'grouprights' and 'groupusers' tables (true)
- * 'inherited' => filter array to fetch all rights from (sub)group membership
- * 'implied' => filter array for fetching implied rights
- * 'naming' => LIVEUSER_SECTION_RIGHT for PREFIX_RIGHTNAME <- DEFAULT
- * LIVEUSER_SECTION_AREA for PREFIX_AREANAME_RIGHTNAME
- * LIVEUSER_SECTION_APPLICATION for PREFIX_APPLICATIONNAME_AREANAME_RIGHTNAME
- * 'filename' => if $mode is 'file' you must give the full path for the
- * output file
- * 'varname' => if $mode is 'file' and $type is 'array' you must give
- * the name of the variable to define
- *
- * If no prefix is given it will not be used to generate the constants/arrays
- *
- * $mode can either be 'file' or 'direct' and will determine of the
- * constants/arrays will be written to a file, or returned/defined.
- * returned as an array when $type is set to 'array' and defined when $type
- * is set to 'constant'
- *
- * @param string type of output ('constant' or 'array')
- * @param array options for constants generation
- * @param string output mode desired ('file' or 'direct')
- * @return bool|array depending on the type an array with the data or
- * a boolean denoting success or failure
- *
- * @access public
- */
- function outputRightsConstants($type, $options = array(), $mode = null)
- {
- $params = array();
-
- // Prepare the fields to fetch.
- $params['fields'] = array('right_id', 'right_define_name');
-
- $naming = LIVEUSER_SECTION_RIGHT;
- if (array_key_exists('naming', $options)) {
- $naming = $options['naming'];
- switch ($naming) {
- case LIVEUSER_SECTION_AREA:
- $params['fields'][] = 'area_define_name';
- break;
- case LIVEUSER_SECTION_APPLICATION:
- $params['fields'][] = 'application_define_name';
- $params['fields'][] = 'area_define_name';
- break;
- }
- }
-
- // Prepare the filters.
- if (array_key_exists('by_group', $options)) {
- $params['by_group'] = $options['by_group'];
- }
-
- if (array_key_exists('inherited', $options)) {
- $params['inherited'] = $options['inherited'];
- }
-
- if (array_key_exists('implied', $options)) {
- $params['implied'] = $options['implied'];
- }
-
- if (array_key_exists('filters', $options)) {
- $params['filters'] = $options['filters'];
- } else {
- if (array_key_exists('area', $options)) {
- $params['filters']['area_id'] = $options['area'];
- }
-
- if (array_key_exists('application', $options)) {
- $params['filters']['application_id'] = $options['application'];
- }
- }
-
- $prefix = '';
- if (array_key_exists('prefix', $options)) {
- $prefix = $options['prefix'] . '_';
- }
-
- $rekey = false;
- if ($type == 'array' && array_key_exists('rekey', $options)) {
- $rekey = $options['rekey'];
- }
-
- $rights = $this->getRights($params);
-
- if ($rights === false) {
- return false;
- }
-
- $generate = array();
-
- // Prepare an array containing all the rights to be defined. The stucture of
- // this array is dependent on the value of naming and if the rekey is set.
- switch ($naming) {
- case LIVEUSER_SECTION_APPLICATION:
- if ($rekey) {
- foreach ($rights as $r) {
- $app_name = $prefix . $r['application_define_name'];
- $area_name = $r['area_define_name'];
- $generate[$app_name][$area_name][$r['right_define_name']] = $r['right_id'];
- }
- } else {
- foreach ($rights as $r) {
- $key = $prefix . $r['application_define_name'] . '_'
- . $r['area_define_name'] . '_' . $r['right_define_name'];
- $generate[$key] = $r['right_id'];
- }
- }
- break;
- case LIVEUSER_SECTION_AREA:
- if ($rekey) {
- foreach ($rights as $r) {
- $area_name = $prefix . $r['area_define_name'];
- $generate[$area_name][$r['right_define_name']] = $r['right_id'];
- }
- } else {
- foreach ($rights as $r) {
- $key = $prefix . $r['area_define_name'] . '_' . $r['right_define_name'];
- $generate[$key] = $r['right_id'];
- }
- }
- break;
- case LIVEUSER_SECTION_RIGHT:
- default:
- foreach ($rights as $r) {
- $generate[$prefix . $r['right_define_name']] = $r['right_id'];
- }
- break;
- }
-
- if ($type == 'array' && $mode != 'file') {
- return $generate;
- }
-
- // Define the rights, either as an array or defines.
- // Add an error to the stack if the provided variable name is not valid.
- if ($type == 'array') {
- if (!array_key_exists('varname', $options)
- || !preg_match('/^[a-zA-Z_0-9]+$/', $options['varname'])
- ) {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR_FILTER, 'exception',
- array('msg' => 'varname is not a valid variable name in PHP: '.$options['varname'])
- );
- return false;
- }
- $strDef = sprintf("\$%s = %s;\n", $options['varname'], var_export($generate, true));
- } else {
- if ($mode == 'file') {
- $strDef = '';
- }
- foreach ($generate as $v => $k) {
- if (!preg_match('/^[a-zA-Z_0-9]+$/', $v)) {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR_FILTER, 'exception',
- array('msg' => 'definename is not a valid define name in PHP: '.$v)
- );
- return false;
- }
- $v = strtoupper($v);
- if ($mode == 'file') {
- $strDef .= sprintf("define('%s', %s);\n", $v, $k);
- } elseif (!defined($v)) {
- define($v, $k);
- }
- }
- }
-
- if ($mode != 'file') {
- return true;
- }
-
- // The results should be written to a file.
- // If the filename doesn't exist or the file cannot be opened, add an error to the stack.
- if (!array_key_exists('filename', $options) || !$options['filename']) {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR_FILTER, 'exception',
- array('msg' => 'no filename is set for output mode file')
- );
- return false;
- }
-
- $fp = @fopen($options['filename'], 'wb');
-
- if (!$fp) {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR_FILTER, 'exception',
- array('msg' => 'file could not be opened: '.$options['filename'])
- );
- return false;
- }
-
- @fputs($fp, "<?php\n".$strDef.'?>');
- @fclose($fp);
-
- return true;
- }
-
- /**
- * properly disconnect from resources
- *
- * @access public
- */
- function disconnect()
- {
- $this->_storage->disconnect();
- }
-}
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * A framework for authentication and authorization in PHP applications
- *
- * LiveUser is an authentication/permission framework designed
- * to be flexible and easily extendable.
- *
- * Since it is impossible to have a
- * "one size fits all" it takes a container
- * approach which should enable it to
- * be versatile enough to meet most needs.
- *
- * PHP version 4 and 5
- *
- * LICENSE: This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library 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
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
- * MA 02111-1307 USA
- *
- *
- * @category authentication
- * @package LiveUser
- * @author Markus Wolff <wolff@21st.de>
- * @author Helgi Þormar Þorbjörnsson <dufuz@php.net>
- * @author Lukas Smith <smith@pooteeweet.org>
- * @author Arnaud Limbourg <arnaud@php.net>
- * @author Pierre-Alain Joye <pajoye@php.net>
- * @author Bjoern Kraus <krausbn@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version CVS: $Id: Storage.php,v 1.1.1.1 2008/04/28 15:20:46 jamie Exp $
- * @link http://pear.php.net/LiveUser
- */
-
-/**
- * Abstraction class for all the storage containers
- *
- * @category authentication
- * @package LiveUser
- * @author Lukas Smith <smith@pooteeweet.org>
- * @author Bjoern Kraus <krausbn@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version Release: @package_version@
- * @link http://pear.php.net/LiveUser
- */
-class LiveUser_Perm_Storage
-{
- /**
- * Table configuration
- *
- * @var array
- * @access public
- */
- var $tables = array();
-
- /**
- * All fields with their types
- *
- * @var array
- * @access public
- */
- var $fields = array();
-
- /**
- * All fields with their alias
- *
- * @var array
- * @access public
- */
- var $alias = array();
-
- /**
- * Constructor
- *
- * @access protected
- * @param mixed configuration array
- * @return void
- */
- function LiveUser_Perm_Storage()
- {
- $this->stack = &PEAR_ErrorStack::singleton('LiveUser');
- }
-
- /**
- * Initialize the storage container
- *
- * @param array Array with the storage configuration
- * @return bool true on success, false on failure.
- *
- * @access public
- */
- function init(&$storageConf)
- {
- if (is_array($storageConf)) {
- $keys = array_keys($storageConf);
- foreach ($keys as $key) {
- if (isset($this->$key)) {
- $this->$key =& $storageConf[$key];
- }
- }
- }
-
- require_once 'LiveUser/Perm/Storage/Globals.php';
- if (empty($this->tables)) {
- $this->tables = $GLOBALS['_LiveUser']['perm']['tables'];
- } else {
- $this->tables = LiveUser::arrayMergeClobber($GLOBALS['_LiveUser']['perm']['tables'], $this->tables);
- }
- if (empty($this->fields)) {
- $this->fields = $GLOBALS['_LiveUser']['perm']['fields'];
- } else {
- $this->fields = LiveUser::arrayMergeClobber($GLOBALS['_LiveUser']['perm']['fields'], $this->fields);
- }
- if (empty($this->alias)) {
- $this->alias = $GLOBALS['_LiveUser']['perm']['alias'];
- } else {
- $this->alias = LiveUser::arrayMergeClobber($GLOBALS['_LiveUser']['perm']['alias'], $this->alias);
- }
-
- return true;
- }
-
- /**
- * map an auth user to a perm user
- *
- * @param int $auth_user_id
- * @param string $containerName
- * @return array requested data or false on failure
- *
- * @access public
- */
- function mapUser($auth_user_id, $containerName)
- {
- $this->stack->push(LIVEUSER_ERROR, 'error', array(),
- __METHOD__.' is not implemented');
- return false;
- }
-
- /**
- * Reads all rights of current user into a
- * two-dimensional associative array, having the
- * area names as the key of the 1st dimension.
- * Group rights and invididual rights are being merged
- * in the process.
- *
- * @param int perm user id
- * @return array requested data or false on failure
- *
- * @access public
- */
- function readUserRights($perm_user_id)
- {
- $this->stack->push(LIVEUSER_ERROR, 'error', array(),
- __METHOD__.' is not implemented');
- return false;
- }
-
- /**
- * read the areas in which a user is an area admin
- *
- * @param int perm user id
- * @return array requested data or false on failure
- *
- * @access public
- */
- function readAreaAdminAreas($perm_user_id)
- {
- $this->stack->push(LIVEUSER_ERROR, 'error', array(),
- __METHOD__.' is not implemented');
- return false;
- }
-
- /**
- * Reads all the group ids in that the user is also a member of
- * (all groups that are subgroups of these are also added recursively)
- *
- * @param int perm user id
- * @return array requested data or false on failure
- *
- * @see readRights()
- * @access public
- */
- function readGroups($perm_user_id)
- {
- $this->stack->push(LIVEUSER_ERROR, 'error', array(),
- __METHOD__.' is not implemented');
- return false;
- }
-
- /**
- * Reads the group rights
- * and put them in the array
- *
- * right => 1
- *
- * @param int group ids
- * @return array requested data or false on failure
- *
- * @access public
- */
- function readGroupRights($group_ids)
- {
- $this->stack->push(LIVEUSER_ERROR, 'error', array(),
- __METHOD__.' is not implemented');
- return false;
- }
-
- /**
- * Read the sub groups of the new groups that are not part of the group ids
- *
- * @param array group ids
- * @param array new group ids
- * @return array requested data or false on failure
- *
- * @access public
- */
- function readSubGroups($group_ids, $newGroupIds)
- {
- $this->stack->push(LIVEUSER_ERROR, 'error', array(),
- __METHOD__.' is not implemented');
- return false;
- }
-
- /**
- * Read out the rights from the userrights or grouprights table
- * that imply other rights along with their level
- *
- * @param array right ids
- * @param string name of the table
- * @return array requested data or false on failure
- *
- * @access public
- */
- function readImplyingRights($rightIds, $table)
- {
- $this->stack->push(LIVEUSER_ERROR, 'error', array(),
- __METHOD__.' is not implemented');
- return false;
- }
-
- /**
- * Read out the implied rights with a given level from the implied_rights table
- *
- * @param array current right ids
- * @param string current level
- * @return array requested data or false on failure
- *
- * @access public
- */
- function readImpliedRights($currentRights, $currentLevel)
- {
- $this->stack->push(LIVEUSER_ERROR, 'error', array(),
- __METHOD__.' is not implemented');
- return false;
- }
-
- /**
- * store all properties in the session and return them as an array
- *
- * @param string name of the key to use inside the session
- * @param array property values
- * @return array containing the property values
- *
- * @access public
- */
- function freeze($sessionName, $propertyValues)
- {
- $_SESSION[$sessionName]['perm'] = $propertyValues;
- return $propertyValues;
- }
-
- /**
- * Reinitializes properties
- *
- * @param string name of the key to use inside the session
- * @return array
- *
- * @access public
- */
- function unfreeze($sessionName)
- {
- return (array_key_exists('perm', $_SESSION[$sessionName])
- && is_array($_SESSION[$sessionName]['perm']))
- ? $_SESSION[$sessionName]['perm'] : array();
- }
-
- /**
- * properly disconnect from resources
- *
- * @return bool true on success and false on failure
- *
- * @access public
- */
- function disconnect()
- {
- }
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * A framework for authentication and authorization in PHP applications
- *
- * LiveUser_Admin is meant to be used with the LiveUser package.
- * It is composed of all the classes necessary to administrate
- * data used by LiveUser.
- *
- * You'll be able to add/edit/delete/get things like:
- * * Rights
- * * Users
- * * Groups
- * * Areas
- * * Applications
- * * Subgroups
- * * ImpliedRights
- *
- * And all other entities within LiveUser.
- *
- * At the moment we support the following storage containers:
- * * DB
- * * MDB
- * * MDB2
- *
- * But it takes no time to write up your own storage container,
- * so if you like to use native mysql functions straight, then it's possible
- * to do so in under a hour!
- *
- * PHP version 4 and 5
- *
- * LICENSE: This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library 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
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
- * MA 02111-1307 USA
- *
- *
- * @category authentication
- * @package LiveUser_Admin
- * @author Markus Wolff <wolff@21st.de>
- * @author Helgi Þormar Þorbjörnsson <dufuz@php.net>
- * @author Lukas Smith <smith@pooteeweet.org>
- * @author Arnaud Limbourg <arnaud@php.net>
- * @author Christian Dickmann <dickmann@php.net>
- * @author Matt Scifo <mscifo@php.net>
- * @author Bjoern Kraus <krausbn@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version CVS: $Id: DB.php,v 1.1.1.1 2008/04/28 15:20:46 jamie Exp $
- * @link http://pear.php.net/LiveUser_Admin
- */
-
-/**
- * Require parent class definition.
- */
-require_once 'LiveUser/Admin/Storage/DB.php';
-
-/**
- * This is a PEAR::DB backend storage driver for the LiveUser_Admin perm class.
- * All it does is read the Globals.php file and the container and database config on
- *
- * @category authentication
- * @package LiveUser_Admin
- * @permor Lukas Smith <smith@pooteeweet.org>
- * @permor Bjoern Kraus <krausbn@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version Release: @package_version@
- * @link http://pear.php.net/LiveUser_Admin
- */
-class LiveUser_Admin_Perm_Storage_DB extends LiveUser_Admin_Storage_DB
-{
- /**
- * Initializes database storage container.
- *
- * @param array Storage Configuration
- * @return void
- *
- * @access public
- * @uses LiveUser_Admin_Storage_DB::init
- */
- function init(&$storageConf)
- {
- require_once 'LiveUser/Perm/Storage/Globals.php';
- parent::init($storageConf, $GLOBALS['_LiveUser']['perm']);
- }
-}
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * A framework for authentication and authorization in PHP applications
- *
- * LiveUser is an authentication/permission framework designed
- * to be flexible and easily extendable.
- *
- * Since it is impossible to have a
- * "one size fits all" it takes a container
- * approach which should enable it to
- * be versatile enough to meet most needs.
- *
- * PHP version 4 and 5
- *
- * LICENSE: This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library 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
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
- * MA 02111-1307 USA
- *
- *
- * @category authentication
- * @package LiveUser
- * @author Markus Wolff <wolff@21st.de>
- * @author Helgi Þormar Þorbjörnsson <dufuz@php.net>
- * @author Lukas Smith <smith@pooteeweet.org>
- * @author Arnaud Limbourg <arnaud@php.net>
- * @author Pierre-Alain Joye <pajoye@php.net>
- * @author Bjoern Kraus <krausbn@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version CVS: $Id: Globals.php,v 1.1.1.1 2008/04/28 15:20:46 jamie Exp $
- * @link http://pear.php.net/LiveUser
- */
-
-
-/**
- * This file holds all our default table/fields name/types/relations,
- * if they should be checked and more which are needed by both
- * LiveUser and LiveUser_Admin
- *
- * You can add to those table or modify options via our table/field
- * options in the config.
- */
-
-$GLOBALS['_LiveUser']['perm']['tables'] = array(
- 'perm_users' => array(
- 'fields' => array(
- 'perm_user_id' => 'seq',
- 'auth_user_id' => 'auth_id',
- 'auth_container_name' => 'auth_id',
- 'perm_type' => false,
- ),
- 'joins' => array(
- 'userrights' => 'perm_user_id',
- 'groupusers' => 'perm_user_id',
- 'area_admin_areas' => 'perm_user_id',
- ),
- ),
- 'userrights' => array(
- 'fields' => array(
- 'perm_user_id' => 'id',
- 'right_id' => 'id',
- 'right_level' => false,
- ),
- 'joins' => array(
- 'perm_users' => 'perm_user_id',
- 'rights' => 'right_id',
- ),
- ),
- 'rights' => array(
- 'fields' => array(
- 'right_id' => 'seq',
- 'area_id' => 'define_name',
- 'right_define_name' => 'define_name',
- 'has_implied' => null,
- ),
- 'joins' => array(
- 'areas' => 'area_id',
- 'userrights' => 'right_id',
- 'grouprights' => 'right_id',
- 'right_implied' => array(
- 'right_id' => 'right_id',
- ),
- 'translations' => array(
- 'right_id' => 'section_id',
- LIVEUSER_SECTION_RIGHT => 'section_type',
- ),
- ),
- ),
- 'right_implied' => array(
- 'fields' => array(
- 'right_id' => 'id',
- 'implied_right_id' => 'id',
- ),
- 'joins' => array(
- 'rights' => array(
- 'right_id' => 'right_id',
- 'implied_right_id' => 'right_id',
- ),
- ),
- ),
- 'translations' => array(
- 'fields' => array(
- 'translation_id' => 'seq',
- 'section_id' => 'translation',
- 'section_type' => 'translation',
- 'language_id' => 'translation',
- 'name' => false,
- 'description' => null,
- ),
- 'joins' => array(
- 'rights' => array(
- 'section_id' => 'right_id',
- 'section_type' => LIVEUSER_SECTION_RIGHT,
- ),
- 'areas' => array(
- 'section_id' => 'area_id',
- 'section_type' => LIVEUSER_SECTION_AREA,
- ),
- 'applications' => array(
- 'section_id' => 'application_id',
- 'section_type' => LIVEUSER_SECTION_APPLICATION,
- ),
- 'groups' => array(
- 'section_id' => 'group_id',
- 'section_type' => LIVEUSER_SECTION_GROUP,
- ),
- ),
- ),
- 'areas' => array(
- 'fields' => array(
- 'area_id' => 'seq',
- 'application_id' => 'define_name',
- 'area_define_name' => 'define_name',
- ),
- 'joins' => array(
- 'rights' => 'area_id',
- 'applications' => 'application_id',
- 'translations' => array(
- 'area_id' => 'section_id',
- LIVEUSER_SECTION_AREA => 'section_type',
- ),
- 'area_admin_areas' => 'area_id',
- ),
- ),
- 'area_admin_areas' => array(
- 'fields' => array(
- 'area_id' => 'id',
- 'perm_user_id' => 'id',
- ),
- 'joins' => array(
- 'perm_users' => 'perm_user_id',
- 'areas' => 'area_id',
- )
- ),
- 'applications' => array(
- 'fields' => array(
- 'application_id' => 'seq',
- 'application_define_name' => 'define_name',
- ),
- 'joins' => array(
- 'areas' => 'application_id',
- 'translations' => array(
- 'application_id' => 'section_id',
- LIVEUSER_SECTION_APPLICATION => 'section_type',
- ),
- ),
- ),
- 'groups' => array(
- 'fields' => array(
- 'group_id' => 'seq',
- 'group_type' => false,
- 'group_define_name' => 'define_name',
- ),
- 'joins' => array(
- 'groupusers' => 'group_id',
- 'grouprights' => 'group_id',
- 'group_subgroups' => 'group_id',
- 'translations' => array(
- 'group_id' => 'section_id',
- LIVEUSER_SECTION_GROUP => 'section_type',
- ),
- ),
- ),
- 'groupusers' => array(
- 'fields' => array(
- 'perm_user_id' => 'id',
- 'group_id' => 'id',
- ),
- 'joins' => array(
- 'groups' => 'group_id',
- 'perm_users' => 'perm_user_id',
- 'grouprights' => 'group_id',
- ),
- ),
- 'grouprights' => array(
- 'fields' => array(
- 'group_id' => 'id',
- 'right_id' => 'id',
- 'right_level' => false,
- ),
- 'joins' => array(
- 'rights' => 'right_id',
- 'groups' => 'group_id',
- 'groupusers' => 'group_id',
- ),
- ),
- 'group_subgroups' => array(
- 'fields' => array(
- 'group_id' => 'id',
- 'subgroup_id' => 'id',
- ),
- 'joins' => array(
- 'groups' => 'group_id',
- ),
- ),
-);
-
-$GLOBALS['_LiveUser']['perm']['fields'] = array(
- 'perm_user_id' => 'integer',
- 'auth_user_id' => 'text',
- 'auth_container_name' => 'text',
- 'perm_type' => 'integer',
- 'right_id' => 'integer',
- 'right_level' => 'integer',
- 'area_id' => 'integer',
- 'application_id' => 'integer',
- 'right_define_name' => 'text',
- 'area_define_name' => 'text',
- 'application_define_name' => 'text',
- 'translation_id' => 'integer',
- 'section_id' => 'integer',
- 'section_type' => 'integer',
- 'name' => 'text',
- 'description' => 'text',
- 'language_id' => 'text',
- 'group_id' => 'integer',
- 'group_type' => 'integer',
- 'group_define_name' => 'text',
- 'has_implied' => 'boolean',
- 'implied_right_id' => 'integer',
- 'subgroup_id' => 'integer'
-);
-
-$GLOBALS['_LiveUser']['perm']['alias'] = array(
- 'perm_user_id' => 'perm_user_id',
- 'auth_user_id' => 'auth_user_id',
- 'auth_container_name' => 'auth_container_name',
- 'perm_type' => 'perm_type',
- 'right_id' => 'right_id',
- 'right_level' => 'right_level',
- 'area_id' => 'area_id',
- 'application_id' => 'application_id',
- 'right_define_name' => 'right_define_name',
- 'area_define_name' => 'area_define_name',
- 'application_define_name' => 'application_define_name',
- 'translation_id' => 'translation_id',
- 'section_id' => 'section_id',
- 'section_type' => 'section_type',
- 'name' => 'name',
- 'description' => 'description',
- 'language_id' => 'language_id',
- 'group_id' => 'group_id',
- 'group_type' => 'group_type',
- 'group_define_name' => 'group_define_name',
- 'has_implied' => 'has_implied',
- 'implied_right_id' => 'implied_right_id',
- 'subgroup_id' => 'subgroup_id',
- 'perm_users' => 'perm_users',
- 'userrights' => 'userrights',
- 'applications' => 'applications',
- 'areas' => 'areas',
- 'area_admin_areas' => 'area_admin_areas',
- 'rights' => 'rights',
- 'groups' => 'groups',
- 'groupusers' => 'groupusers',
- 'grouprights' => 'grouprights',
- 'right_implied' => 'right_implied',
- 'group_subgroups' => 'group_subgroups',
- 'translations' => 'translations',
-);
-
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * A framework for authentication and authorization in PHP applications
- *
- * LiveUser_Admin is meant to be used with the LiveUser package.
- * It is composed of all the classes necessary to administrate
- * data used by LiveUser.
- *
- * You'll be able to add/edit/delete/get things like:
- * * Rights
- * * Users
- * * Groups
- * * Areas
- * * Applications
- * * Subgroups
- * * ImpliedRights
- *
- * And all other entities within LiveUser.
- *
- * At the moment we support the following storage containers:
- * * DB
- * * MDB
- * * MDB2
- *
- * But it takes no time to write up your own storage container,
- * so if you like to use native mysql functions straight, then it's possible
- * to do so in under a hour!
- *
- * PHP version 4 and 5
- *
- * LICENSE: This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library 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
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
- * MA 02111-1307 USA
- *
- *
- * @category authentication
- * @package LiveUser_Admin
- * @author Markus Wolff <wolff@21st.de>
- * @author Helgi Þormar Þorbjörnsson <dufuz@php.net>
- * @author Lukas Smith <smith@pooteeweet.org>
- * @author Arnaud Limbourg <arnaud@php.net>
- * @author Christian Dickmann <dickmann@php.net>
- * @author Matt Scifo <mscifo@php.net>
- * @author Bjoern Kraus <krausbn@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version CVS: $Id: MDB.php,v 1.1.1.1 2008/04/28 15:20:46 jamie Exp $
- * @link http://pear.php.net/LiveUser_Admin
- */
-
-
-/**
- * Require parent class definition.
- */
-require_once 'LiveUser/Admin/Storage/MDB.php';
-
-/**
- * This is a PEAR::MDB backend storage driver for the LiveUser_Admin perm class.
- * All it does is read the Globals.php file and the container and database config on
- *
- * @category authentication
- * @package LiveUser_Admin
- * @permor Lukas Smith <smith@pooteeweet.org>
- * @permor Bjoern Kraus <krausbn@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version Release: @package_version@
- * @link http://pear.php.net/LiveUser_Admin
- */
-class LiveUser_Admin_Perm_Storage_MDB extends LiveUser_Admin_Storage_MDB
-{
- /**
- * Initializes database storage container.
- *
- * @param array Storage Configuration
- * @return void
- *
- * @access public
- * @uses LiveUser_Admin_Storage_DB::init
- */
- function init(&$storageConf)
- {
- require_once 'LiveUser/Perm/Storage/Globals.php';
- parent::init($storageConf, $GLOBALS['_LiveUser']['perm']);
- }
-}
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * A framework for authentication and authorization in PHP applications
- *
- * LiveUser_Admin is meant to be used with the LiveUser package.
- * It is composed of all the classes necessary to administrate
- * data used by LiveUser.
- *
- * You'll be able to add/edit/delete/get things like:
- * * Rights
- * * Users
- * * Groups
- * * Areas
- * * Applications
- * * Subgroups
- * * ImpliedRights
- *
- * And all other entities within LiveUser.
- *
- * At the moment we support the following storage containers:
- * * DB
- * * MDB
- * * MDB2
- *
- * But it takes no time to write up your own storage container,
- * so if you like to use native mysql functions straight, then it's possible
- * to do so in under a hour!
- *
- * PHP version 4 and 5
- *
- * LICENSE: This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library 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
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
- * MA 02111-1307 USA
- *
- *
- * @category authentication
- * @package LiveUser_Admin
- * @author Markus Wolff <wolff@21st.de>
- * @author Helgi Þormar Þorbjörnsson <dufuz@php.net>
- * @author Lukas Smith <smith@pooteeweet.org>
- * @author Arnaud Limbourg <arnaud@php.net>
- * @author Christian Dickmann <dickmann@php.net>
- * @author Matt Scifo <mscifo@php.net>
- * @author Bjoern Kraus <krausbn@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version CVS: $Id: MDB2.php,v 1.1.1.1 2008/04/28 15:20:46 jamie Exp $
- * @link http://pear.php.net/LiveUser_Admin
- */
-
-
-/**
- * Require parent class definition.
- */
-require_once 'LiveUser/Admin/Storage/MDB2.php';
-
-/**
- * This is a PEAR::MDB2 backend storage driver for the LiveUser_Admin perm class.
- * All it does is read the Globals.php file and the container and database config on
- *
- * @category authentication
- * @package LiveUser_Admin
- * @permor Lukas Smith <smith@pooteeweet.org>
- * @permor Bjoern Kraus <krausbn@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version Release: @package_version@
- * @link http://pear.php.net/LiveUser_Admin
- */
-class LiveUser_Admin_Perm_Storage_MDB2 extends LiveUser_Admin_Storage_MDB2
-{
- /**
- * Initializes database storage container.
- *
- * @param array Storage Configuration
- * @return void
- *
- * @access public
- * @uses LiveUser_Admin_Storage_DB::init
- */
- function init(&$storageConf)
- {
- require_once 'LiveUser/Perm/Storage/Globals.php';
- parent::init($storageConf, $GLOBALS['_LiveUser']['perm']);
- }
-}
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * A framework for authentication and authorization in PHP applications
- *
- * LiveUser_Admin is meant to be used with the LiveUser package.
- * It is composed of all the classes necessary to administrate
- * data used by LiveUser.
- *
- * You'll be able to add/edit/delete/get things like:
- * * Rights
- * * Users
- * * Groups
- * * Areas
- * * Applications
- * * Subgroups
- * * ImpliedRights
- *
- * And all other entities within LiveUser.
- *
- * At the moment we support the following storage containers:
- * * DB
- * * MDB
- * * MDB2
- *
- * But it takes no time to write up your own storage container,
- * so if you like to use native mysql functions straight, then it's possible
- * to do so in under a hour!
- *
- * PHP version 4 and 5
- *
- * LICENSE: This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library 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
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
- * MA 02111-1307 USA
- *
- *
- * @category authentication
- * @package LiveUser_Admin
- * @author Markus Wolff <wolff@21st.de>
- * @author Helgi Þormar Þorbjörnsson <dufuz@php.net>
- * @author Lukas Smith <smith@pooteeweet.org>
- * @author Arnaud Limbourg <arnaud@php.net>
- * @author Christian Dickmann <dickmann@php.net>
- * @author Matt Scifo <mscifo@php.net>
- * @author Bjoern Kraus <krausbn@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version CVS: $Id: PDO.php,v 1.1.1.1 2008/04/28 15:20:46 jamie Exp $
- * @link http://pear.php.net/LiveUser_Admin
- */
-
-/**
- * Require parent class definition.
- */
-require_once 'LiveUser/Admin/Storage/PDO.php';
-
-/**
- * This is a PECL::PDO backend storage driver for the LiveUser_Admin perm class.
- * All it does is read the Globals.php file and the container and database config on
- *
- * @category authentication
- * @package LiveUser_Admin
- * @permor Lukas Smith <smith@pooteeweet.org>
- * @permor Bjoern Kraus <krausbn@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version Release: @package_version@
- * @link http://pear.php.net/LiveUser_Admin
- */
-class LiveUser_Admin_Perm_Storage_PDO extends LiveUser_Admin_Storage_PDO
-{
- /**
- * Initializes database storage container.
- *
- * @param array Storage Configuration
- * @return void
- *
- * @access public
- * @uses LiveUser_Admin_Storage_PDO::init
- */
- function init(&$storageConf)
- {
- require_once 'LiveUser/Perm/Storage/Globals.php';
- parent::init($storageConf, $GLOBALS['_LiveUser']['perm']);
- }
-}
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * A framework for authentication and authorization in PHP applications
- *
- * LiveUser is an authentication/permission framework designed
- * to be flexible and easily extendable.
- *
- * Since it is impossible to have a
- * "one size fits all" it takes a container
- * approach which should enable it to
- * be versatile enough to meet most needs.
- *
- * PHP version 4 and 5
- *
- * LICENSE: This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library 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
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
- * MA 02111-1307 USA
- *
- *
- * @category authentication
- * @package LiveUser
- * @author Markus Wolff <wolff@21st.de>
- * @author Helgi Þormar Þorbjörnsson <dufuz@php.net>
- * @author Lukas Smith <smith@pooteeweet.org>
- * @author Arnaud Limbourg <arnaud@php.net>
- * @author Pierre-Alain Joye <pajoye@php.net>
- * @author Bjoern Kraus <krausbn@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version CVS: $Id: SQL.php,v 1.1.1.1 2008/04/28 15:20:46 jamie Exp $
- * @link http://pear.php.net/LiveUser
- */
-
-/**
- * Require parent class definition.
- */
-require_once 'LiveUser/Perm/Storage.php';
-
-/**
- * SQL container for permission handling
- *
- * @category authentication
- * @package LiveUser
- * @author Lukas Smith <smith@pooteeweet.org>
- * @author Bjoern Kraus <krausbn@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version Release: @package_version@
- * @link http://pear.php.net/LiveUser
- */
-class LiveUser_Perm_Storage_SQL extends LiveUser_Perm_Storage
-{
- /**
- * dsn that was connected to
- * @var string
- * @access private
- */
- var $dsn = false;
-
- /**
- * instance of the database backend object.
- *
- * @var object
- * @access private
- */
- var $dbc = false;
-
- /**
- * Database connection options.
- *
- * @var object
- * @access private
- */
- var $options = array();
-
- /**
- * Table prefix
- * Prefix for all db tables the container has.
- *
- * @var string
- * @access public
- */
- var $prefix = 'liveuser_';
-
- /**
- * properly disconnect from resources
- *
- * @return bool true on success and false on failure
- *
- * @access public
- */
- function disconnect()
- {
- if ($this->dsn) {
- $result = $this->dbc->disconnect();
- if (PEAR::isError($result)) {
- $this->stack->push(
- LIVEUSER_ERROR, 'exception',
- array('reason' => $result->getMessage() . '-' . $result->getUserInfo())
- );
- return false;
- }
- $this->dbc = false;
- }
- return true;
- }
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * A framework for authentication and authorization in PHP applications
- *
- * LiveUser is an authentication/permission framework designed
- * to be flexible and easily extendable.
- *
- * Since it is impossible to have a
- * "one size fits all" it takes a container
- * approach which should enable it to
- * be versatile enough to meet most needs.
- *
- * PHP version 4 and 5
- *
- * LICENSE: This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library 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
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
- * MA 02111-1307 USA
- *
- *
- * @category authentication
- * @package LiveUser
- * @author Markus Wolff <wolff@21st.de>
- * @author Helgi Þormar Þorbjörnsson <dufuz@php.net>
- * @author Lukas Smith <smith@pooteeweet.org>
- * @author Arnaud Limbourg <arnaud@php.net>
- * @author Pierre-Alain Joye <pajoye@php.net>
- * @author Bjoern Kraus <krausbn@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version CVS: $Id: XML.php,v 1.1.1.1 2008/04/28 15:20:46 jamie Exp $
- * @link http://pear.php.net/LiveUser
- */
-
-/**
- * Require parent class definition.
- */
-require_once 'LiveUser/Perm/Storage.php';
-require_once 'XML/Tree.php';
-
-/**
- * XML container for permission handling
- *
- * This is a XML backend driver for the LiveUser class.
- *
- * Requirements:
- * - File "Liveuser.php" (contains the parent class "LiveUser")
- * - XML_Parser
- *
- * @category authentication
- * @package LiveUser
- * @author Lukas Smith <smith@pooteeweet.org>
- * @author Bjoern Kraus <krausbn@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version Release: @package_version@
- * @link http://pear.php.net/LiveUser
- */
-class LiveUser_Perm_Storage_XML extends LiveUser_Perm_Storage
-{
- /**
- * XML file in which the auth data is stored.
- *
- * @var string
- * @access private
- */
- var $file = '';
-
- /**
- * XML::Tree object.
- *
- * @var XML_Tree
- * @access private
- */
- var $tree = null;
-
- /**
- * XML::Tree object of the user logged in.
- *
- * @var XML_Tree
- *
- * @access private
- * @see readUserData()
- */
- var $userObj = null;
-
- /**
- * Initialize the storage container
- *
- * @param array Array with the storage configuration
- * @return bool true on success, false on failure.
- *
- * @access public
- */
- function init(&$storageConf)
- {
- parent::init($storageConf);
-
- if (!is_file($this->file)) {
- if (!is_file(getenv('DOCUMENT_ROOT') . $this->file)) {
- $this->stack->push(LIVEUSER_ERROR_MISSING_DEPS, 'exception', array(),
- "Perm initialisation failed. Can't find xml file.");
- return false;
- }
- $this->file = getenv('DOCUMENT_ROOT') . $this->file;
- }
-
- $tree =& new XML_Tree($this->file);
- $err =& $tree->getTreeFromFile();
- if (PEAR::isError($err)) {
- $this->stack->push(LIVEUSER_ERROR, 'exception', array(),
- "Perm initialisation failed. Can't get tree from file");
- return false;
- }
- $this->tree =& $tree;
-
- if (!is_a($this->tree, 'xml_tree')) {
- $this->stack->push(LIVEUSER_ERROR_INIT_ERROR, 'error',
- array('container' => 'storage layer configuration missing'));
- return false;
- }
-
- return true;
- }
-
- /**
- * map an auth user to a perm user
- *
- * @param int $auth_user_id
- * @param string $containerName
- * @return array requested data or false on failure
- *
- * @access public
- */
- function mapUser($auth_user_id, $containerName)
- {
- $nodeIndex = 0;
- $userIndex = 0;
-
- if (isset($this->tree->root->children) && is_array($this->tree->root->children)) {
- foreach ($this->tree->root->children as $node) {
- if ($node->name == 'users') {
- foreach ($node->children as $user) {
- if ($user->name == 'user'
- && $auth_user_id == $user->attributes['authUserId']
- && $containerName == $user->attributes['authContainerName']
- ) {
- $result['perm_user_id'] = $user->attributes['userId'];
- $result['perm_type'] = $user->attributes['type'];
- $this->userObj =& $this->tree->root->getElement(array($nodeIndex, $userIndex));
- return $result;
- }
- $userIndex++;
- }
- }
- $nodeIndex++;
- }
- }
-
- return false;
- }
-
- /**
- * Reads all rights of current user into a
- * two-dimensional associative array, having the
- * area names as the key of the 1st dimension.
- * Group rights and invididual rights are being merged
- * in the process.
- *
- * @param int perm user id
- * @return array requested data or false on failure
- *
- * @access public
- */
- function readUserRights($perm_user_id)
- {
- $result = array();
-
- foreach ($this->userObj->children as $node) {
- if ($node->name == 'rights') {
- $tmp = explode(',', $node->content);
- foreach ($tmp as $value) {
- $level = LIVEUSER_MAX_LEVEL;
- // level syntax: 10(2) => right id 10 at level 2
- $match = array();
- if (preg_match('/(\d+)\((\d+)\)/', $value, $match)) {
- $value = $match[1];
- $level = $match[2];
- }
- $result[$value] = $level;
- }
- }
- }
-
- return $result;
- }
-
- /**
- * properly disconnect from resources
- *
- * @return bool true on success and false on failure
- *
- * @access public
- */
- function disconnect()
- {
- $this->tree = null;
- $this->userObj = null;
- return true;
- }
-}
-?>
\ No newline at end of file
+++ /dev/null
-03 July 2004
-
-TODO
- * Session fixation attack (BUG #2021)
- * Fix multiple open windows and challenge responce cookies (use a list of cookies which are allowed)
-
-Since Auth 1.3 new security functionality has been added.
-The main purpose for these advanced security checks is to avoid man-in-the-middle attacks and
-session hijacking.
-
-
-Session hijacking example
- - Login to an Auth protected page. Write down the session id (should be something like PHPSESSID=36916b0aa1180386010f304b6160e3e8)
- - Open a different browser (FireFox <> IE), or a browser on a different computer
- - Type down the address of the secure page and add ?PHPSESSID=36916b0aa1180386010f304b6160e3e8 where
- PHPSESSID is the php session name and 36916b0aa1180386010f304b6160e3e8 is the valid session id which you wrote down earlier
- - You should be logged in with the same creditentials
-
-
-
-To enable the advanced scurity checks you have to call
-$auth->setAdvancedSecurity();
-
-If this has been enabled the following security checks will be performed
-
- - Login screen will use md5 when submitting the password if java script is enabled in the browser
- - If user ip address has been changed betwin requests the user will be logged out
- - If user User-Agent string has been changed the user will be logged out
- - If user does not provide a valid auth challenge cookied he will be logged out (read below for explanation)
-
-Limitations
- * Challenge responce cookies would not allow a user to open multiple windows of the same page (Open in new window/tab). If
- the user accesses the protected area from two browser windows he will be logged out. It can also create a problem if you
- create dynamic images with php and that code passes through the auth layer. One way to avoid it is to disable advanced security for
- those pages only selectively.
- * Password saving does not work with login screens which use challenge responce (md5 hashing) of password
- * Challenge responce on login only works with DB container and plain or md5 hashing
-
-
-
-
-Challenge Responce cookies
-
-
- The challenge responce cookies provide a way to avoid most of the session hijacking problems. Since User-Agent headers
- and IP address can be spoofed, or in the case of IP a proxy can be used an extra security step has been added using a
- challenge cookie.
-
- After the user is authenthicated by Auth he is presented with a challenge cookie. For his next request to be succesfull
- he must present that cookie on his next request. If that is successfull he will be presented with a new
- challenge cookie. This will be reapeated for each request the user makes.
-
- While this method is not fool proof it does limit the possibilities for an attack.
- First the attacker must must obtain the challenge cookie and use it before the user does.
- If the user makes a request after the attacker the session will be logged out and both of them
- will need to login again.
-
- A problem which this scheme does not address well is users leaving their sessions without preforming a logout
- in this case the attacker is free to abuse the user session (provided he has met all the prerequisites).
-
- Ideas and sujestions for improvements are more than welcome.
- send to yavo@siava.org
-
+++ /dev/null
-The documentation for PEAR::Auth is available at
-
- http://pear.php.net/manual/
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * A framework for authentication and authorization in PHP applications
- *
- * LiveUser_Admin is meant to be used with the LiveUser package.
- * It is composed of all the classes necessary to administrate
- * data used by LiveUser.
- *
- * You'll be able to add/edit/delete/get things like:
- * * Rights
- * * Users
- * * Groups
- * * Areas
- * * Applications
- * * Subgroups
- * * ImpliedRights
- *
- * And all other entities within LiveUser.
- *
- * At the moment we support the following storage containers:
- * * DB
- * * MDB
- * * MDB2
- *
- * But it takes no time to write up your own storage container,
- * so if you like to use native mysql functions straight, then it's possible
- * to do so in under a hour!
- *
- * PHP version 4 and 5
- *
- * LICENSE: This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library 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
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
- * MA 02111-1307 USA
- *
- *
- * @category authentication
- * @package LiveUser_Admin
- * @author Markus Wolff <wolff@21st.de>
- * @author Helgi Þormar Þorbjörnsson <dufuz@php.net>
- * @author Lukas Smith <smith@pooteeweet.org>
- * @author Arnaud Limbourg <arnaud@php.net>
- * @author Christian Dickmann <dickmann@php.net>
- * @author Matt Scifo <mscifo@php.net>
- * @author Bjoern Kraus <krausbn@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version CVS: $Id: Storage.php,v 1.1.1.1 2008/04/28 15:20:46 jamie Exp $
- * @link http://pear.php.net/LiveUser_Admin
- */
-
-/**
- * This is core base class for all LiveUser admin storage classes that is meant
- * for internal use only.
- *
- * @category authentication
- * @package LiveUser_Admin
- * @author Lukas Smith <smith@pooteeweet.org>
- * @author Bjoern Kraus <krausbn@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version Release: @package_version@
- * @link http://pear.php.net/LiveUser_Admin
- */
-class LiveUser_Admin_Storage
-{
- /**
- * Table configuration
- *
- * @var array
- * @access public
- */
- var $tables = array();
-
- /**
- * All fields with their types
- *
- * @var array
- * @access public
- */
- var $fields = array();
-
- /**
- * All fields with their alias
- *
- * @var array
- * @access public
- */
- var $alias = array();
-
- /**
- * Constructor
- *
- * @access protected
- * @return void
- */
- function LiveUser_Admin_Storage()
- {
- $this->stack = &PEAR_ErrorStack::singleton('LiveUser_Admin');
- }
-
- /**
- * Initializes database storage container.
- * Goes through the storage config and turns each value into
- * a var
- *
- * @param array Storage Configuration
- * @param array containing the database structure (tables, fields, alias)
- * @return bool true on success and false on failure
- *
- * @access public
- */
- function init(&$storageConf, $structure)
- {
- if (is_array($storageConf)) {
- $keys = array_keys($storageConf);
- foreach ($keys as $key) {
- if (isset($this->$key)) {
- $this->$key =& $storageConf[$key];
- }
- }
- }
-
- if (empty($this->tables)) {
- $this->tables = $structure['tables'];
- } else {
- $this->tables = LiveUser::arrayMergeClobber($structure['tables'], $this->tables);
- }
- if (empty($this->fields)) {
- $this->fields = $structure['fields'];
- } else {
- $this->fields = LiveUser::arrayMergeClobber($structure['fields'], $this->fields);
- }
- if (empty($this->alias)) {
- $this->alias = $structure['alias'];
- } else {
- $this->alias = LiveUser::arrayMergeClobber($structure['alias'], $this->alias);
- }
-
- return true;
- }
-
- /**
- * Static method to set defaults into a select params array
- *
- * @param array params array
- * @return array params array
- *
- * @access public
- */
- function setSelectDefaultParams($params)
- {
- if (!is_array($params)) {
- PEAR_ErrorStack::staticPush('LiveUser_Admin', LIVEUSER_ADMIN_ERROR,
- 'exception', array(), 'Parameters must be an array but is of type: '.gettype($params));
- }
-
- $params['fields'] = empty($params['fields']) ? array('*') : $params['fields'];
- $params['with'] = empty($params['with']) ? array() : $params['with'];
- $params['filters'] = empty($params['filters']) ? array() : $params['filters'];
- $params['orders'] = empty($params['orders']) ? array() : $params['orders'];
- $params['rekey'] = empty($params['rekey']) ? false : $params['rekey'];
- $params['group'] = empty($params['group']) ? false : $params['group'];
- $params['limit'] = empty($params['limit']) ? null : $params['limit'];
- $params['offset'] = empty($params['offset']) ? null : $params['offset'];
- $params['select'] = empty($params['select']) ? 'all' : $params['select'];
-
- return $params;
- }
-
- /**
- * properly disconnect from resources
- *
- * @access public
- */
- function disconnect()
- {
- }
-}
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * A framework for authentication and authorization in PHP applications
- *
- * LiveUser_Admin is meant to be used with the LiveUser package.
- * It is composed of all the classes necessary to administrate
- * data used by LiveUser.
- *
- * You'll be able to add/edit/delete/get things like:
- * * Rights
- * * Users
- * * Groups
- * * Areas
- * * Applications
- * * Subgroups
- * * ImpliedRights
- *
- * And all other entities within LiveUser.
- *
- * At the moment we support the following storage containers:
- * * DB
- * * MDB
- * * MDB2
- *
- * But it takes no time to write up your own storage container,
- * so if you like to use native mysql functions straight, then it's possible
- * to do so in under a hour!
- *
- * PHP version 4 and 5
- *
- * LICENSE: This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library 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
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
- * MA 02111-1307 USA
- *
- *
- * @category authentication
- * @package LiveUser_Admin
- * @author Markus Wolff <wolff@21st.de>
- * @author Helgi Þormar Þorbjörnsson <dufuz@php.net>
- * @author Lukas Smith <smith@pooteeweet.org>
- * @author Arnaud Limbourg <arnaud@php.net>
- * @author Christian Dickmann <dickmann@php.net>
- * @author Matt Scifo <mscifo@php.net>
- * @author Bjoern Kraus <krausbn@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version CVS: $Id: DB.php,v 1.1.1.1 2008/04/28 15:20:46 jamie Exp $
- * @link http://pear.php.net/LiveUser_Admin
- */
-
-/**
- * Require parent class definition.
- */
-require_once 'LiveUser/Admin/Storage/SQL.php';
-require_once 'DB.php';
-
-/**
- * This is a PEAR::DB backend driver for the LiveUser class.
- * A PEAR::DB connection object can be passed to the constructor to reuse an
- * existing connection. Alternatively, a DSN can be passed to open a new one.
- *
- * Requirements:
- * - File "Liveuser/Admin.php" (contains the parent class "LiveUser_Admin")
- * - Array of connection options or a PEAR::DB connection object must be
- * passed to the init() method
- * Example: array('dsn' => 'mysql://user:pass@host/db_name')
- * OR
- * array('dbc' => &$conn) ($conn is a PEAR::DB connection object)
- *
- * @category authentication
- * @package LiveUser_Admin
- * @author Lukas Smith <smith@pooteeweet.org>
- * @author Bjoern Kraus <krausbn@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version Release: @package_version@
- * @link http://pear.php.net/LiveUser_Admin
- */
-class LiveUser_Admin_Storage_DB extends LiveUser_Admin_Storage_SQL
-{
- /**
- * Initializes database storage container.
- * Connects to database or uses existing database connection.
- *
- * @param array Storage Configuration
- * @param array containing the database structure (tables, fields, alias)
- * @return bool true on success and false on failure
- *
- * @access public
- */
- function init(&$storageConf, $structure)
- {
- parent::init($storageConf, $structure);
-
- if (!is_a($this->dbc, 'db_common') && !is_null($this->dsn)) {
- $this->options['portability'] = DB_PORTABILITY_ALL;
- $dbc =& DB::connect($this->dsn, $this->options);
- if (PEAR::isError($dbc)) {
- $this->stack->push(LIVEUSER_ERROR_INIT_ERROR, 'error',
- array('container' => 'could not connect: '.$dbc->getMessage(),
- 'debug' => $dbc->getUserInfo()));
- return false;
- }
- $this->dbc =& $dbc;
- }
-
- if (!is_a($this->dbc, 'db_common')) {
- $this->stack->push(LIVEUSER_ERROR_INIT_ERROR, 'error',
- array('container' => 'storage layer configuration missing'));
- return false;
- }
-
- return true;
- }
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string text string value that is intended to be converted.
- * @param string type to which the value should be converted to
- * @return stringtext string that represents the given argument value in
- * a DBMS specific format.
- *
- * @access public
- * @uses DB::quoteSmart
- */
- function quote($value, $type)
- {
- return $this->dbc->quoteSmart($value);
- }
-
- /**
- * Apply a type to all values of an array and return as a comma
- * seperated string useful for generating IN statements
- *
- * @param array data array
- * @param string determines type of the field
- * @return string comma seperated values
- *
- * @access public
- * @uses DB::quoteSmart
- */
- function implodeArray($array, $type)
- {
- if (!is_array($array) || empty($array)) {
- return 'NULL';
- }
- foreach ($array as $value) {
- $return[] = $this->dbc->quoteSmart($value);
- }
- return implode(', ', $return);
- }
-
- /**
- * This function is not implemented into DB so we
- * can't make use of it.
- *
- * @param string number of rows to select
- * @param string first row to select
- *
- * @return bool false This feature isn't supported by DB
- *
- * @access public
- */
- function setLimit($limit, $offset)
- {
- if ($limit || $offset) {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR_FILTER, 'exception',
- array('msg' => 'limit is not supported by this backend')
- );
- return false;
- }
- }
-
- /**
- * Execute DML query
- *
- * @param string DML query
- * @return bool|int of the affected rows
- *
- * @access public
- * @uses DB::query DB::affectedRows
- */
- function exec($query)
- {
- $result = $this->dbc->query($query);
- if (PEAR::isError($result)) {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR_QUERY_BUILDER, 'exception',
- array('reason' => $result->getMessage() . '-' . $result->getUserInfo())
- );
- return false;
- }
- return $this->dbc->affectedRows();
- }
-
- /**
- * Execute the specified query, fetch the value from the first column of
- * the first row of the result set and then frees the result set.
- *
- * @param string the SELECT query statement to be executed.
- * @param string argument that specifies the expected datatype of the
- * result set field, so that an eventual conversion may be performed.
- * The default datatype is text, meaning no conversion is performed.
- * @return bool|string
- *
- * @access public
- * @uses DB::getOne
- */
- function queryOne($query, $type)
- {
- $result = $this->dbc->getOne($query);
- if (PEAR::isError($result)) {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR_QUERY_BUILDER, 'exception',
- array('reason' => $result->getMessage() . '-' . $result->getUserInfo())
- );
- return false;
- }
- return $result;
- }
-
- /**
- * Execute the specified query, fetch the values from the first
- * row of the result set into an array and then frees
- * the result set.
- *
- * @param string the SELECT query statement to be executed.
- * @param array argument that specifies a list of expected datatypes
- * of theresult set columns, so that the conversions may be performed.
- * The default datatype is text, meaning no conversion is performed.
- * @return bool|array
- *
- * @access public
- * @uses DB::getRow
- */
- function queryRow($query, $type)
- {
- $result = $this->dbc->getRow($query, null, DB_FETCHMODE_ASSOC);
- if (PEAR::isError($result)) {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR_QUERY_BUILDER, 'exception',
- array('reason' => $result->getMessage() . '-' . $result->getUserInfo())
- );
- return false;
- }
- return $result;
- }
-
- /**
- * Execute the specified query, fetch the value from the first column of
- * each row of the result set into an array and then frees the result set.
- *
- * @param string the SELECT query statement to be executed.
- * @param string argument that specifies the expected datatype of the
- * result set field, so that an eventual conversion may be performed.
- * The default datatype is text, meaning no conversion is performed.
- * @return bool|array
- *
- * @access public
- * @uses DB::getCol
- */
- function queryCol($query, $type)
- {
- $result = $this->dbc->getCol($query);
- if (PEAR::isError($result)) {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR_QUERY_BUILDER, 'exception',
- array('reason' => $result->getMessage() . '-' . $result->getUserInfo())
- );
- return false;
- }
- return $result;
- }
-
- /**
- * Execute the specified query, fetch all the rows of the result set into
- * a two dimensional array and then frees the result set.
- *
- * @param string the SELECT query statement to be executed.
- * @param array argument that specifies a list of expected datatypes
- * of theresult set columns, so that the conversions may be performed.
- * The default datatype is text, meaning no conversion is performed.
- * @param bool if set to true, returned array will have the first
- * column as its first dimension
- * @param bool if set to true and $rekey is set to true, then
- * all values with the same first column will be wrapped in an array
- * @return bool|array
- *
- * @access public
- * @uses DB::getAll DB::getAssoc
- */
- function queryAll($query, $types, $rekey, $group)
- {
- if ($rekey) {
- $result = $this->dbc->getAssoc($query, false, array(), DB_FETCHMODE_ASSOC, $group);
- } else {
- $result = $this->dbc->getAll($query, array(), DB_FETCHMODE_ASSOC);
- }
- if (PEAR::isError($result)) {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR_QUERY_BUILDER, 'exception',
- array('reason' => $result->getMessage() . '-' . $result->getUserInfo())
- );
- return false;
- }
- return $result;
- }
-
- /**
- * returns the next free id of a sequence
- *
- * @param string name of the sequence
- * @param bool when true the seqence is
- * automatic created, if it not exists
- * @return bool|int false on failure or next id for the table
- *
- * @access public
- * @uses DB::nextId
- */
- function nextId($seqname, $ondemand = true)
- {
- $result = $this->dbc->nextId($seqname, $ondemand);
- if (PEAR::isError($result)) {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR_QUERY_BUILDER, 'exception',
- array('reason' => $result->getMessage() . '-' . $result->getUserInfo())
- );
- return false;
- }
- return $result;
- }
-
- /**
- * Since DB does not support determining if auto increment is supported,
- * the call is redirected to nextID()
- *
- * @param string name of the table into which a new row was inserted
- * @param string name of the field into which a new row was inserted
- * @param bool when true the seqence is automatic created, if it not exists
- * @return bool|int
- *
- * @access public
- * @uses MDB2::nextId MDB2_Extended::getBeforeId
- */
- function getBeforeId($table, $field, $ondemand = true)
- {
- $seq = $table.(empty($field) ? '' : '_'.$field);
- return $this->nextId($seq, $ondemand);
- }
-
- /**
- * Since DB does not support determining if auto increment is supported,
- * the call just returns the $id parameter
- *
- * @param string value as returned by getBeforeId()
- * @param string name of the table into which a new row was inserted
- * @param string name of the field into which a new row was inserted
- * @return bool|int returns the id that the users passed via params
- *
- * @access public
- * @uses MDB2_Extended::getAfterId
- */
- function getAfterId($id, $table, $field)
- {
- return $id;
- }
-}
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * A framework for authentication and authorization in PHP applications
- *
- * LiveUser_Admin is meant to be used with the LiveUser package.
- * It is composed of all the classes necessary to administrate
- * data used by LiveUser.
- *
- * You'll be able to add/edit/delete/get things like:
- * * Rights
- * * Users
- * * Groups
- * * Areas
- * * Applications
- * * Subgroups
- * * ImpliedRights
- *
- * And all other entities within LiveUser.
- *
- * At the moment we support the following storage containers:
- * * DB
- * * MDB
- * * MDB2
- *
- * But it takes no time to write up your own storage container,
- * so if you like to use native mysql functions straight, then it's possible
- * to do so in under a hour!
- *
- * PHP version 4 and 5
- *
- * LICENSE: This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library 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
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
- * MA 02111-1307 USA
- *
- *
- * @category authentication
- * @package LiveUser_Admin
- * @author Markus Wolff <wolff@21st.de>
- * @author Helgi Þormar Þorbjörnsson <dufuz@php.net>
- * @author Lukas Smith <smith@pooteeweet.org>
- * @author Arnaud Limbourg <arnaud@php.net>
- * @author Christian Dickmann <dickmann@php.net>
- * @author Matt Scifo <mscifo@php.net>
- * @author Bjoern Kraus <krausbn@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version CVS: $Id: MDB.php,v 1.1.1.1 2008/04/28 15:20:46 jamie Exp $
- * @link http://pear.php.net/LiveUser_Admin
- */
-
-/**
- * Require parent class definition.
- */
-require_once 'LiveUser/Admin/Storage/SQL.php';
-require_once 'MDB.php';
-
-/**
- * This is a PEAR::MDB backend driver for the LiveUser class.
- * A PEAR::MDB connection object can be passed to the constructor to reuse an
- * existing connection. Alternatively, a DSN can be passed to open a new one.
- *
- * Requirements:
- * - File "Liveuser/Admin.php" (contains the parent class "LiveUser_Admin")
- * - Array of connection options or a PEAR::MDB connection object must be
- * passed to the init() method
- * Example: array('dsn' => 'mysql://user:pass@host/db_name')
- * OR
- * array('dbc' => &$conn) ($conn is a PEAR::MDB connection object)
- *
- * @category authentication
- * @package LiveUser_Admin
- * @author Lukas Smith <smith@pooteeweet.org>
- * @author Bjoern Kraus <krausbn@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version Release: @package_version@
- * @link http://pear.php.net/LiveUser_Admin
- */
-class LiveUser_Admin_Storage_MDB extends LiveUser_Admin_Storage_SQL
-{
- /**
- * Database connection functions
- *
- * @var object
- * @access private
- */
- var $function = 'connect';
-
- /**
- * Initializes database storage container.
- * Connects to database or uses existing database connection.
- *
- * @param array Storage Configuration
- * @param array containing the database structure (tables, fields, alias)
- * @return bool true on success and false on failure
- *
- * @access public
- */
- function init(&$storageConf, $structure)
- {
- parent::init($storageConf, $structure);
-
- if (!MDB::isConnection($this->dbc) && !is_null($this->dsn)) {
- $this->options['optimize'] = 'portability';
- if ($this->function == 'singleton') {
- $dbc =& MDB::singleton($this->dsn, $this->options);
- } else {
- $dbc =& MDB::connect($this->dsn, $this->options);
- }
- if (PEAR::isError($dbc)) {
- $this->stack->push(LIVEUSER_ERROR_INIT_ERROR, 'error',
- array('container' => 'could not connect: '.$dbc->getMessage(),
- 'debug' => $dbc->getUserInfo()));
- return false;
- }
- $this->dbc =& $dbc;
- }
-
- if (!MDB::isConnection($this->dbc)) {
- $this->stack->push(LIVEUSER_ERROR_INIT_ERROR, 'error',
- array('container' => 'storage layer configuration missing'));
- return false;
- }
-
- return true;
- }
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string text string value that is intended to be converted.
- * @param string type to which the value should be converted to
- * @return stringtext string that represents the given argument value in
- * a DBMS specific format.
- *
- * @access public
- * @uses MDB::getValue
- */
- function quote($value, $type)
- {
- return $this->dbc->getValue($type, $value);
- }
-
- /**
- * Apply a type to all values of an array and return as a comma
- * seperated string useful for generating IN statements
- *
- * @param array data array
- * @param string determines type of the field
- * @return string comma seperated values
- *
- * @access public
- * @uses MDB::getValue
- */
- function implodeArray($array, $type)
- {
- if (!is_array($array) || empty($array)) {
- return 'NULL';
- }
- foreach ($array as $value) {
- $return[] = $this->dbc->getValue($type, $value);
- }
- return implode(', ', $return);
- }
-
- /**
- * Sets the range of the next query
- *
- * @param string number of rows to select
- * @param string first row to select
- *
- * @return bool true on success and false on failure
- *
- * @access public
- * @uses MDB::setSelectedRowRange
- */
- function setLimit($limit, $offset)
- {
- if ($limit || $offset) {
- $result = $this->dbc->setSelectedRowRange($offset, $limit);
- if (PEAR::isError($result)) {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR_QUERY_BUILDER, 'exception',
- array('reason' => $result->getMessage() . '-' . $result->getUserInfo())
- );
- return false;
- }
- }
- return true;
- }
-
- /**
- * Execute DML query
- *
- * @param string DML query
- * @return bool|int of the affected rows
- *
- * @access public
- * @uses MDB::query MDB::affectedRows
- */
- function exec($query)
- {
- $result = $this->dbc->query($query);
- if (PEAR::isError($result)) {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR_QUERY_BUILDER, 'exception',
- array('reason' => $result->getMessage() . '-' . $result->getUserInfo())
- );
- return false;
- }
- return $this->dbc->affectedRows();
- }
-
- /**
- * Execute the specified query, fetch the value from the first column of
- * the first row of the result set and then frees the result set.
- *
- * @param string the SELECT query statement to be executed.
- * @param string argument that specifies the expected datatype of the
- * result set field, so that an eventual conversion may be performed.
- * The default datatype is text, meaning no conversion is performed.
- * @return bool|string
- *
- * @access public
- * @uses MDB::queryOne
- */
- function queryOne($query, $type)
- {
- if (is_array($type)) {
- $type = reset($type);
- }
-
- $result = $this->dbc->queryOne($query, $type);
- if (PEAR::isError($result)) {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR_QUERY_BUILDER, 'exception',
- array('reason' => $result->getMessage() . '-' . $result->getUserInfo())
- );
- return false;
- }
- return $result;
- }
-
- /**
- * Execute the specified query, fetch the values from the first
- * row of the result set into an array and then frees
- * the result set.
- *
- * @param string the SELECT query statement to be executed.
- * @param array argument that specifies a list of expected datatypes
- * of theresult set columns, so that the conversions may be performed.
- * The default datatype is text, meaning no conversion is performed.
- * @return bool|array
- *
- * @access public
- * @uses MDB::queryRow
- */
- function queryRow($query, $type)
- {
- $result = $this->dbc->queryRow($query, $type, MDB_FETCHMODE_ASSOC);
- if (PEAR::isError($result)) {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR_QUERY_BUILDER, 'exception',
- array('reason' => $result->getMessage() . '-' . $result->getUserInfo())
- );
- return false;
- }
- return $result;
- }
-
- /**
- * Execute the specified query, fetch the value from the first column of
- * each row of the result set into an array and then frees the result set.
- *
- * @param string the SELECT query statement to be executed.
- * @param string argument that specifies the expected datatype of the
- * result set field, so that an eventual conversion may be performed.
- * The default datatype is text, meaning no conversion is performed.
- * @return bool|array
- *
- * @access public
- * @uses MDB::queryCol
- */
- function queryCol($query, $type)
- {
- if (is_array($type)) {
- $type = reset($type);
- }
-
- $result = $this->dbc->queryCol($query, $type);
- if (PEAR::isError($result)) {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR_QUERY_BUILDER, 'exception',
- array('reason' => $result->getMessage() . '-' . $result->getUserInfo())
- );
- return false;
- }
- return $result;
- }
-
- /**
- * Execute the specified query, fetch all the rows of the result set into
- * a two dimensional array and then frees the result set.
- *
- * @param string the SELECT query statement to be executed.
- * @param array argument that specifies a list of expected datatypes
- * of theresult set columns, so that the conversions may be performed.
- * The default datatype is text, meaning no conversion is performed.
- * @param bool if set to true, returned array will have the first
- * column as its first dimension
- * @param bool if set to true and $rekey is set to true, then
- * all values with the same first column will be wrapped in an array
- * @return bool|array
- *
- * @access public
- * @uses MDB::queryAll
- */
- function queryAll($query, $types, $rekey, $group)
- {
- $result = $this->dbc->queryAll($query, $types, MDB_FETCHMODE_ASSOC, $rekey, false, $group);
- if (PEAR::isError($result)) {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR_QUERY_BUILDER, 'exception',
- array('reason' => $result->getMessage() . '-' . $result->getUserInfo())
- );
- return false;
- }
- return $result;
- }
-
- /**
- * returns the next free id of a sequence
- *
- * @param string name of the sequence
- * @param bool when true the seqence is
- * automatic created, if it not exists
- * @return bool|int false on failure or next id for the table
- *
- * @access public
- * @uses MDB::nextId
- */
- function nextId($seqname, $ondemand = true)
- {
- $result = $this->dbc->nextId($seqname, $ondemand);
- if (PEAR::isError($result)) {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR_QUERY_BUILDER, 'exception',
- array('reason' => $result->getMessage() . '-' . $result->getUserInfo())
- );
- return false;
- }
- return $result;
- }
-
- /**
- * Since MDB does not support determining if auto increment is supported,
- * the call is redirected to nextID()
- *
- * @param string name of the table into which a new row was inserted
- * @param string name of the field into which a new row was inserted
- * @param bool when true the seqence is automatic created, if it not exists
- * @return bool|int
- *
- * @access public
- * @uses MDB2::nextId MDB2_Extended::getBeforeId
- */
- function getBeforeId($table, $field, $ondemand = true)
- {
- $seq = $table.(empty($field) ? '' : '_'.$field);
- return $this->nextId($seq, $ondemand);
- }
-
- /**
- * Since MDB does not support determining if auto increment is supported,
- * the call just returns the $id parameter
- *
- * @param string value as returned by getBeforeId()
- * @param string name of the table into which a new row was inserted
- * @param string name of the field into which a new row was inserted
- * @return bool|int returns the id that the users passed via params
- *
- * @access public
- * @uses MDB2_Extended::getAfterId
- */
- function getAfterId($id, $table, $field)
- {
- return $id;
- }
-}
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * A framework for authentication and authorization in PHP applications
- *
- * LiveUser_Admin is meant to be used with the LiveUser package.
- * It is composed of all the classes necessary to administrate
- * data used by LiveUser.
- *
- * You'll be able to add/edit/delete/get things like:
- * * Rights
- * * Users
- * * Groups
- * * Areas
- * * Applications
- * * Subgroups
- * * ImpliedRights
- *
- * And all other entities within LiveUser.
- *
- * At the moment we support the following storage containers:
- * * DB
- * * MDB
- * * MDB2
- *
- * But it takes no time to write up your own storage container,
- * so if you like to use native mysql functions straight, then it's possible
- * to do so in under a hour!
- *
- * PHP version 4 and 5
- *
- * LICENSE: This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library 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
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
- * MA 02111-1307 USA
- *
- *
- * @category authentication
- * @package LiveUser_Admin
- * @author Markus Wolff <wolff@21st.de>
- * @author Helgi Þormar Þorbjörnsson <dufuz@php.net>
- * @author Lukas Smith <smith@pooteeweet.org>
- * @author Arnaud Limbourg <arnaud@php.net>
- * @author Christian Dickmann <dickmann@php.net>
- * @author Matt Scifo <mscifo@php.net>
- * @author Bjoern Kraus <krausbn@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version CVS: $Id: MDB2.php,v 1.1.1.1 2008/04/28 15:20:46 jamie Exp $
- * @link http://pear.php.net/LiveUser_Admin
- */
-
-/**
- * Require parent class definition.
- */
-require_once 'LiveUser/Admin/Storage/SQL.php';
-require_once 'MDB2.php';
-
-/**
- * This is a PEAR::MDB2 backend driver for the LiveUser class.
- * A PEAR::MDB2 connection object can be passed to the constructor to reuse an
- * existing connection. Alternatively, a DSN can be passed to open a new one.
- *
- * Requirements:
- * - File "Liveuser/Admin.php" (contains the parent class "LiveUser_Admin")
- * - Array of connection options or a PEAR::MDB2 connection object must be
- * passed to the init() method
- * Example: array('dsn' => 'mysql://user:pass@host/db_name')
- * OR
- * array('dbc' => &$conn) ($conn is a PEAR::MDB2 connection object)
- *
- * @category authentication
- * @package LiveUser_Admin
- * @author Lukas Smith <smith@pooteeweet.org>
- * @author Bjoern Kraus <krausbn@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version Release: @package_version@
- * @link http://pear.php.net/LiveUser_Admin
- */
-class LiveUser_Admin_Storage_MDB2 extends LiveUser_Admin_Storage_SQL
-{
- /**
- * Database connection functions
- *
- * @var object
- * @access private
- */
- var $function = 'connect';
-
- /**
- * determines of the use of sequences should be forced
- *
- * @var bool
- * @access private
- */
- var $force_seq = true;
-
- /**
- * Initializes database storage container.
- * Connects to database or uses existing database connection.
- *
- * @param array Storage Configuration
- * @param array containing the database structure (tables, fields, alias)
- * @return bool true on success and false on failure
- *
- * @access public
- */
- function init(&$storageConf, $structure)
- {
- parent::init($storageConf, $structure);
-
- if (!MDB2::isConnection($this->dbc) && !is_null($this->dsn)) {
- $this->options['portability'] = MDB2_PORTABILITY_ALL;
- if ($this->function == 'singleton') {
- $dbc =& MDB2::singleton($storageConf['dsn'], $this->options);
- } else {
- $dbc =& MDB2::connect($storageConf['dsn'], $this->options);
- }
- if (PEAR::isError($dbc)) {
- $this->stack->push(LIVEUSER_ERROR_INIT_ERROR, 'error',
- array('container' => 'could not connect: '.$dbc->getMessage(),
- 'debug' => $dbc->getUserInfo()));
- return false;
- }
- $this->dbc =& $dbc;
- }
-
- if (!MDB2::isConnection($this->dbc)) {
- $this->stack->push(LIVEUSER_ERROR_INIT_ERROR, 'error',
- array('container' => 'storage layer configuration missing'));
- return false;
- }
-
- return true;
- }
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string text string value that is intended to be converted.
- * @param string type to which the value should be converted to
- * @return stringtext string that represents the given argument value in
- * a DBMS specific format.
- *
- * @access public
- * @uses MDB2::quote
- */
- function quote($value, $type)
- {
- return $this->dbc->quote($value, $type);
- }
-
- /**
- * Apply a type to all values of an array and return as a comma
- * seperated string useful for generating IN statements
- *
- * @param array data array
- * @param string determines type of the field
- * @return string comma seperated values
- *
- * @access public
- * @uses MDB2_Driver_Datatype_Common::implodeArray
- */
- function implodeArray($array, $type)
- {
- $this->dbc->loadModule('Datatype');
- return $this->dbc->datatype->implodeArray($array, $type);
- }
-
- /**
- * Sets the range of the next query
- *
- * @param string number of rows to select
- * @param string first row to select
- *
- * @return bool true on success and false on failure
- *
- * @access public
- * @uses MDB2::setLimit
- */
- function setLimit($limit, $offset)
- {
- if ($limit || $offset) {
- $result = $this->dbc->setLimit($limit, $offset);
- if (PEAR::isError($result)) {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR_QUERY_BUILDER, 'exception',
- array('reason' => $result->getMessage() . '-' . $result->getUserInfo())
- );
- return false;
- }
- }
- return true;
- }
-
- /**
- * Execute DML query
- *
- * @param string DML query
- * @return bool|int of the affected rows
- *
- * @access public
- * @uses MDB2::exec
- */
- function exec($query)
- {
- $result = $this->dbc->exec($query);
- if (PEAR::isError($result)) {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR_QUERY_BUILDER, 'exception',
- array('reason' => $result->getMessage() . '-' . $result->getUserInfo())
- );
- return false;
- }
- return $result;
- }
-
- /**
- * Execute the specified query, fetch the value from the first column of
- * the first row of the result set and then frees the result set.
- *
- * @param string the SELECT query statement to be executed.
- * @param string argument that specifies the expected datatype of the
- * result set field, so that an eventual conversion may be performed.
- * The default datatype is text, meaning no conversion is performed.
- * @return bool|string
- *
- * @access public
- * @uses MDB2::queryOne
- */
- function queryOne($query, $type)
- {
- $result = $this->dbc->queryOne($query, $type);
- if (PEAR::isError($result)) {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR_QUERY_BUILDER, 'exception',
- array('reason' => $result->getMessage() . '-' . $result->getUserInfo())
- );
- return false;
- }
- return $result;
- }
-
- /**
- * Execute the specified query, fetch the values from the first
- * row of the result set into an array and then frees
- * the result set.
- *
- * @param string the SELECT query statement to be executed.
- * @param array argument that specifies a list of expected datatypes
- * of theresult set columns, so that the conversions may be performed.
- * The default datatype is text, meaning no conversion is performed.
- * @return bool|array
- *
- * @access public
- * @uses MDB2::queryRow
- */
- function queryRow($query, $type)
- {
- $result = $this->dbc->queryRow($query, $type, MDB2_FETCHMODE_ASSOC);
- if (PEAR::isError($result)) {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR_QUERY_BUILDER, 'exception',
- array('reason' => $result->getMessage() . '-' . $result->getUserInfo())
- );
- return false;
- }
- return $result;
- }
-
- /**
- * Execute the specified query, fetch the value from the first column of
- * each row of the result set into an array and then frees the result set.
- *
- * @param string the SELECT query statement to be executed.
- * @param string argument that specifies the expected datatype of the
- * result set field, so that an eventual conversion may be performed.
- * The default datatype is text, meaning no conversion is performed.
- * @return bool|array
- *
- * @access public
- * @uses MDB2::queryCol
- */
- function queryCol($query, $type)
- {
- $result = $this->dbc->queryCol($query, $type);
- if (PEAR::isError($result)) {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR_QUERY_BUILDER, 'exception',
- array('reason' => $result->getMessage() . '-' . $result->getUserInfo())
- );
- return false;
- }
- return $result;
- }
-
- /**
- * Execute the specified query, fetch all the rows of the result set into
- * a two dimensional array and then frees the result set.
- *
- * @param string the SELECT query statement to be executed.
- * @param array argument that specifies a list of expected datatypes
- * of theresult set columns, so that the conversions may be performed.
- * The default datatype is text, meaning no conversion is performed.
- * @param bool if set to true, returned array will have the first
- * column as its first dimension
- * @param bool if set to true and $rekey is set to true, then
- * all values with the same first column will be wrapped in an array
- * @return bool|array
- *
- * @access public
- * @uses MDB2::queryAll
- */
- function queryAll($query, $types, $rekey, $group)
- {
- $result = $this->dbc->queryAll($query, $types, MDB2_FETCHMODE_ASSOC, $rekey, false, $group);
- if (PEAR::isError($result)) {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR_QUERY_BUILDER, 'exception',
- array('reason' => $result->getMessage() . '-' . $result->getUserInfo())
- );
- return false;
- }
- return $result;
- }
-
- /**
- * returns the next free id of a sequence
- *
- * @param string name of the sequence
- * @param bool when true the seqence is
- * automatic created, if it not exists
- * @return bool|int false on failure or next id for the table
- *
- * @access public
- * @uses MDB2::nextId
- */
- function nextId($seqname, $ondemand = true)
- {
- $result = $this->dbc->nextId($seqname, $ondemand);
- if (PEAR::isError($result)) {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR_QUERY_BUILDER, 'exception',
- array('reason' => $result->getMessage() . '-' . $result->getUserInfo())
- );
- return false;
- }
- return $result;
- }
-
- /**
- * returns the next free id of a sequence if the RDBMS
- * does not support auto increment
- *
- * @param string name of the table into which a new row was inserted
- * @param string name of the field into which a new row was inserted
- * @param bool when true the seqence is automatic created, if it not exists
- * @return bool|int
- *
- * @access public
- * @uses MDB2::nextId MDB2_Extended::getBeforeId
- */
- function getBeforeId($table, $field, $ondemand = true)
- {
- if ($this->force_seq) {
- $result = $this->dbc->nextId($table, $ondemand);
- } else {
- $this->dbc->loadModule('Extended');
- $result = $this->dbc->extended->getBeforeId($table, $field, $ondemand, false);
- }
-
- if (PEAR::isError($result)) {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR_QUERY_BUILDER, 'exception',
- array('reason' => $result->getMessage() . '-' . $result->getUserInfo())
- );
- return false;
- }
- return $result;
- }
-
- /**
- * returns the autoincrement ID if supported or $id
- *
- * @param string value as returned by getBeforeId()
- * @param string name of the table into which a new row was inserted
- * @param string name of the field into which a new row was inserted
- * @return bool|int returns the id that the users passed via params
- *
- * @access public
- * @uses MDB2_Extended::getAfterId
- */
- function getAfterId($id, $table, $field)
- {
- if ($this->force_seq) {
- return $id;
- }
-
- $this->dbc->loadModule('Extended');
- $result = $this->dbc->extended->getAfterId($id, $table, $field);
- if (PEAR::isError($result)) {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR_QUERY_BUILDER, 'exception',
- array('reason' => $result->getMessage() . '-' . $result->getUserInfo())
- );
- return false;
- }
- return $result;
- }
-}
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * A framework for authentication and authorization in PHP applications
- *
- * LiveUser_Admin is meant to be used with the LiveUser package.
- * It is composed of all the classes necessary to administrate
- * data used by LiveUser.
- *
- * You'll be able to add/edit/delete/get things like:
- * * Rights
- * * Users
- * * Groups
- * * Areas
- * * Applications
- * * Subgroups
- * * ImpliedRights
- *
- * And all other entities within LiveUser.
- *
- * At the moment we support the following storage containers:
- * * DB
- * * MDB
- * * MDB2
- *
- * But it takes no time to write up your own storage container,
- * so if you like to use native mysql functions straight, then it's possible
- * to do so in under a hour!
- *
- * PHP version 4 and 5
- *
- * LICENSE: This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library 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
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
- * MA 02111-1307 USA
- *
- *
- * @category authentication
- * @package LiveUser_Admin
- * @author Markus Wolff <wolff@21st.de>
- * @author Helgi Þormar Þorbjörnsson <dufuz@php.net>
- * @author Lukas Smith <smith@pooteeweet.org>
- * @author Arnaud Limbourg <arnaud@php.net>
- * @author Christian Dickmann <dickmann@php.net>
- * @author Matt Scifo <mscifo@php.net>
- * @author Bjoern Kraus <krausbn@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version CVS: $Id: PDO.php,v 1.1.1.1 2008/04/28 15:20:46 jamie Exp $
- * @link http://pear.php.net/LiveUser_Admin
- */
-
-/**
- * Require parent class definition.
- */
-require_once 'LiveUser/Admin/Storage/SQL.php';
-
-/**
- * This is a PECL::PDO backend driver for the LiveUser class.
- * A PECL::PDO connection object can be passed to the constructor to reuse an
- * existing connection. Alternatively, a DSN can be passed to open a new one.
- *
- * Requirements:
- * - File "Liveuser/Admin.php" (contains the parent class "LiveUser_Admin")
- * - Array of connection options or a PECL::PDO connection object must be
- * passed to the init() method
- * Example: array('dsn' => 'mysql:host:localhost;dbname=db_name',
- * 'options' => array('username' => 'root', 'password' => 'secret', 'attr' => array()));
- *
- * @category authentication
- * @package LiveUser_Admin
- * @author Lukas Smith <smith@pooteeweet.org>
- * @author Bjoern Kraus <krausbn@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version Release: @package_version@
- * @link http://pear.php.net/LiveUser_Admin
- */
-class LiveUser_Admin_Storage_PDO extends LiveUser_Admin_Storage_SQL
-{
- /**
- * determines of the use of sequences should be forced
- *
- * @var bool
- * @access private
- */
- var $force_seq = false;
-
- /**
- * Initializes database storage container.
- * Connects to database or uses existing database connection.
- *
- * @param array Storage Configuration
- * @param array containing the database structure (tables, fields, alias)
- * @return bool true on success and false on failure
- *
- * @access public
- */
- function init(&$storageConf, $structure)
- {
- parent::init($storageConf, $structure);
-
- if (!is_a($this->dbc, 'pdo') && !is_null($this->dsn)) {
- $login = $password = $extra = null;
- if (!empty($this->options)) {
- if (array_key_exists('username', $this->options)) {
- $login = $this->options['username'];
- }
- if (array_key_exists('password', $this->options)) {
- $password = $this->options['password'];
- }
- if (array_key_exists('attr', $this->options)) {
- $extra = $this->options['attr'];
- }
- }
- try {
- $dbc = new PDO($this->dsn, $login, $password, $extra);
- } catch (PDOException $e) {
- $this->stack->push(LIVEUSER_ERROR_INIT_ERROR, 'error',
- array(
- 'container' => 'could not connect: ' . $e->getMessage(),
- 'debug' => $e->getTrace()
- )
- );
- return false;
- }
- $this->dbc = $dbc;
- }
-
- if (!is_a($this->dbc, 'pdo')) {
- $this->stack->push(LIVEUSER_ERROR_INIT_ERROR, 'error',
- array('container' => 'storage layer configuration missing'));
- return false;
- }
-
- return true;
- }
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string text string value that is intended to be converted.
- * @param string type to which the value should be converted to
- * @return stringtext string that represents the given argument value in
- * a DBMS specific format.
- *
- * @access public
- * @uses DB::quoteSmart
- */
- function quote($value, $type)
- {
- return $this->dbc->quote($value);
- }
-
- /**
- * Apply a type to all values of an array and return as a comma
- * seperated string useful for generating IN statements
- *
- * @param array data array
- * @param string determines type of the field
- * @return string comma seperated values
- *
- * @access public
- * @uses DB::quoteSmart
- */
- function implodeArray($array, $type)
- {
- if (!is_array($array) || empty($array)) {
- return 'NULL';
- }
- foreach ($array as $value) {
- $return[] = $this->dbc->quote($value);
- }
- return implode(', ', $return);
- }
-
- /**
- * This function is not implemented into DB so we
- * can't make use of it.
- *
- * @param string number of rows to select
- * @param string first row to select
- *
- * @return bool false This feature isn't supported by DB
- *
- * @access public
- */
- function setLimit($limit, $offset)
- {
- if ($limit || $offset) {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR_FILTER, 'exception',
- array('msg' => 'limit is not supported by this backend')
- );
- return false;
- }
- }
-
- /**
- * Execute DML query
- *
- * @param string DML query
- * @return bool|int of the affected rows
- *
- * @access public
- * @uses DB::query DB::affectedRows
- */
- function exec($query)
- {
- try {
- $result = $this->dbc->exec($query);
- } catch (PDOException $e) {
- $this->stack->push(LIVEUSER_ERROR_INIT_ERROR, 'error',
- array(
- 'container' => 'could not exec DML: ' . $e->getMessage(),
- 'debug' => $e->getTrace()
- )
- );
- return false;
- }
- return $result;
- }
-
- /**
- * Execute the specified query, fetch the value from the first column of
- * the first row of the result set and then frees the result set.
- *
- * @param string the SELECT query statement to be executed.
- * @param string argument that specifies the expected datatype of the
- * result set field, so that an eventual conversion may be performed.
- * The default datatype is text, meaning no conversion is performed.
- * @return bool|string
- *
- * @access public
- * @uses DB::getOne
- */
- function queryOne($query, $type)
- {
- try {
- $stmt = $this->dbc->query($query);
- $result = $stmt->fetchColumn();
- } catch (PDOException $e) {
- $this->stack->push(LIVEUSER_ERROR_INIT_ERROR, 'error',
- array(
- 'container' => 'could not fetch single value: ' . $e->getMessage(),
- 'debug' => $e->getTrace()
- )
- );
- return false;
- }
- return $result;
- }
-
- /**
- * Execute the specified query, fetch the values from the first
- * row of the result set into an array and then frees
- * the result set.
- *
- * @param string the SELECT query statement to be executed.
- * @param array argument that specifies a list of expected datatypes
- * of theresult set columns, so that the conversions may be performed.
- * The default datatype is text, meaning no conversion is performed.
- * @return bool|array
- *
- * @access public
- * @uses DB::getRow
- */
- function queryRow($query, $type)
- {
- try {
- $stmt = $this->dbc->query($query);
- $result = $stmt->fetch(PDO::FETCH_ASSOC);
- if ($result === false && $this->dbc->errorCode() === '00000') {
- $result = null;
- }
- } catch (PDOException $e) {
- $this->stack->push(LIVEUSER_ERROR_INIT_ERROR, 'error',
- array(
- 'container' => 'could not fetch single row: ' . $e->getMessage(),
- 'debug' => $e->getTrace()
- )
- );
- return false;
- }
- return $result;
- }
-
- /**
- * Execute the specified query, fetch the value from the first column of
- * each row of the result set into an array and then frees the result set.
- *
- * @param string the SELECT query statement to be executed.
- * @param string argument that specifies the expected datatype of the
- * result set field, so that an eventual conversion may be performed.
- * The default datatype is text, meaning no conversion is performed.
- * @return bool|array
- *
- * @access public
- * @uses DB::getCol
- */
- function queryCol($query, $type)
- {
- try {
- $stmt = $this->dbc->query($query);
- $result = $stmt->fetchAll(PDO::FETCH_COLUMN);
- } catch (PDOException $e) {
- $this->stack->push(LIVEUSER_ERROR_INIT_ERROR, 'error',
- array(
- 'container' => 'could not fetch single column: ' . $e->getMessage(),
- 'debug' => $e->getTrace()
- )
- );
- return false;
- }
- return $result;
- }
-
- /**
- * Execute the specified query, fetch all the rows of the result set into
- * a two dimensional array and then frees the result set.
- *
- * @param string the SELECT query statement to be executed.
- * @param array argument that specifies a list of expected datatypes
- * of theresult set columns, so that the conversions may be performed.
- * The default datatype is text, meaning no conversion is performed.
- * @param bool if set to true, returned array will have the first
- * column as its first dimension
- * @param bool if set to true and $rekey is set to true, then
- * all values with the same first column will be wrapped in an array
- * @return bool|array
- *
- * @access public
- * @uses DB::getAll DB::getAssoc
- */
- function queryAll($query, $types, $rekey, $group)
- {
- try {
- $stmt = $this->dbc->query($query);
- if ($rekey) {
- if ($group) {
- $fetchmode = PDO::FETCH_ASSOC|PDO::FETCH_GROUP;
- } else {
- $fetchmode = PDO::FETCH_ASSOC|PDO::FETCH_UNIQUE;
- }
- } else {
- $fetchmode = PDO::FETCH_ASSOC;
- }
- $result = $stmt->fetchAll($fetchmode);
- if ($rekey && !empty($result)) {
- if ($group) {
- if (count(reset(reset($result))) == 1) {
- foreach ($result as $group => $array) {
- foreach ($array as $key => $value) {
- $result[$group][$key] = reset($value);
- }
- }
- }
- } elseif (count(reset($result)) == 1) {
- foreach ($result as $key => $array) {
- $result[$key] = reset($array);
- }
- }
- }
- } catch (PDOException $e) {
- $this->stack->push(LIVEUSER_ERROR_INIT_ERROR, 'error',
- array(
- 'container' => 'could not fetch all: ' . $e->getMessage(),
- 'debug' => $e->getTrace()
- )
- );
- return false;
- }
- return $result;
- }
-
- /**
- * returns the next free id of a sequence
- *
- * @param string name of the sequence
- * @param bool when true the seqence is
- * automatic created, if it not exists
- * @return bool|int false on failure or next id for the table
- *
- * @access public
- * @uses DB::nextId
- */
- function nextId($seqname, $ondemand = true)
- {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR_FILTER, 'exception',
- array('msg' => 'nextID is not supported by this backend')
- );
- return false;
- }
-
- /**
- * Since DB does not support determining if auto increment is supported,
- * the call is redirected to nextID()
- *
- * @param string name of the table into which a new row was inserted
- * @param string name of the field into which a new row was inserted
- * @param bool when true the seqence is automatic created, if it not exists
- * @return bool|int
- *
- * @access public
- * @uses MDB2::nextId MDB2_Extended::getBeforeId
- */
- function getBeforeId($table, $field, $ondemand = true)
- {
- // todo: need to figure out what to do here
- return null;
- }
-
- /**
- * Since DB does not support determining if auto increment is supported,
- * the call just returns the $id parameter
- *
- * @param string value as returned by getBeforeId()
- * @param string name of the table into which a new row was inserted
- * @return int returns the id that the users passed via params
- *
- * @access public
- */
- function getAfterId($id, $table)
- {
- // todo: need to figure out what to do here
- try {
- $result = $this->dbc->lastInsertId($table);
- } catch (PDOException $e) {
- $this->stack->push(LIVEUSER_ERROR_INIT_ERROR, 'error',
- array(
- 'container' => 'could not fetch last insert id: ' . $e->getMessage(),
- 'debug' => $e->getTrace()
- )
- );
- return false;
- }
- return $result;
- }
-}
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * A framework for authentication and authorization in PHP applications
- *
- * LiveUser_Admin is meant to be used with the LiveUser package.
- * It is composed of all the classes necessary to administrate
- * data used by LiveUser.
- *
- * You'll be able to add/edit/delete/get things like:
- * * Rights
- * * Users
- * * Groups
- * * Areas
- * * Applications
- * * Subgroups
- * * ImpliedRights
- *
- * And all other entities within LiveUser.
- *
- * At the moment we support the following storage containers:
- * * DB
- * * MDB
- * * MDB2
- *
- * But it takes no time to write up your own storage container,
- * so if you like to use native mysql functions straight, then it's possible
- * to do so in under a hour!
- *
- * PHP version 4 and 5
- *
- * LICENSE: This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library 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
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
- * MA 02111-1307 USA
- *
- *
- * @category authentication
- * @package LiveUser_Admin
- * @author Markus Wolff <wolff@21st.de>
- * @author Helgi Þormar Þorbjörnsson <dufuz@php.net>
- * @author Lukas Smith <smith@pooteeweet.org>
- * @author Arnaud Limbourg <arnaud@php.net>
- * @author Christian Dickmann <dickmann@php.net>
- * @author Matt Scifo <mscifo@php.net>
- * @author Bjoern Kraus <krausbn@php.net>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version CVS: $Id: SQL.php,v 1.1.1.1 2008/04/28 15:20:46 jamie Exp $
- * @link http://pear.php.net/LiveUser_Admin
- */
-
-/**
- * Require parent class definition.
- */
-require_once 'LiveUser/Admin/Storage.php';
-
-/**
- * This is a SQL backend driver for the LiveUser class.
- * A database connection object can be passed to the constructor to reuse an
- * existing connection. Alternatively, a DSN can be passed to open a new one.
- *
- * Requirements:
- * - File "Liveuser.php" (contains the parent class "LiveUser")
- * - Array of connection options or a PEAR::MDB2 connection object must be
- * passed to the constructor.
- * Example: array('dsn' => 'mysql://user:pass@host/db_name')
- * OR
- * &$conn (PEAR::MDB2 connection object)
- *
- * @category authentication
- * @package LiveUser_Admin
- * @author Lukas Smith <smith@pooteeweet.org>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version Release: @package_version@
- * @link http://pear.php.net/LiveUser_Admin
- */
-class LiveUser_Admin_Storage_SQL extends LiveUser_Admin_Storage
-{
- /**
- * dsn that was connected to
- *
- * @var string
- * @access private
- */
- var $dsn = false;
-
- /**
- * Database connection object.
- *
- * @var object
- * @access private
- */
- var $dbc = false;
-
- /**
- * Database connection options.
- *
- * @var object
- * @access private
- */
- var $options = array();
-
- /**
- * Table prefix for all db tables the container has.
- *
- * @var string
- * @access public
- */
- var $prefix = 'liveuser_';
-
- /**
- * Insert data into a table
- *
- * @param string name of the table
- * @param array key value pairs
- * @return int|bool false on error, true (or new id) on success
- *
- * @access public
- */
- function insert($table, $data)
- {
- // sanity checks
- $sequence_id = false;
- foreach ($this->tables[$table]['fields'] as $field => $required) {
- if ($required) {
- if ($required === 'seq') {
- if (!array_key_exists($field, $data) || empty($data[$field])) {
- $result = $this->getBeforeId($this->prefix . $this->alias[$table], $field, true);
- if ($result === false) {
- return false;
- }
- $data[$field] = $result;
- $sequence_id = is_numeric($result) ? $result : $field;
- } else {
- $sequence_id = $data[$field];
- }
- } elseif (!array_key_exists($field, $data)
- || (empty($data[$field]) && $data[$field] !== 0)
- ) {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR_QUERY_BUILDER, 'exception',
- array('reason' => 'field to insert may not be empty: '.$field)
- );
- return false;
- }
- }
- }
-
- $fields = array();
- $values = array();
- foreach ($data as $field => $value) {
- // sanity checks
- if (!array_key_exists($field, $this->tables[$table]['fields'])) {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR_QUERY_BUILDER, 'exception',
- array('reason' => 'field to insert is not defined: '.$field)
- );
- return false;
- }
-
- $fields[] = $this->alias[$field];
- $value_quoted = $this->quote($value, $this->fields[$field]);
- if ($value_quoted === false) {
- return false;
- }
- $values[] = $value_quoted;
- }
-
- $result = $this->exec($this->createInsert($table, $fields, $values));
- if ($result === false) {
- return false;
- }
- if ($sequence_id !== false) {
- if (is_numeric($sequence_id)) {
- return $sequence_id;
- }
- return $this->getAfterId($sequence_id, $this->prefix . $this->alias[$table], $sequence_id);
- }
- return $result;
- }
-
- /**
- * Create the SQL necessary for an insert
- *
- * @param string name of the table
- * @param array array of field names
- * @param array array of quoted values
- * @return string SQL insert query
- *
- * @access public
- */
- function createInsert($table, $fields, $values)
- {
- $query = 'INSERT INTO ' . $this->prefix . $this->alias[$table] . "\n";
- $query .= '(' . implode(', ', $fields) . ')' . "\n";
- $query .= 'VALUES (' . implode(', ', $values) . ')';
- return $query;
- }
-
- /**
- * Update data in a table based given filters
- *
- * @param string name of the table
- * @param array key value pairs
- * @param array key values pairs (value may be a string or an array)
- * @return int|bool false on error, the affected rows on success
- *
- * @access public
- */
- function update($table, $data, $filters)
- {
- if (empty($data)) {
- return true;
- }
-
- $fields = array();
- foreach ($data as $field => $value) {
- // sanity checks
- if (!array_key_exists($field, $this->tables[$table]['fields'])) {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR_QUERY_BUILDER, 'exception',
- array('reason' => 'field to update is not defined: '.$field)
- );
- return false;
- }
-
- if ($this->tables[$table]['fields'][$field]
- && empty($data[$field]) && $data[$field] !== 0
- ) {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR_QUERY_BUILDER, 'exception',
- array('reason' => 'field tp update may not be empty: '.$field)
- );
- return false;
- }
-
- $value_quoted = $this->quote($value, $this->fields[$field]);
- if ($value_quoted === false) {
- return false;
- }
- $fields[] = $this->alias[$field] . ' = ' . $value_quoted;
- }
-
- $result = $this->exec($this->createUpdate($table, $fields, $filters));
- return $result;
- }
-
- /**
- * Create the SQL necessary for an update
- *
- * @param string name of the table
- * @param array array of field names
- * @param array array containing the filtering to apply
- * @return string SQL update query
- *
- * @access public
- */
- function createUpdate($table, $fields, $filters)
- {
- $query = 'UPDATE ' . $this->prefix . $this->alias[$table] . ' SET'. "\n";
- $query .= implode(",\n", $fields);
- $query .= $this->createWhere($filters);
- return $query;
- }
-
- /**
- * Delete from a table based given filters
- *
- * @param string name of the table
- * @param array key values pairs (value may be a string or an array)
- * @return int|bool false on error, the affected rows on success
- *
- * @access public
- */
- function delete($table, $filters)
- {
- $fields = $orders = array();
- $selectable_tables = array($table);
- $result = $this->findTables($fields, $filters, $orders, $selectable_tables);
- if ($result === false) {
- return false;
- }
-
- $result = $this->exec($this->createDelete($table, $filters));
- return $result;
- }
-
- /**
- * Create the SQL necessary for an delete
- *
- * @param string name of the table
- * @param array array containing the filtering to apply
- * @return string SQL delete query
- *
- * @access public
- */
- function createDelete($table, $filters)
- {
- $query = 'DELETE FROM ' . $this->prefix . $this->alias[$table];
- $query .= $this->createWhere($filters);
- return $query;
- }
-
- /**
- * Fetches the count of many rows contain the filtered data
- *
- * @param string name of the table
- * @param string field name to count
- * @param array key values pairs (value may be a string or an array)
- * @return bool|int false on failure and integer of how many
- * rows contain the filtered data
- *
- * @access public
- */
- function selectCount($table, $field, $filters)
- {
- if (empty($field)) {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR_QUERY_BUILDER, 'exception',
- array('reason' => 'field is missing')
- );
- return false;
- }
-
- if (empty($table)) {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR_QUERY_BUILDER, 'exception',
- array('reason' => 'table is missing')
- );
- return false;
- }
-
- $query = 'SELECT ';
- $query .= 'COUNT(' . $this->alias[$field] . ')';
- $query .= "\n" . 'FROM ' . $this->prefix . $this->alias[$table];
- $query .= $this->createWhere($filters);
- return $this->queryOne($query, 'integer');
- }
-
- /**
- * Select data from a set of tables
- *
- * @param string determines what query method to use:
- * 'one' -> queryOne, 'row' -> queryRow, 'col' -> queryCol,
- * 'all' ->queryAll (default)
- * @param array list of fields to fetch
- * @param array key values pairs (value may be a string or an array)
- * @param array key value pairs (values 'ASC' or 'DESC')
- * @param bool if set to true, returned array will have the first
- * column as its first dimension
- * @param bool if set to true and $rekey is set to true, then
- * all values with the same first column will be wrapped in an array
- * @param string number of rows to select
- * @param string first row to select
- * @param string name of the table from which to start looking
- * for join points
- * @param array list of tables that may be joined to
- * @return bool|array false on failure or array with selected data
- *
- * @access public
- */
- function select($select, $fields, $filters, $orders, $rekey, $group, $limit,
- $offset, $root_table, $selectable_tables)
- {
- if (!is_array($fields) || empty($fields)) {
- $fields = array_keys($this->tables[$root_table]['fields']);
- } elseif (($pos = array_search('*', $fields)) !== false) {
- $fields_tmp = array();
- foreach ($fields as $key => $field) {
- if ($pos == $key) {
- $fields_default = array_diff(array_keys($this->tables[$root_table]['fields']), $fields);
- foreach ($fields_default as $field) {
- if (!in_array($field, $fields_tmp)) {
- $fields_tmp[] = $field;
- }
- }
- } else {
- if (!in_array($field, $fields_tmp)) {
- $fields_tmp[] = $field;
- }
- }
- }
- $fields = array_unique($fields_tmp);
- }
-
- $types = array();
- foreach ($fields as $field) {
- $types[] = $this->fields[$field];
- }
-
- $query = $this->createSelect($fields, $filters, $orders, $root_table, $selectable_tables);
- if ($query === false) {
- return false;
- }
-
- $this->setLimit($limit, $offset);
-
- switch($select) {
- case 'one':
- return $this->queryOne($query, $types);
- break;
- case 'row':
- return $this->queryRow($query, $types);
- break;
- case 'col':
- return $this->queryCol($query, $types);
- break;
- }
-
- return $this->queryAll($query, $types, $rekey, $group);
- }
-
- /**
- * Create the SQL necessary for a select
- *
- * @param array list of fields to fetch
- * @param array key values pairs (value may be a string or an array)
- * @param array key value pairs (values 'ASC' or 'DESC')
- * @param string name of the table from which to start looking
- * for join points
- * @param array list of tables that may be joined to
- * @return bool|string false on failure or a string with SQL query
- *
- * @access public
- */
- function createSelect($fields, $filters, $orders, $root_table, $selectable_tables)
- {
- // find the tables to be used inside the query FROM
- $tables = $this->findTables($fields, $filters, $orders, $selectable_tables);
- if (!$tables) {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR_QUERY_BUILDER, 'exception',
- array('reason' => 'no tables were found')
- );
- return false;
- }
-
- $tables[$root_table] = true;
- $joinfilters = array();
- if (count($tables) > 1) {
- // find join condition
- $joinfilters = array();
- $result = $this->createJoinFilter($root_table, $joinfilters, $tables, $selectable_tables);
- if (!$result) {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR_QUERY_BUILDER, 'exception',
- array('reason' => 'joins could not be set')
- );
- return false;
- }
- $joinfilters = $result[0];
- $tables = array_merge($tables, array_flip($result[2]));
- }
-
- $tables = array_keys($tables);
- foreach ($tables as $key => $table) {
- $tables[$key] = $this->prefix.$this->alias[$table];
- }
- // build SELECT query
- $query = 'SELECT '.implode(', ', $fields);
- $query.= "\n".' FROM '.implode(', ', $tables);
- $query.= $this->createWhere($filters, $joinfilters);
- if ($orders) {
- $query.= "\n".' ORDER BY ';
- $orderby = array();
- foreach ($orders as $name => $direction) {
- $orderby[] = $name.' '.$direction;
- }
- $query.= implode(', ', $orderby);
- }
- return $query;
- }
-
- /**
- * Create the SQL necessary for a where statement
- *
- * @param array key values pairs (value may be a string or an array)
- * @param array key values pairs of join related filters
- * @return bool|string false on failure or string with SQL WHERE
- *
- * @access public
- */
- function createWhere($filters, $joinfilters = array())
- {
- if (empty($filters) && empty($joinfilters)) {
- return '';
- }
-
- $where = array();
-
- foreach ($joinfilters as $key => $value) {
- if (is_string($key)) {
- $where[] = $key.' = '.$value;
- } else {
- $where[] = $value;
- }
- }
-
- foreach ($filters as $field => $value) {
- if (array_key_exists($field, $this->fields)) {
- $type = $this->fields[$field];
- $tmp_field = $this->alias[$field];
- // find type for fields with naming like [tablename].[fieldname]
- } elseif (preg_match('/^('.$this->prefix.'[^.]+\.)(.+)$/', $field, $match)
- && array_key_exists($match[2], $this->fields)
- ) {
- $type = $this->fields[$match[2]];
- $tmp_field = $match[1].$this->alias[$match[2]];
- } else {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR_QUERY_BUILDER, 'exception',
- array('reason' => 'field could not be mapped to a type : '.$field)
- );
- return false;
- }
-
- if (is_array($value)) {
- if (array_key_exists('value', $value)) {
- if (is_array($value['value'])) {
- $where[] = $tmp_field.' ' . $value['op'] . ' ('.$this->implodeArray($value['value'], $type).')';
- } else {
- $value_quoted = $this->quote($value['value'], $type);
- if ($value_quoted === false) {
- return false;
- }
- $where[] = $tmp_field. ' ' . $value['op'] . ' ' .$value_quoted;
- }
- } else {
- $where[] = $tmp_field.' IN ('.$this->implodeArray($value, $type).')';
- }
- } else {
- $value_quoted = $this->quote($value, $type);
- if ($value_quoted === false) {
- return false;
- }
- $op = ($value_quoted === 'NULL') ? ' IS ' : ' = ';
- $where[] = $tmp_field.$op.$value_quoted;
- }
- }
-
- return "\n".' WHERE '.implode("\n".' AND ', $where);
- }
-
- /**
- * Determine if an explicitly prefixed table is in the selectable table
- * list and is a valid field
- *
- * @param string (qualified) field name
- * @param array list of tables that may be joined to
- * @return bool|array null or false on failure
- *
- * @access private
- */
- function _checkExplicitTable($field, $selectable_tables)
- {
- if (!preg_match('/^([^.]+)\.(.+)$/', $field, $match)) {
- return null;
- }
- if (!isset($this->tables[$match[1]]['fields'][$match[2]])) {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR_QUERY_BUILDER, 'exception',
- array('reason' => 'table/field is not defined in the schema structure: '.$field)
- );
- return false;
- }
- if (!in_array($match[1], $selectable_tables)) {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR_QUERY_BUILDER, 'exception',
- array('reason' => 'explicit field is not a selectable: ' . $match[1])
- );
- return false;
- }
- return $match;
- }
-
- /**
- * Find all the tables that need to be joined to be able to select
- * all requested columns and to be able to filter the joined rows
- *
- * @param array list of fields to fetch
- * @param array key values pairs (value may be a string or an array)
- * @param array key value pairs (values 'ASC' or 'DESC')
- * @param array list of tables that may be joined to
- * @return bool|array of table names required or false on failure
- *
- * @access public
- */
- function findTables(&$fields, &$filters, &$orders, $selectable_tables)
- {
- $tables = array();
-
- // find tables that the user explicitly requested
- // by using field names like [tablename].[fieldname]
- $fields_tmp = $fields;
- foreach ($fields_tmp as $key => $field) {
- $match = $this->_checkExplicitTable($field, $selectable_tables);
- if (is_null($match)) {
- continue;
- } elseif ($match === false) {
- return false;
- }
- $tables[$match[1]] = true;
- unset($fields_tmp[$key]);
- // append table prefix and AS to this field
- $fields[$key] = $this->prefix.$this->alias[$match[1]].'.'.$match[2].' AS '.$match[2];
- }
-
- $filters_tmp = $filters;
- foreach ($filters_tmp as $field => $value) {
- $match = $this->_checkExplicitTable($field, $selectable_tables);
- if (is_null($match)) {
- continue;
- } elseif ($match === false) {
- return false;
- }
- $tables[$match[1]] = true;
- unset($fields_tmp[$field]);
- // append prefix to this filter
- $filters[$this->prefix.$this->alias[$match[1]].'.'.$match[2]] = $value;
- }
-
- $orders_tmp = $orders;
- foreach ($orders_tmp as $field => $value) {
- $match = $this->_checkExplicitTable($field, $selectable_tables);
- if (is_null($match)) {
- continue;
- } elseif ($match === false) {
- return false;
- }
- $tables[$match[1]] = true;
- unset($orders_tmp[$field]);
- // append prefix to this order by field
- $orders[$this->prefix.$this->alias[$match[1]].'.'.$match[2]] = $value;
- }
-
- $fields_not_yet_linked = array_unique(array_merge($fields_tmp, array_keys($filters_tmp), array_keys($orders_tmp)));
- if (empty($fields_not_yet_linked)) {
- return $tables;
- }
-
- // find the required tables for all other fields
- $table_prefix = !empty($tables);
- foreach ($selectable_tables as $table) {
- if (!isset($this->tables[$table]['fields'])) {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR_QUERY_BUILDER, 'exception',
- array('reason' => 'table is not defined in the schema structure: '.$table)
- );
- return false;
- }
- // find all fields linked in the current table
- $current_fields = array_intersect($fields_not_yet_linked, array_keys($this->tables[$table]['fields']));
- if (empty($current_fields)) {
- continue;
- }
- // add table to the list of tables to include in the FROM
- $tables[$table] = true;
- // remove fields that have been dealt with
- $fields_not_yet_linked = array_diff($fields_not_yet_linked, $current_fields);
- if ($table_prefix || !empty($fields_not_yet_linked)) {
- $table_prefix = true;
- foreach ($current_fields as $field) {
- // append table name to all selected fields for this table
- for ($i = 0, $j = count($fields); $i < $j; $i++) {
- if ($field == $fields[$i]) {
- $fields[$i] = $this->prefix.$this->alias[$table].'.'.$this->alias[$fields[$i]].' AS '.$field;
- }
- }
- // append table name to all filter fields for this table
- // filters are aliased in createWhere
- if (array_key_exists($field, $filters)) {
- $filters[$this->prefix.$this->alias[$table].'.'.$field] = $filters[$field];
- unset($filters[$field]);
- }
- // append table name to all order by fields for this table
- if (array_key_exists($field, $orders)) {
- $orders[$this->prefix.$this->alias[$table].'.'.$this->alias[$field]] = $orders[$field];
- unset($orders[$field]);
- }
- }
- } else {
- foreach ($current_fields as $field) {
- // alias field
- for ($i = 0, $j = count($fields); $i < $j; $i++) {
- if ($field == $fields[$i]) {
- $fields[$i] = $this->alias[$fields[$i]].' AS '.$field;
- }
- }
- // alias filters
- // filters are aliased in createWhere
- // alias orders
- if (array_key_exists($field, $orders) && $this->alias[$field] != $field) {
- $orders[$this->alias[$field]] = $orders[$field];
- unset($orders[$field]);
- }
- }
- }
- if (empty($fields_not_yet_linked)) {
- break;
- }
- }
-
- if (!empty($fields_not_yet_linked)) {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR_QUERY_BUILDER, 'exception',
- array('reason' => 'not all fields ('.implode(', ', $fields_not_yet_linked).
- ') could be linked to a table ('.implode(', ', $selectable_tables).')')
- );
- return false;
- }
- return $tables;
- }
-
- /**
- * Recursively find all the tables that need to be joined to be able to select
- * all requested columns and to be able to filter the joined rows
- *
- * @param string name of the table from which to start looking for join points
- * @param array list of fields to fetch
- * @param array list of tables that are joined
- * @param array list of tables that may be joined to
- * @param array array of table already visisted to prevent infinite recursions
- * @return bool|array false on failure
- *
- * @access public
- */
- function createJoinFilter($root_table, $filters, $tables, $selectable_tables, $visited = array(), $depth = 0)
- {
- // table has been joint
- unset($tables[$root_table]);
-
- if (empty($tables)) {
- return array($filters, null, $visited);
- }
-
- // check for possible infinite recursion
- if (in_array($root_table, $visited)) {
- return false;
- }
- $visited[] = $root_table;
- $tables_orig = $tables;
-
- // find tables that can be join directly with the root table
- $direct_matches = array_intersect(array_keys($this->tables[$root_table]['joins']), array_intersect($selectable_tables, array_keys($tables)));
- foreach ($direct_matches as $table) {
- // handle multi column join
- if (is_array($this->tables[$root_table]['joins'][$table])) {
- foreach ($this->tables[$root_table]['joins'][$table] as $joinsource => $jointarget) {
- // both tables use a field to join
- if (isset($this->tables[$root_table]['fields'][$joinsource])
- && isset($this->tables[$table]['fields'][$jointarget])
- ) {
- $filters[] = $this->prefix.$this->alias[$root_table].'.'.$this->alias[$joinsource].' = '.
- $this->prefix.$this->alias[$table].'.'.$this->alias[$jointarget];
- // target table uses a field in the join and source table
- // a constant value
- } elseif (isset($this->tables[$table]['fields'][$jointarget])) {
- $value_quoted = $this->quote($joinsource, $this->fields[$jointarget]);
- if ($value_quoted === false) {
- return false;
- }
- $filters[] = $this->prefix.$this->alias[$table].'.'.$this->alias[$jointarget].' = '.$value_quoted;
- // source table uses a field in the join and target table
- // a constant value
- } elseif (isset($this->tables[$root_table]['fields'][$joinsource])) {
- $value_quoted = $this->quote($jointarget, $this->fields[$joinsource]);
- if ($value_quoted === false) {
- return false;
- }
- $filters[] = $this->prefix.$this->alias[$root_table].'.'.$this->alias[$joinsource].' = '.$value_quoted;
- // neither tables uses a field in the join
- } else {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR_QUERY_BUILDER, 'exception',
- array('reason' => 'join structure incorrect, one of the two needs to be a field')
- );
- return false;
- }
- }
- // handle single column join
- } else {
- $filters[] = $this->prefix.$this->alias[$root_table].'.'.$this->tables[$root_table]['joins'][$table].' = '.
- $this->prefix.$this->alias[$table].'.'.$this->tables[$table]['joins'][$root_table];
- }
- unset($tables[$table]);
- }
-
- // all tables have been joined
- if (empty($tables)) {
- return array($filters, null, $visited);
- }
-
- $tmp_filters = $filters;
- foreach ($direct_matches as $table) {
- $result = $this->createJoinFilter($table, $tmp_filters, $tables, $selectable_tables, $visited, ($depth+1));
- // check if the recursion was able to find a join that would reduce
- // the number of to be joined tables
- if (is_array($result)) {
- if (!$result[1]) {
- return $result;
- }
- $filters = $result[0];
- $tables = $result[1];
- }
- }
-
- // all tables have been joined
- if (empty($tables)) {
- return array($filters, null, $visited);
- }
-
- foreach ($this->tables[$root_table]['joins'] as $table => $fields) {
- // verify that the table is in the selectable_tables list
- if (!in_array($table, $selectable_tables)) {
- continue;
- }
- $tmp_filters = $filters;
- $tmp_tables = $tables;
- // handle multi column join
- if (is_array($fields)) {
- foreach ($fields as $joinsource => $jointarget) {
- // both tables use a field to join
- if (isset($this->tables[$root_table]['fields'][$joinsource])
- && isset($this->tables[$table]['fields'][$jointarget])
- ) {
- $tmp_filters[$this->prefix.$this->alias[$root_table].'.'.$this->alias[$joinsource]] =
- $this->prefix.$this->alias[$table].'.'.$this->alias[$jointarget];
- // target table uses a field in the join and source table
- // a constant value
- } elseif (isset($this->tables[$table]['fields'][$jointarget])) {
- $value_quoted = $this->quote($joinsource, $this->fields[$jointarget]);
- if ($value_quoted === false) {
- return false;
- }
- $tmp_filters[$this->prefix.$this->alias[$table].'.'.$this->alias[$jointarget]] = $value_quoted;
- // source table uses a field in the join and target table
- // a constant value
- } elseif (isset($this->tables[$root_table]['fields'][$joinsource])) {
- $value_quoted = $this->quote($jointarget, $this->fields[$joinsource]);;
- if ($value_quoted === false) {
- return false;
- }
- $tmp_filters[$this->prefix.$this->alias[$root_table].'.'.$this->alias[$joinsource]] = $value_quoted;
- // neither tables uses a field in the join
- } else {
- $this->stack->push(
- LIVEUSER_ADMIN_ERROR_QUERY_BUILDER, 'exception',
- array('reason' => 'join structure incorrect, one of the two needs to be a field')
- );
- return false;
- }
- }
- // handle single column join
- } else {
- $tmp_filters[$this->prefix.$this->alias[$root_table].'.'.$fields] =
- $this->prefix.$this->alias[$table].'.'.$fields;
- }
- // recurse
- $result = $this->createJoinFilter($table, $tmp_filters, $tmp_tables, $selectable_tables, $visited, ($depth+1));
- // check if the recursion was able to find a join that would reduce
- // the number of to be joined tables
- if (is_array($result)) {
- if (!$result[1]) {
- return $result;
- }
- $filters = $result[0];
- $tables = $result[1];
- }
- }
-
- // return false if list of tables was not reduced using the current root table
- if ($tables_orig === $tables) {
- return false;
- }
-
- // return the generated new filters and reduced table list
- return array($filters, $tables, $visited);
- }
-
- /**
- * Properly disconnect from database
- *
- * @return void
- *
- * @access public
- */
- function disconnect()
- {
- if ($this->dsn) {
- $result = $this->dbc->disconnect();
- if (PEAR::isError($result)) {
- $this->stack->push(
- LIVEUSER_ERROR, 'exception',
- array('reason' => $result->getMessage() . '-' . $result->getUserInfo())
- );
- return false;
- }
- $this->dbc = false;
- }
- return true;
- }
-}
-?>
+++ /dev/null
-<?php
-/**
- * Structures_DataGrid Class
- *
- * PHP versions 4 and 5
- *
- * LICENSE:
- *
- * Copyright (c) 1997-2007, Andrew Nagy <asnagy@webitecture.org>,
- * Olivier Guilyardi <olivier@samalyse.com>,
- * Mark Wiesemann <wiesemann@php.net>
- * Sascha Grossenbacher <saschagros@bluewin.ch>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * The names of the authors may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * CSV file id: $Id: DataGrid.php,v 1.1.1.1 2008/04/28 15:20:46 jamie Exp $
- *
- * @version $Revision: 1.1.1.1 $
- * @package Structures_DataGrid
- * @category Structures
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- */
-
-
-require_once 'PEAR.php';
-
-require_once 'Structures/DataGrid/Column.php';
-
-// Rendering Drivers
-define('DATAGRID_RENDER_TABLE', 'HTMLTable');
-define('DATAGRID_RENDER_SMARTY', 'Smarty');
-define('DATAGRID_RENDER_XML', 'XML');
-define('DATAGRID_RENDER_XLS', 'XLS');
-define('DATAGRID_RENDER_XUL', 'XUL');
-define('DATAGRID_RENDER_CSV', 'CSV');
-define('DATAGRID_RENDER_CONSOLE', 'Console');
-define('DATAGRID_RENDER_PAGER', 'Pager');
-define('DATAGRID_RENDER_SORTFORM', 'HTMLSortForm');
-
-define('DATAGRID_RENDER_DEFAULT', DATAGRID_RENDER_TABLE);
-
-// DataSource Drivers
-define('DATAGRID_SOURCE_ARRAY', 'Array');
-define('DATAGRID_SOURCE_DATAOBJECT','DataObject');
-define('DATAGRID_SOURCE_DB', 'DB');
-define('DATAGRID_SOURCE_XML', 'XML');
-define('DATAGRID_SOURCE_RSS', 'RSS');
-define('DATAGRID_SOURCE_CSV', 'CSV');
-define('DATAGRID_SOURCE_DBQUERY', 'DBQuery');
-define('DATAGRID_SOURCE_DBTABLE', 'DBTable');
-define('DATAGRID_SOURCE_MDB2', 'MDB2');
-
-// PEAR_Error code for unsupported features
-define('DATAGRID_ERROR_UNSUPPORTED', 1);
-
-/**
- * Structures_DataGrid Class
- *
- * A PHP class to implement the functionality provided by the .NET Framework's
- * DataGrid control. This class can produce a data driven list in many formats
- * based on a defined record set. Commonly, this is used for outputting an HTML
- * table based on a record set from a database or an XML document. It allows
- * for the output to be published in many ways, including an HTML table,
- * an HTML Template, an Excel spreadsheet, an XML document. The data can
- * be sorted and paged, each cell can have custom output, and the table can be
- * custom designed with alternating color rows.
- *
- * Quick Example:
- * <code>
- * <?php
- * require 'Structures/DataGrid.php';
- * $datagrid =& new Structures_DataGrid();
- * $options = array('dsn' => 'mysql://user:password@host/db_name');
- * $datagrid->bind("SELECT * FROM my_table", $options);
- * $datagrid->render();
- * ?>
- * </code>
- *
- * @author Andrew S. Nagy <asnagy@webitecture.org>
- * @author Olivier Guilyardi <olivier@samalyse.com>
- * @author Mark Wiesemann <wiesemann@php.net>
- * @author Sascha Grossenbacher <saschagros@bluewin.ch>
- * @access public
- * @package Structures_DataGrid
- * @category Structures
- */
-class Structures_DataGrid
-{
- /**
- * Renderer driver
- * @var object Structures_DataGrid_Renderer_* family
- * @access private
- */
- var $_renderer;
-
- /**
- * Renderer driver type
- * @var int DATAGRID_RENDER_* constant family
- * @access private
- */
- var $_rendererType = null;
-
- /**
- * Options to use for all renderers
- * @var array
- * @access private
- */
- var $_rendererCommonOptions = array();
-
- /**
- * Renderer driver backup
- * @var object Structures_DataGrid_Renderer_* family
- * @access private
- */
- var $_rendererBackup;
-
- /**
- * Renderer driver type backup
- * @var int DATAGRID_RENDER_* constant family
- * @access private
- */
- var $_rendererTypeBackup = null;
-
- /**
- * Whether the backup is an empty renderer
- *
- * This property is set to true when _saveRenderer() is called and there
- * is no renderer loaded.
- *
- * @var bool
- * @access private
- */
- var $_rendererEmptyBackup = false;
-
- /**
- * Array of columns. Columns are defined as a DataGridColumn object.
- * @var array
- * @access private
- */
- var $columnSet = array();
-
- /**
- * Array of records.
- * @var array
- * @access private
- */
- var $recordSet = array();
-
- /**
- * The Data Source Driver object
- * @var object Structures_DataGrid_DataSource
- * @access private
- */
- var $_dataSource;
-
- /**
- * Fields/directions to sort the data by
- *
- * @var array Structure: array(fieldName => direction, ....)
- * @access private
- */
- var $sortSpec = array();
-
- /**
- * Default fields/directions to sort the data by
- *
- * @var array Structure: array(fieldName => direction, ....)
- * @access private
- */
- var $defaultSortSpec = array();
-
- /**
- * Limit of records to show per page.
- * @var string
- * @access private
- */
- var $rowLimit;
-
- /**
- * The current page to show.
- * @var string
- * @access private
- */
- var $page;
-
- /**
- * Whether the page number was provided at instantiation or not
- * @var bool
- * @access private
- */
- var $_forcePage;
-
- /**
- * GET/POST/Cookie parameters prefix
- * @var string
- * @access private
- */
- var $_requestPrefix = '';
-
- /**
- * Possible renderer types and their equivalent renderer constants
- * @var array
- * @access private
- */
- var $_rendererTypes = array(
- 'html_table' => DATAGRID_RENDER_TABLE,
- 'smarty' => DATAGRID_RENDER_SMARTY,
- 'spreadsheet_excel_writer_workbook' => DATAGRID_RENDER_XLS,
- 'console_table' => DATAGRID_RENDER_CONSOLE,
- 'pager_common' => DATAGRID_RENDER_PAGER,
- );
-
- /**
- * Number of records that should be buffered when streaming is enabled
- * @var integer
- * @access private
- */
- var $_bufferSize = null;
-
- /**
- * Array of matched params
- *
- * @var array
- * @access private
- */
- var $_mapperMatch = null;
-
- /**
- * Allowed URL parameters. Format: Name => regex
- *
- * @var array
- * @access private
- */
- var $_mapperRules = array(
- 'page' => '[0-9]+',
- 'orderBy' => '[^\/]+',
- 'direction' => '(ASC|DESC|asc|desc)'
- );
-
- /**
- * Default values for mapper. Format: Name => value
- *
- * A default value triggers the param to be optional
- *
- * @var array
- * @access private
- */
- var $_mapperDefaults = array(
- 'orderBy' => null,
- 'direction' => null,
- 'page' => 1
- );
-
- /**
- * URL mapper instance, if activated
- *
- * @var object Net_URL_Mapper
- * @access protected
- */
- var $_urlMapper = null;
-
- /**
- * Constructor
- *
- * Builds the DataGrid class. The Core functionality and Renderer are
- * seperated for maintainability and to keep cohesion high.
- *
- * @example constructor.php Instantiation
- * @param string $limit The number of records to display per page.
- * @param int $page The current page viewed.
- * In most cases, this is useless.
- * Note: if you specify this, the "page" GET
- * variable will be ignored.
- * @param string $rendererType The type of renderer to use.
- * You may prefer to use the $type argument
- * of {@link render}, {@link fill} or
- * {@link getOutput}
- *
- * @return void
- * @access public
- */
- function Structures_DataGrid($limit = null, $page = null,
- $rendererType = null)
- {
- // Set the defined rowlimit
- $this->rowLimit = $limit;
-
- //Use set page number, otherwise automatically detect the page number
- if (!is_null($page)) {
- $this->page = $page;
- $this->_forcePage = true;
- } else {
- $this->page = 1;
- $this->_forcePage = false;
- }
-
- // Automatic handling of GET/POST/COOKIE variables
- $this->_parseHttpRequest();
-
- if (!is_null($rendererType)) {
- $this->setRenderer($rendererType);
- }
- }
-
- /**
- * Method used for debugging purposes only. Displays a dump of the DataGrid
- * object.
- *
- * @access public
- * @return void
- */
- function dump()
- {
- echo '<pre>';
- print_r($this);
- echo '</pre>';
- }
-
- /**
- * Checks if a file exists in the include path
- *
- * @access private
- * @param string filename
- * @return boolean true success and false on error
- */
- function fileExists($file)
- {
- $fp = @fopen($file, 'r', true);
- if (is_resource($fp)) {
- @fclose($fp);
- return true;
- }
- return false;
- }
-
- /**
- * Checks if a class exists without triggering __autoload
- *
- * @param string className
- * @return bool true success and false on error
- *
- * @access private
- */
- function classExists($className)
- {
- if (version_compare(phpversion(), "5.0", ">=")) {
- return class_exists($className, false);
- }
- return class_exists($className);
- }
-
- /**
- * Load a Renderer or DataSource driver
- *
- * @param string $className Name of the driver class
- * @access private
- * @return object The driver object or a PEAR_Error
- * @static
- */
- function &loadDriver($className)
- {
- if (!Structures_DataGrid::classExists($className)) {
- $fileName = str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
- if (!include_once($fileName)) {
- if (!Structures_DataGrid::fileExists($fileName)) {
- $msg = "unable to find package '$className' file '$fileName'";
- } else {
- $msg = "unable to load driver class '$className' from file '$fileName'";
- }
- $error = PEAR::raiseError($msg);
- return $error;
- }
- }
-
- $driver =& new $className();
- return $driver;
- }
-
- /**
- * Datasource driver Factory
- *
- * A clever method which loads and instantiate data source drivers.
- *
- * Can be called in various ways:
- *
- * Detect the source type and load the appropriate driver with default
- * options:
- * <code>
- * $driver =& Structures_DataGrid::dataSourceFactory($source);
- * </code>
- *
- * Detect the source type and load the appropriate driver with custom
- * options:
- * <code>
- * $driver =& Structures_DataGrid::dataSourceFactory($source, $options);
- * </code>
- *
- * Load a driver for an explicit type (faster, bypasses detection routine):
- * <code>
- * $driver =& Structures_DataGrid::dataSourceFactory($source, $options, $type);
- * </code>
- *
- * @access public
- * @param mixed $source The data source respective to the driver
- * @param array $options An associative array of the form:
- * array(optionName => optionValue, ...)
- * @param string $type The data source type constant (of the form
- * DATAGRID_SOURCE_*)
- * @uses Structures_DataGrid::_detectSourceType()
- * @return Structures_DataGrid_DataSource|PEAR_Error
- * driver object or PEAR_Error on failure
- * @static
- */
- function &dataSourceFactory($source, $options = array(), $type = null)
- {
- if (is_null($type) &&
- !($type = Structures_DataGrid::_detectSourceType($source,
- $options))) {
- $error = PEAR::raiseError('Unable to determine the data source type. '.
- 'You may want to explicitly specify it.');
- return $error;
- }
-
- $type = Structures_DataGrid::_correctDriverName($type, 'DataSource');
- if (PEAR::isError($type)) {
- return $type;
- }
-
- $className = "Structures_DataGrid_DataSource_$type";
-
- if (PEAR::isError($driver =& Structures_DataGrid::loadDriver($className))) {
- return $driver;
- }
-
- $result = $driver->bind($source, $options);
-
- if (PEAR::isError($result)) {
- return $result;
- } else {
- return $driver;
- }
- }
-
- /**
- * Renderer driver factory
- *
- * Load and instantiate a renderer driver.
- *
- * @access private
- * @param mixed $source The rendering container respective to the driver
- * @param array $options An associative array of the form:
- * array(optionName => optionValue, ...)
- * @param string $type The renderer type constant (of the form
- * DATAGRID_RENDER_*)
- * @uses Structures_DataGrid_DataSource::_detectRendererType()
- * @return mixed Returns the renderer driver object or
- * PEAR_Error on failure
- */
- function &rendererFactory($type, $options = array())
- {
- $type = Structures_DataGrid::_correctDriverName($type, 'Renderer');
- if (PEAR::isError($type)) {
- return $type;
- }
-
- $className = "Structures_DataGrid_Renderer_$type";
-
- if (PEAR::isError($driver =& Structures_DataGrid::loadDriver($className))) {
- return $driver;
- }
-
- $options = array_merge($this->_rendererCommonOptions, $options);
- if ($this->_urlMapper) {
- $driver->setUrlMapper($this->_urlMapper);
- }
- if ($options) {
- $driver->setOptions((array)$options);
- }
-
- return $driver;
- }
-
- /**
- * Render the datagrid
- *
- * You can call this method several times with different renderers.
- *
- * @param mixed $renderer Renderer type or instance (optional)
- * @param array $options An associative array of the form:
- * array(optionName => optionValue, ...)
- * @access public
- * @return mixed True or PEAR_Error
- */
- function render($renderer = null, $options = array())
- {
- if (!is_null($renderer)) {
- $this->_saveRenderer();
-
- if (is_a($renderer, 'Structures_DataGrid_Renderer')) {
- $result = $this->attachRenderer($renderer);
- } else {
- $result = $this->setRenderer($renderer);
- }
- if (PEAR::isError($result)) {
- $this->_restoreRenderer();
- return $result;
- }
- } else if (!isset($this->_renderer)) {
- $result = $this->setRenderer(DATAGRID_RENDER_DEFAULT);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
-
- $options = array_merge($this->_rendererCommonOptions, (array)$options);
- if ($options) {
- $this->_renderer->setOptions($options);
- }
-
- if (!$this->_renderer->isBuilt()) {
- $result = $this->build();
- if (PEAR::isError($result)) {
- return $result;
- }
- }
-
- $result = $this->_renderer->render();
- if (PEAR::isError($result)) {
- if ($result->getCode() == DATAGRID_ERROR_UNSUPPORTED) {
- $type = is_null($this->_rendererType)
- ? get_class($this->_renderer)
- : $this->_rendererType;
- $this->_restoreRenderer();
- return PEAR::raiseError("The $type driver does not support the ".
- "render() method. Try using fill().");
- } else {
- $this->_restoreRenderer();
- return $result;
- }
- }
- $this->_restoreRenderer();
-
- return true;
- }
-
- /**
- * Return the datagrid output
- *
- * @param int $type Renderer type (optional)
- * @param array $options An associative array of the form:
- * array(optionName => optionValue, ...)
- * @access public
- * @return mixed The datagrid output (Usually a string: HTML, CSV, etc...)
- * or a PEAR_Error
- */
- function getOutput($type = null, $options = array())
- {
- if (!is_null($this->_bufferSize)) {
- return PEAR::raiseError('getOutput() cannot be used together with ' .
- 'streaming.');
- }
-
- if (!is_null($type)) {
- $this->_saveRenderer();
-
- $test = $this->setRenderer($type);
- if (PEAR::isError($test)) {
- $this->_restoreRenderer();
- return $test;
- }
- } else if (!isset($this->_renderer)) {
- $this->setRenderer(DATAGRID_RENDER_DEFAULT);
- }
-
- $options = array_merge($this->_rendererCommonOptions, (array)$options);
- if ($options) {
- $this->_renderer->setOptions($options);
- }
-
- if (!$this->_renderer->isBuilt()) {
- $result = $this->build();
- if (PEAR::isError($result)) {
- return $result;
- }
- }
-
- $output = $this->_renderer->getOutput();
- if (PEAR::isError($output) && $output->getCode() == DATAGRID_ERROR_UNSUPPORTED) {
- $type = is_null($this->_rendererType)
- ? get_class($this->_renderer)
- : $this->_rendererType;
- $this->_restoreRenderer();
- return PEAR::raiseError("The $type driver does not support the ".
- "getOutput() method. Try using render().");
- }
-
- $this->_restoreRenderer();
- return $output;
- }
-
- /**
- * Get the current or default Rendering driver
- *
- * Retrieves the renderer object as a reference
- *
- * @return object Renderer object reference
- * @access public
- */
- function &getRenderer()
- {
- isset($this->_renderer) or $this->setRenderer(DATAGRID_RENDER_DEFAULT);
- return $this->_renderer;
- }
-
- /**
- * Get the currently loaded DataSource driver
- *
- * Retrieves the DataSource object as a reference
- *
- * @return object DataSource object reference or null if no driver is loaded
- * @access public
- */
- function &getDataSource()
- {
- if (isset($this->_dataSource)) {
- return $this->_dataSource;
- }
- return null;
- }
-
- /**
- * Set Renderer
- *
- * Defines which renderer to be used by the DataGrid based on given
- * $type and $options. To attach an existing renderer instance, use
- * attachRenderer() instead.
- *
- * @param string $type The defined renderer string
- * @param array $options Rendering options
- * @return mixed Renderer instance or PEAR_Error
- * @access public
- * @see Structures_DataGrid::attachRenderer()
- */
- function &setRenderer($type, $options = array())
- {
- $renderer =& $this->rendererFactory($type, $options);
- if (PEAR::isError($renderer)) {
- return $renderer;
- }
- $this->_rendererType = $type;
- return $this->attachRenderer($renderer);
- }
-
- /**
- * Backup the current renderer
- *
- * @return void
- * @access private
- */
- function _saveRenderer()
- {
- if (isset($this->_renderer)) {
- // The following line is a workaround for PHP bug 32660
- // See: http://bugs.php.net/bug.php?id=32660
- // Another solution would be to remove __get which is used only for BC
- $this->_rendererBackup = 1;
-
- $this->_rendererBackup =& $this->_renderer;
- $this->_rendererTypeBackup = $this->_rendererType;
-
- unset($this->_renderer);
- $this->_rendererType = null;
- } else {
- $this->_rendererEmptyBackup = true;
- }
- }
-
- /**
- * Restore a previously saved renderer
- *
- * If the $_renderer property was not set when _saveRenderer() got
- * previously called, _restoreRenderer() will unset it.
- *
- * @return void
- * @access private
- */
- function _restoreRenderer()
- {
- if ($this->_rendererEmptyBackup) {
- unset($this->_renderer);
- $this->_rendererType = null;
- } elseif (isset($this->_rendererBackup)) {
- $this->_renderer =& $this->_rendererBackup;
- $this->_rendererType = $this->_rendererTypeBackup;
- }
-
- unset($this->_rendererBackup);
- $this->_rendererTypeBackup = null;
- $this->_rendererEmptyBackup = false;
- }
-
- /**
- * Tell the renderer how the data is sorted
- *
- * This method takes the "multiSort" capabilities of the datasource
- * into account. The idea is to correctly inform the renderer : for
- * example, a GET request may contain multiple fields and directions
- * to sort by. But, if the datasource does not support "multiSort"
- * then the renderer should not be told that the data is sorted according
- * to multiple fields.
- *
- * It also properly set the "multiSortCapable" renderer flag (second argument
- * to Renderer::setCurrentSorting()).
- *
- * This method requires both a datasource and renderer to be loaded.
- *
- * It should be called even if $sortSpec is empty.
- *
- * @return void
- * @access private
- */
- function _setRendererCurrentSorting()
- {
- $sortSpec = $this->sortSpec ? $this->sortSpec : $this->defaultSortSpec;
- if (isset($this->_dataSource)
- && $this->_dataSource->hasFeature('multiSort')
- ) {
- $this->_renderer->setCurrentSorting($sortSpec, true);
- } else {
- reset($sortSpec);
- list($field, $direction) = each($sortSpec);
- $this->_renderer->setCurrentSorting(
- array($field => $direction), false);
- }
- }
-
- /**
- * Attach an already instantiated Rendering driver
- *
- * @param object $renderer Driver object, subclassing
- * Structures_DataGrid_Renderer
- * @return mixed Renderer instance or a PEAR_Error object
- * @access public
- * @see Structures_DataGrid::setRenderer()
- */
- function &attachRenderer(&$renderer)
- {
- if (is_subclass_of($renderer, 'structures_datagrid_renderer')) {
- // The following line is a workaround for PHP bug 32660
- // See: http://bugs.php.net/bug.php?id=32660
- $this->_renderer = 1;
-
- $this->_renderer =& $renderer;
- if (isset($this->_dataSource)) {
- $this->_renderer->setColumns($this->columnSet);
- $this->_renderer->setLimit($this->page, $this->rowLimit,
- $this->getRecordCount());
- $this->_setRendererCurrentSorting();
- }
- if ($this->_requestPrefix) {
- $this->_renderer->setRequestPrefix($this->_requestPrefix);
- }
-
- } else {
- return PEAR::raiseError('Invalid renderer type, ' .
- 'must be a valid renderer driver class');
- }
-
- return $renderer;
- }
-
- /**
- * Fill a rendering container with data
- *
- * @example fill-sortform.php Fill a form with sort fields
- * @example fill-pager.php Filling a Pager object
- * @param object &$container A rendering container of any of the supported
- * types (example: an HTML_Table object,
- * a Spreadsheet_Excel_Writer object, etc...)
- * @param array $options Options for the corresponding rendering driver
- * @param string $type Explicit type in case the container type
- * can't be detected
- * @return mixed Either true or a PEAR_Error object
- * @access public
- */
- function fill(&$container, $options = array(), $type = null)
- {
- if (is_null($type)) {
- $type = $this->_detectRendererType($container);
- if (is_null($type)) {
- return PEAR::raiseError('The rendering container type can not '.
- 'be automatically detected. Please ' .
- 'specify its type explicitly.');
- }
- }
-
- /* Is a renderer driver already loaded and does it exactly match
- * the driver class name that corresponds to $type ? */
- //FIXME: is this redundant with the $rendererType property ?
- if (!isset($this->_renderer)
- or !is_a($this->_renderer, "Structures_DataGrid_Renderer_$type")) {
- /* No, then load the right driver */
- $this->_saveRenderer();
- if (PEAR::isError($test = $this->setRenderer($type, $options))) {
- $this->_restoreRenderer();
- return $test;
- }
- } else {
- $options = array_merge($this->_rendererCommonOptions, (array)$options);
- $this->_renderer->setOptions($options);
- }
-
- $test = $this->_renderer->setContainer($container);
- if (PEAR::isError($test)) {
- if ($test->getCode() == DATAGRID_ERROR_UNSUPPORTED) {
- $this->_restoreRenderer();
- return PEAR::raiseError("The $type driver does not support the " .
- "fill() method. Try using render().");
- } else {
- $this->_restoreRenderer();
- return $test;
- }
- }
-
- if (!$this->_renderer->isBuilt()) {
- $result = $this->build();
- if (PEAR::isError($result)) {
- return $result;
- }
- }
-
- $this->_restoreRenderer();
- return true;
- }
-
- /**
- * Create Default Columns
- *
- * This method handles the instantiation of default column objects,
- * when some records have been fetched from the datasource but columns
- * have neither been generated, nor provided by the user.
- *
- * @access private
- * @return void
- */
- function _createDefaultColumns()
- {
- if (empty($this->columnSet)) {
- $this->generateColumns();
- }
- }
-
- /**
- * Retrieves the current page number when paging is implemented
- *
- * @return int the current page number
- * @access public
- */
- function getCurrentPage()
- {
- return $this->page;
- }
-
- /**
- * Define the current page number.
- *
- * This method is used when paging is implemented
- *
- * @access public
- * @param mixed $page The current page number (as string or int).
- */
- function setCurrentPage($page)
- {
- $this->page = $page;
- }
-
- /**
- * Returns the total number of pages
- *
- * @return int the total number of pages or 1 if there are no records
- * or if there is no row limit
- * @access public
- */
- function getPageCount()
- {
- if (is_null($this->rowLimit) || $this->getRecordCount() == 0) {
- return 1;
- } else {
- return ceil($this->getRecordCount() / $this->rowLimit);
- }
- }
-
- /**
- * Returns the number of columns
- *
- * @return int the number of columns
- * @access public
- */
- function getColumnCount()
- {
- return count($this->columnSet);
- }
-
- /**
- * Returns the total number of records
- *
- * @return int the total number of records
- * @access public
- */
- function getRecordCount()
- {
- if (isset($this->_dataSource)) {
- return $this->_dataSource->count();
- } else {
- // If there is no datasource then there is no data. The old way
- // of putting an array into the recordSet property does not exist
- // anymore. Binding an array loads the Array datasource driver.
- return 0;
- }
- }
-
- /**
- * Returns the number of the first record of the current page
- *
- * @return int the number of the first record currently shown, or: 0
- * if there are no records, 1 if there is no row limit
- * @access public
- */
- function getCurrentRecordNumberStart()
- {
- if (is_null($this->page)) {
- return 1;
- } elseif ($this->getRecordCount() == 0) {
- return 0;
- } else {
- return ($this->page - 1) * $this->rowLimit + 1;
- }
- }
-
- /**
- * Returns the number of the last record of the current page
- *
- * @return int the number of the last record currently shown
- * @access public
- */
- function getCurrentRecordNumberEnd()
- {
- if (is_null($this->rowLimit)) {
- return $this->getRecordCount();
- } else {
- return
- min($this->getCurrentRecordNumberStart() + $this->rowLimit - 1,
- $this->getRecordCount());
- }
- }
-
- /**
- * Set the global GET/POST variables prefix
- *
- * If you need to change the request variables, you can define a prefix.
- * This is extra useful when using multiple datagrids.
- *
- * This methods need to be called before bind().
- *
- * @access public
- * @param string $prefix The prefix to use on request variables;
- */
- function setRequestPrefix($prefix)
- {
- $this->_requestPrefix = $prefix;
- $this->_parseHttpRequest();
-
- if (isset($this->_renderer)) {
-
- $this->_renderer->setRequestPrefix($prefix);
-
- /* We just called parseHttpRequest() using a new requestPrefix.
- * The page and sort request might have changed, so we need
- * to pass them again to the renderer */
- $this->_renderer->setLimit($this->page, $this->rowLimit,
- $this->getRecordCount());
- $this->_setRendererCurrentSorting();
- }
- }
-
- /**
- * Add a column, with optional position
- *
- * @example addColumn.php Adding a simple column
- * @access public
- * @param object $column The Structures_DataGrid_Column object
- * (reference to)
- * @param string $position One of: "last", "first", "after" or "before"
- * (default: "last")
- * @param string $relativeTo The name (label) or field name of the
- * relative column, if $position is "after"
- * or "before"
- * @return mixed PEAR_Error on failure, void otherwise
- */
- function addColumn(&$column, $position = 'last', $relativeTo = null)
- {
- if (!is_a($column, 'structures_datagrid_column')) {
- return PEAR::raiseError(__FUNCTION__ . "(): not a valid ".
- " Structures_DataGrid_Column object");
- } else {
- switch ($position) {
- case 'first':
- array_unshift($this->columnSet, '');
- $this->columnSet[0] =& $column;
- break;
- case 'last':
- $this->columnSet[] =& $column;
- break;
- case 'after':
- case 'before':
- $this->_createDefaultColumns();
- // Has a relative column been specified ?
- if (is_null($relativeTo)) {
- return PEAR::raiseError(
- __FUNCTION__ . "(): a relative column must be".
- "specified when using position \"$position\"");
- }
- // Yes, does it exist ?
- foreach ($this->columnSet as $i => $relColumn) {
- if ($relColumn->columnName == $relativeTo
- || $relColumn->fieldName == $relativeTo) {
- $relIndex = $i;
- }
- }
- // If it does not exist, return an error
- if (!isset($relIndex)) {
- return PEAR::raiseError(
- __FUNCTION__ . "(): Can't find a relative ".
- "column which name or field name is: ".
- $relativeTo);
- }
- // It exists, add the column after or before it
- if ($position == 'after') {
- array_splice($this->columnSet, $relIndex + 1, 0, '');
- $this->columnSet[$relIndex + 1] =& $column;
- } else {
- array_splice($this->columnSet, $relIndex, 0, '');
- $this->columnSet[$relIndex] =& $column;
- }
- break;
- }
- }
- }
-
- /**
- * Return the current columns
- *
- * @return array Structures_DataGrid_Column objects (references to).
- * This is a numerically indexed array (starting from 0).
- * @access public
- */
- function getColumns()
- {
- $this->_createDefaultColumns();
-
- // Cloning the column set to prevent users from playing with our
- // internal $columnSet property.
- $columnSetClone = array();
-
- $columnCount = $this->getColumnCount();
- for ($i = 0; $i < $columnCount; $i++) {
- $columnSetClone[$i] =& $this->columnSet[$i];
- }
-
- return $columnSetClone;
- }
-
- /**
- * Find a column by name (label)
- *
- * @access public
- * @param string $name The name (label) of the column to look for
- * @return object Either the column object (reference to) or
- * false if there is no such column
- */
- function &getColumnByName($name)
- {
- $this->_createDefaultColumns();
- foreach ($this->columnSet as $key => $column) {
- if ($column->columnName === $name) {
- return $this->columnSet[$key];
- }
- }
- $ret = false;
- return $ret;
- }
-
- /**
- * Find a column by field name
- *
- * @access public
- * @param string $fieldName The field name of the column to look for
- * @return object Either the column object (reference to) or
- * false if there is no such column
- */
- function &getColumnByField($fieldName)
- {
- $this->_createDefaultColumns();
- foreach ($this->columnSet as $key => $column) {
- if ($column->fieldName === $fieldName) {
- return $this->columnSet[$key];
- }
- }
- $ret = false;
- return $ret;
- }
-
- /**
- * Remove a column
- *
- * @example removeColumn.php Remove an unneeded column
- * @access public
- * @param object $column The Structures_DataGrid_Column object
- * (reference to)
- * @return void
- */
- function removeColumn(&$column)
- {
- $columnCount = count($this->columnSet);
- for ($i = 0; $i < $columnCount; $i++) {
- if ($this->columnSet[$i]->id == $column->id) {
- for ($i++; $i < $columnCount; $i++) {
- $this->columnSet[$i - 1] =& $this->columnSet[$i];
- }
- array_pop($this->columnSet);
- }
- }
- }
-
- /**
- * A simple way to add a record set to the datagrid
- *
- * @example bind-dataobject.php Bind a DB_DataObject
- * @example bind-sql.php Bind an SQL query
- * @access public
- * @param mixed $container The record set in any of the supported data
- * source types
- * @param array $options Optional. The options to be used for the
- * data source
- * @param string $type Optional. The data source type
- * @return bool True if successful, otherwise PEAR_Error.
- */
- function bind($container, $options = array(), $type = null)
- {
- $source =& Structures_DataGrid::dataSourceFactory($container, $options,
- $type);
- if (!PEAR::isError($source)) {
- return $this->bindDataSource($source);
- } else {
- return $source;
- }
- }
-
- /**
- * Bind an already instantiated DataSource driver
- *
- * @access public
- * @param mixed &$source The data source driver object
- * @return mixed True if successful, otherwise PEAR_Error
- */
- function bindDataSource(&$source)
- {
- if (is_subclass_of($source, 'structures_datagrid_datasource')) {
- $this->_dataSource =& $source;
- $result = $this->fetchDataSource();
- if (PEAR::isError($result)) {
- return $result;
- }
- if ($columnSet = $this->_dataSource->getColumns()) {
- $this->columnSet = array_merge($this->columnSet, $columnSet);
- }
- } else {
- return PEAR::raiseError('Invalid data source type, ' .
- 'must be a valid data source driver class');
- }
-
- return true;
- }
-
- /**
- * Request the datasource to sort its data
- *
- * @return void
- * @access private
- */
- function _sortDataSource()
- {
- if (!empty($this->sortSpec)) {
- if ($this->_dataSource->hasFeature('multiSort')) {
- $this->_dataSource->sort($this->sortSpec);
- } else {
- reset($this->sortSpec);
- list($sortBy, $direction) = each($this->sortSpec);
- $this->_dataSource->sort($sortBy, $direction);
- }
- }
- }
-
- /**
- * Fetch data from the datasource
- *
- * @param integer $startRow Start fetching from the specified row number
- * (optional)
- * @return mixed Either true or a PEAR_Error object
- * @access private
- */
- function fetchDataSource($startRow = null)
- {
- if (isset($this->_dataSource)) {
- // Sort the data
- if (empty($this->sortSpec) and $this->defaultSortSpec) {
- $this->sortSpec = $this->defaultSortSpec;
- }
-
- $this->_sortDataSource();
-
- // is streaming enabled or not?
- if (is_null($this->_bufferSize)) {
- // sometimes we have to fix the page number:
- // if we have a row limit, a page number lower than 1, or greater
- // than 1 and the real page count is lower than the given page
- // number indicates, the page number will be set to 1
- if (!is_null($this->rowLimit) && ($this->page < 1 ||
- ($this->page > 1 && $this->getPageCount() < $this->page))
- ) {
- $this->page = 1;
- }
-
- // Determine page
- $page = $this->page ? $this->page - 1 : 0;
-
- // Fetch the data
- $recordSet = $this->_dataSource->fetch(
- ($page * $this->rowLimit),
- $this->rowLimit);
- } else {
- $limit = $this->_bufferSize;
- if (!is_null($this->rowLimit) && $limit > $this->rowLimit) {
- $limit = $this->rowLimit;
- }
-
- // Fetch the data
- $recordSet = $this->_dataSource->fetch($startRow, $limit);
- }
-
- if (PEAR::isError($recordSet)) {
- return $recordSet;
- } else {
- $this->recordSet = $recordSet;
- return true;
- }
- } else {
- return PEAR::raiseError("Cannot fetch data: no datasource driver loaded.");
- }
- }
-
- /**
- * Sorts the records by the defined field.
- *
- * Do not use this method if data is coming from a database as sorting
- * is much faster coming directly from the database itself.
- *
- * @access public
- * @param array $sortSpec Sorting specification
- * Structure: array(fieldName => direction, ...)
- * @param string $direction Deprecated. Put the direction(s) into
- * $sortSpec
- * @return void
- */
- function sortRecordSet($sortSpec, $direction = 'ASC')
- {
- if (is_array($sortSpec)) {
- $this->sortSpec = $sortSpec;
- } else {
- $this->sortSpec = array($sortSpec => $direction);
- }
-
- if (isset($this->_dataSource)) {
- $this->_sortDataSource();
- }
- }
-
- /**
- * Set default sorting specification
- *
- * If there is no sorting query in the HTTP request, and if the
- * sortRecordSet() method is not called, then the specification
- * passed to setDefaultSort() will be used.
- *
- * This is especially useful if you want the data to already be
- * sorted when a user first see the datagrid.
- *
- * This method needs to be called before bind().
- *
- * @param array $sortSpec Sorting specification
- * Structure: array(fieldName => direction, ...)
- * @return mixed Either true or a PEAR_Error object
- * @access public
- */
- function setDefaultSort($sortSpec)
- {
- if (!is_array($sortSpec)) {
- return PEAR::raiseError('Invalid parameter, array expected');
- }
- $this->defaultSortSpec = $sortSpec;
- return true;
- }
-
- /**
- * Read an HTTP request argument
- *
- * This methods take the $_requestPrefix into account, and respect the
- * POST, GET, COOKIE read order.
- *
- * @param string $name Argument name
- * @return mixed Argument value or null
- * @access private
- */
- function _getRequestArgument($name)
- {
- $value = null;
- if (is_array($this->_mapperMatch)) {
- if (isset($this->_mapperMatch[$name])) {
- return $this->_mapperMatch[$name];
- }
- }
-
- $prefix = $this->_requestPrefix;
- if (isset($_REQUEST["$prefix$name"])) {
- if (isset($_POST["$prefix$name"])) {
- $value = $_POST["$prefix$name"];
- } elseif (isset($_GET["$prefix$name"])) {
- $value = $_GET["$prefix$name"];
- } elseif (isset($_COOKIE["$prefix$name"])) {
- $value = $_COOKIE["$prefix$name"];
- }
- }
- return $value;
- }
-
- /**
- * Secure the sort direction string
- *
- * @param string $str Direction string
- * @return string Either ASC or DESC
- * @access private
- */
- function _secureDirection($str)
- {
- $str = strtoupper($str);
- return ($str == 'ASC' or $str == 'DESC') ? $str : 'ASC';
- }
-
- /**
- * Parse HTTP Request parameters
- *
- * Determine page, sort and direction values
- *
- * @access private
- * @return array Associative array of parsed arguments, each of these
- * defaulting to null if not found.
- */
- function _parseHttpRequest()
- {
- //FIXME: with two grids on the same page, one grid with an empty prefix
- //and the other with a non-empty prefix, the first interfers with the
- //second, because _parseHttpRequest() is called from the constructor
- //before setRequestPrefix().
-
- if (!$this->_forcePage) {
- if (!($this->page = $this->_getRequestArgument('page'))) {
- $this->page = 1;
- }
- if (!is_numeric($this->page)) {
- $this->page = 1;
- }
- }
-
- if (($orderBy = $this->_getRequestArgument('orderBy')) !== null) {
- if (is_array($orderBy)) {
- $direction = $this->_getRequestArgument('direction');
- $this->sortSpec = array();
- foreach ($orderBy as $index => $field) {
- if (!empty($field)) {
- $this->sortSpec[$field] =
- $this->_secureDirection($direction[$index]);
- }
- }
- } else {
- if (!($direction = $this->_getRequestArgument('direction'))) {
- $direction = 'ASC';
- }
- $this->sortSpec =
- array($orderBy => $this->_secureDirection($direction));
- }
- }
- }
-
- /**
- * Detect datasource container type
- *
- * @param mixed $source Some kind of source
- * @param array $options Options passed to dataSourceFactory()
- * @return string The type constant of this source or null if
- * it couldn't be detected
- * @access private
- * @todo Add CSV detector. Possible rewrite in IFs to allow for
- * hierarchy for seperating file handle sources from others
- */
- function _detectSourceType($source, $options = array())
- {
- switch(true) {
- // DB_DataObject
- case is_object($source) && is_subclass_of($source, 'db_dataobject'):
- return DATAGRID_SOURCE_DATAOBJECT;
-
- // DB_Result
- case strtolower(get_class($source)) == 'db_result':
- return DATAGRID_SOURCE_DB;
-
- // Array
- case is_array($source):
- return DATAGRID_SOURCE_ARRAY;
-
- // RSS
- case is_string($source) && stristr('<rss', $source):
- case is_string($source) && stristr('<rdf:RDF', $source):
- case is_string($source) && strpos($source, '.rss') !== false:
- return DATAGRID_SOURCE_RSS;
-
- // XML
- case is_string($source) && preg_match('#^ *<\?xml#', $source) === 1:
- return DATAGRID_SOURCE_XML;
-
- // SQL query based drivers
- case is_string($source) &&
- preg_match('#SELECT\s.+\sFROM#is', $source) === 1:
- if (array_key_exists('dbc', $options)) {
- switch (true) {
- case is_subclass_of($options['dbc'], 'db_common'):
- return 'DBQuery';
- case is_subclass_of($options['dbc'], 'PDO'):
- return 'PDO';
- }
- }
- return 'MDB2'; // default driver for SQL queries
-
- // DB_Table
- case is_object($source) && is_subclass_of($source, 'db_table'):
- return DATAGRID_SOURCE_DBTABLE;
-
- default:
- return null;
- }
- }
-
- /**
- * Detect rendering container type
- *
- * @param object $container The rendering container
- * @return string The container type or null if unrecognized
- * @access private
- */
- function _detectRendererType(&$container)
- {
- foreach ($this->_rendererTypes as $class => $type) {
- if (is_a($container, $class)) {
- return $type;
- }
- }
-
- return null;
- }
-
- /**
- * Correct the (file)name of a driver
- *
- * @param string $name The name of the driver
- * @param string $type The type of the driver
- * @return mixed Either true or a PEAR_Error object
- * @access private
- */
- function _correctDriverName($name, $type)
- {
- $driverNameMap = array(
- 'DataSource' => array(
- 'DBDataObject' => 'DataObject',
- 'XLS' => 'Excel'
- ),
- 'Renderer' => array(
- 'ConsoleTable' => 'Console',
- 'Excel' => 'XLS'
- )
- );
-
- // replace underscores (e.g. HTML_Table driver has filename HTMLTable.php)
- $name = str_replace('_', '', $name);
-
- // does the file exist?
- if (Structures_DataGrid::fileExists("Structures/DataGrid/$type/$name.php")) {
- return $name;
- }
-
- // check, whether a name mapping exists (e.g. from 'Excel' to 'XLS')
- if (isset($driverNameMap[$type][$name])) {
- return $driverNameMap[$type][$name];
- }
-
- // we could not find a valid driver name => return an error
- $error = PEAR::raiseError("Unknown $type driver. Please specify an " .
- 'existing driver.');
- return $error;
- }
-
- /**
- * Build the datagrid
- *
- * @return mixed Either true or a PEAR_Error object
- * @access public
- */
- function build()
- {
- if (isset($this->_dataSource)) {
- isset($this->_renderer) or $this->setRenderer(DATAGRID_RENDER_DEFAULT);
- // is streaming enabled or not?
- if (is_null($this->_bufferSize)) {
- $this->_prepareColumnsAndRenderer();
- $result = $this->_renderer->build($this->recordSet, 0, true);
- if (PEAR::isError($result)) {
- return $result;
- }
- } else {
- $recordCount = $this->_dataSource->count();
- for ($row = ($this->page - 1) * $this->rowLimit, $initial = true;
- ( is_null($this->rowLimit)
- || $row < $this->page * $this->rowLimit
- )
- && $row < $recordCount;
- $row += $this->_bufferSize, $initial = false
- ) {
-
- if ($initial) {
- // prepare columns and renderer only on first iteration
- $this->_prepareColumnsAndRenderer();
- } else {
- // we don't fetch on the first iteration because a chunk
- // of data has already been fetched by bindDataSource()
- if (PEAR::isError($result = $this->fetchDataSource($row))) {
- unset($this->_dataSource);
- return $result;
- }
- }
-
- if ( ( is_null($this->rowLimit)
- || $row + $this->_bufferSize < $this->page * $this->rowLimit
- )
- && $row + $this->_bufferSize < $recordCount
- ) {
- $eof = false;
- } else {
- $eof = true;
- }
- $startRow = $row - ($this->page - 1) * $this->rowLimit;
- $result = $this->_renderer->build($this->recordSet,
- $startRow, $eof);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- }
- return true;
- } else {
- return PEAR::raiseError('Cannot build the datagrid: ' .
- 'no datasource driver loaded');
- }
- }
-
- /**
- * Prepare columns and renderer for building
- *
- * @return void
- * @access private
- */
- function _prepareColumnsAndRenderer()
- {
- $this->_createDefaultColumns();
-
- if (isset($this->_renderer)) {
- $this->_renderer->setStreaming(!is_null($this->_bufferSize));
- $this->_renderer->setColumns($this->columnSet);
- $this->_renderer->setLimit($this->page, $this->rowLimit,
- $this->getRecordCount());
- if ($this->sortSpec) {
- $this->_setRendererCurrentSorting();
- }
- }
- }
-
- /**
- * Provide some BC fix (requires PHP5)
- *
- * This is a PHP5 magic method used to simulate the old public
- * $renderer property
- * @access private
- */
- function __get($var)
- {
- if ($var == 'renderer') {
- isset($this->_renderer) or $this->setRenderer(DATAGRID_RENDER_DEFAULT);
- return $this->_renderer;
- }
- }
-
- /**
- * Set a single renderer option
- *
- * @param string $name Option name
- * @param mixed $value Option value
- * @param bool $common Whether to use this option for all
- * renderers (true) or only for the current
- * one (false)
- * @access public
- */
- function setRendererOption($name, $value, $common = false)
- {
- $this->setRendererOptions(array($name => $value), $common);
- }
-
- /**
- * Set multiple renderer options
- *
- * @param array $options An associative array of the form:
- * array("option_name" => "option_value",...)
- * @param bool $common Whether to use these options for all
- * renderers (true) or only for the current
- * one (false)
- * @access public
- */
- function setRendererOptions($options, $common = false)
- {
- if ($common) {
- $this->_rendererCommonOptions
- = array_merge($this->_rendererCommonOptions, (array)$options);
-
- // There is no need to load the default renderer if these are common
- // options. rendererFactory() will set them up.
- isset($this->_renderer) and $this->_renderer->setOptions((array)$options);
- } else {
- isset($this->_renderer) or $this->setRenderer(DATAGRID_RENDER_DEFAULT);
- $this->_renderer->setOptions((array)$options);
- }
- }
-
- /**
- * Set a single datasource option
- *
- * @param string $name Option name
- * @param mixed $value Option value
- * @access public
- */
- function setDataSourceOption($name, $value)
- {
- return $this->setDataSourceOptions(array($name => $value));
- }
-
- /**
- * Set multiple datasource options
- *
- * @param array $options An associative array of the form:
- * array("option_name" => "option_value",...)
- * @access public
- */
- function setDataSourceOptions($options)
- {
- if (isset($this->_dataSource)) {
- $this->_dataSource->setOptions((array)$options);
- } else {
- return PEAR::raiseError('Unable to set options; no datasource loaded.');
- }
- }
-
- /**
- * Enable streaming support for reading from DataSources and writing with
- * Renderers and set the buffer size (number of records)
- *
- * @param integer $bufferSize Number of records that should be buffered
- * @access public
- */
- function enableStreaming($bufferSize = 500)
- {
- $this->_bufferSize = $bufferSize;
- }
-
- /**
- * Generate columns from a fields list
- *
- * This is a shortcut for adding simple columns easily, instead of creating
- * them manually and calling addColumn() for each.
- *
- * The generated columns are appended to the current column set.
- *
- * @param array $fields Fields and labels.
- * Array of the form: array(field => label, ...)
- * The default is an empty array, which means:
- * all fields fetched from the datasource
- *
- * @return void
- * @access public
- */
- function generateColumns($fields = array())
- {
- if (empty($fields)) {
- if (!empty($this->recordSet)) {
- foreach ($this->recordSet[0] as $key => $data) {
- $fields[$key] = $key;
- }
- }
- }
-
- foreach ($fields as $field => $label) {
- $column = new Structures_DataGrid_Column($label, $field, $field);
- $this->addColumn($column);
- unset($column);
- }
- }
-
- /**
- * Enable and configure URL mapping
- *
- * If this is set, it will be parsed instead of GET/POST.
- * This is only supported on PHP5, as it depends on
- * Net_URL_Mapper.
- *
- * There are three possible placeholders, :pager, :orderBy and :direction.
- * :page or (:orderBy and :direction) can be used alone.
- *
- * It is possible to use multipe DataGrid instances on one page with
- * different prefixes.
- *
- * Instead of a format string you might also pass a Net_URL_Mapper instance
- * to this method, in which case $prefix and $scriptname will be ignored.
- * This instance must be properly set up, connected to url patterns, etc...
- * This is especially useful when you've already configured URL mapping
- * globally for your application and want Structures_DataGrid to integrate.
- *
- * @example urlFormat.php configure a url format
- *
- * @param mixed $format The URL format string or a Net_URL_Mapper instance
- * @param string $prefix Sets the url prefix
- * @param string $scriptname Set the scriptname if mod_rewrite not available
- *
- * @return void
- * @access public
- * @throws Net_URL_Mapper_InvalidException
- *
- * @see http://pear.php.net/Net_URL_Mapper
- */
- function setUrlFormat($format, $prefix = null, $scriptname = null)
- {
- if (is_string($format)) {
- if (!Structures_DataGrid::fileExists('Net/URL/Mapper.php')) {
- return PEAR::raiseError('Net_URL_Mapper Package is missing');
- }
- include_once 'Net/URL/Mapper.php';
- }
-
- // reset parsed Params and reparse the request
- $this->_mapperMatch = null;
-
-
- // only call _parseHttpRequest again if the URL matches
- if ($this->_parseRequestWithMapper($format, $prefix, $scriptname)) {
- $this->_parseHttpRequest();
-
- // copied from setRequestPrefix
- // perhabs, this part can be moved to _parseHttpRequest
- if (isset($this->_renderer)) {
- /* The page and sort request might have changed, so we need
- * to pass them again to the renderer */
- $this->_renderer->setLimit($this->page, $this->rowLimit,
- $this->getRecordCount());
- $this->_setRendererCurrentSorting();
- }
- }
- }
-
- /**
- * Tries to parse the request with
- * Net_URL_Mapper.
- *
- * @param mixed $format The URL format string or a Net_URL_Mapper instance
- * @param string $prefix Set the url prefix
- * @param string $scriptname Set the scriptname if mod_rewrite not available
- *
- * @return void
- * @access private
- * @throws Net_URL_Mapper_InvalidException
- *
- */
- function _parseRequestWithMapper($format, $prefix = null, $scriptname = null)
- {
- if (is_a($format, 'Net_URL_Mapper')) {
- $this->_urlMapper = $format;
- } else {
- // Use a special instance, so that it is usable for multipe
- // SDG instances and other NUM Instances
- $this->_urlMapper = Net_URL_Mapper::getInstance('__SDG_Instance_' . $prefix);
-
- // If the prefix is not null, set it
- if (!is_null($prefix)) {
- $this->_urlMapper->setPrefix($prefix);
- }
-
- //if the scriptname is not null, set it
- if (!is_null($scriptname)) {
- $this->_urlMapper->setScriptName($scriptname);
- }
-
- // "connect" the format wit defaults and the defined rules
- $this->_urlMapper->connect($format, $this->_mapperDefaults, $this->_mapperRules);
- }
-
- // run NUM, if it returns an array, the url was successfully matched,
- // return true
- if ($this->_mapperMatch = $this->_urlMapper->match($_SERVER['REQUEST_URI'])) {
- return true;
- }
- return false;
- }
-}
-
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-?>
+++ /dev/null
-<?php
-/**
- * Structures_DataGrid_Column Class
- *
- * PHP versions 4 and 5
- *
- * LICENSE:
- *
- * Copyright (c) 1997-2007, Andrew Nagy <asnagy@webitecture.org>,
- * Olivier Guilyardi <olivier@samalyse.com>,
- * Mark Wiesemann <wiesemann@php.net>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * The names of the authors may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * CSV file id: $Id: Column.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
- *
- * @version $Revision: 1.1.1.1 $
- * @package Structures_DataGrid
- * @category Structures
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- */
-
-/**
- * Structures_DataGrid_Column Class
- *
- * This class represents a single column for the DataGrid.
- *
- * @version $Revision: 1.1.1.1 $
- * @author Andrew S. Nagy <asnagy@webitecture.org>
- * @author Olivier Guilyardi <olivier@samalyse.com>
- * @author Mark Wiesemann <wiesemann@php.net>
- * @access public
- * @package Structures_DataGrid
- * @category Structures
- */
-class Structures_DataGrid_Column
-{
- /**
- * The unique id of the column
- * @var string
- */
- var $id;
-
- /**
- * The name (label) of the column
- * @var string
- */
- var $columnName;
-
- /**
- * The name of the field to map to
- * @var string
- */
- var $fieldName;
-
- /**
- * The field name to order by. Optional
- * @var string
- */
- var $orderBy;
-
- /**
- * The default direction to order this column by
- *
- * @var array
- * @access private
- */
- var $defaultDirection = 'ASC';
-
- /**
- * The attributes to use for the cell. Optional
- * @var array
- */
- var $attribs;
-
- /**
- * The value to be used if a cell is empty
- * @var string
- */
- var $autoFillValue;
-
- /**
- * A callback function to be called for each cell to modify the output
- * @var mixed
- * @access private
- */
- var $formatter;
-
- /**
- * User defined parameters passed to the formatter callback function
- * @var array
- * @access private
- */
- var $formatterArgs;
-
- /**
- * Constructor
- *
- * Creates default table style settings
- *
- * @param string $label The label of the column to be printed
- * @param string $field The name of the field for the column
- * to be mapped to
- * @param string $orderBy The field or expression to order the
- * data by
- * @param array $attributes The attributes for the XML or HTML
- * TD tag; form: array(name => value, ...)
- * @param string $autoFillValue The value to use for the autoFill
- * @param mixed $formatter Formatter callback. See setFormatter()
- * @param array $formatterArgs Associative array of arguments
- * passed as second argument to the
- * formatter callback
- * @see http://www.php.net/manual/en/language.pseudo-types.php
- * @see Structures_DataGrid::addColumn()
- * @see setFormatter()
- * @access public
- */
- function Structures_DataGrid_Column($label,
- $field = null,
- $orderBy = null,
- $attributes = array(),
- $autoFillValue = null,
- $formatter = null,
- $formatterArgs = array())
- {
- $this->id = uniqid('_');
- $this->columnName = $label;
- $this->fieldName = $field;
- $this->orderBy = $orderBy;
- $this->attribs = $attributes;
- $this->autoFillValue = $autoFillValue;
- if (!is_null($formatter)) {
- $this->setFormatter($formatter, $formatterArgs);
- }
- }
-
- /**
- * Get column label
- *
- * The label is the text rendered into the column header.
- *
- * @return string
- * @access public
- */
- function getLabel()
- {
- return $this->columnName;
- }
-
- /**
- * Set column label
- *
- * The label is the text rendered into the column header.
- *
- * @param string $str Column label
- * @access public
- */
- function setLabel($str)
- {
- $this->columnName = $str;
- }
-
- /**
- * Get name of the field for the column to be mapped to
- *
- * Returns the name of the field for the column to be mapped to
- *
- * @return string
- * @access public
- */
- function getField()
- {
- return $this->fieldName;
- }
-
- /**
- * Set name of the field for the column to be mapped to
- *
- * Defines the name of the field for the column to be mapped to
- *
- * @param string $str The name of the field for the column to
- * be mapped to
- * @access public
- */
- function setField($str)
- {
- $this->fieldName = $str;
- }
-
- /**
- * Get the field name to order the data by
- *
- * @return string field name
- * @access public
- */
- function getOrderBy()
- {
- return $this->orderBy;
- }
-
- /**
- * Set the field name to order the data by
- *
- * @param string $str field name
- * @access public
- */
- function setOrderBy($str)
- {
- $this->orderBy = $str;
- }
-
- /**
- * Return the default direction to order this column by
- *
- * @return string "ASC" or "DESC"
- * @access public
- */
- function getDefaultDirection($str)
- {
- return $this->defaultDirection;
- }
-
- /**
- * Set the default direction to order this column by
- *
- * @param string $str "ASC" or "DESC"
- * @access public
- */
- function setDefaultDirection($str)
- {
- $this->defaultDirection = $str;
- }
-
- /**
- * Get the column XML/HTML attributes
- *
- * Return the attributes applied to all cells in this column.
- * This only makes sense for HTML or XML rendering
- *
- * @return array Attributes; form: array(name => value, ...)
- * @access public
- */
- function getAttributes()
- {
- return $this->attribs;
- }
-
- /**
- * Set the column XML/HTML attributes
- *
- * Set the attributes to be applied to all cells in this column.
- * This only makes sense for HTML or XML rendering
- *
- * @param array $attributes form: array(name => value, ...)
- * @access public
- */
- function setAttributes($attributes)
- {
- $this->attribs = $attributes;
- }
-
- /**
- * Get auto fill value
- *
- * Returns the value to be printed if a cell in the column is null.
- *
- * @return string
- * @access public
- */
- function getAutoFillValue()
- {
- return $this->autoFillValue;
- }
-
- /**
- * Set auto fill value
- *
- * Defines a value to be printed if a cell in the column is null.
- *
- * @param string $str The value to use for the autoFill
- * @access public
- */
- function setAutoFillValue($str)
- {
- $this->autoFillValue = $str;
- }
-
- /**
- * Set Formatter Callback
- *
- * Define a formatting callback function with optional arguments for
- * this column.
- *
- * The callback function receives the following array as its first argument:
- * <code>
- * array(
- * 'record' => associative array of all fields values for this record,
- * 'fieldName' => the field name of this column,
- * 'columnName' => the label (header) of this column,
- * 'orderBy' => the field name to sort this column by,
- * 'attribs' => this column's attributes,
- * 'currRow' => zero-based row index,
- * 'currCol' => zero-based column index,
- * );
- * </code>
- *
- * If you pass the optional $arguments parameter to setFormatter(), the callback
- * function will receive it as its second argument.
- *
- * @param mixed $formatter Callback PHP pseudo-type (Array or String)
- * @param array $arguments Associative array of parameters passed to
- * as second argument to the callback function
- * @return mixed PEAR_Error on failure
- * @see http://www.php.net/manual/en/language.pseudo-types.php
- * @access public
- */
- function setFormatter($formatter, $arguments = array())
- {
- $this->formatterArgs = $arguments;
- if (is_array($formatter)) {
- $formatter[1] = $this->_parseCallbackString($formatter[1],
- $this->formatterArgs);
- } else {
- $formatter = $this->_parseCallbackString($formatter,
- $this->formatterArgs);
- }
- if (is_callable ($formatter)) {
- $this->formatter = $formatter;
- } else {
- return PEAR::raiseError('Column formatter is not a valid callback');
- }
- }
-
- /**
- * Choose a format preset
- *
- * EXPERIMENTAL: the behaviour of this method may change in future releases.
- *
- * This method allows to associate an "automatic" predefined formatter
- * to the column, for common needs as formatting dates, numbers, ...
- *
- * The currently supported predefined formatters are :
- * - dateFromTimestamp: format a UNIX timestamp according to the
- * date()-like format string passed as second argument
- * - dateFromMysql : format a MySQL DATE, DATETIME, or TIMESTAMP MySQL
- * according to the date() like format string passed as second argument
- * - number: format a number, according to the same optional 2nd, 3rd and
- * 4th arguments that the number_format() PHP function accepts.
- * - printf: format using the printf expression passed as 2nd argument.
- * - printfURL: url-encode and format using the printf expression passed
- * as 2nd argument
- *
- * @example format.php Common formats
- * @param mixed $type,... Predefined formatter name, followed by
- * formatter-specific parameters
- * @return void
- * @access public
- */
- function format($type)
- {
- $params = func_get_args();
- $this->setFormatter(array(get_class($this), '_autoFormatter'), $params);
- }
-
- /**
- * Automatic formatter(s)
- *
- * @param array $data Datagrid and record data
- * @param data $params Formatter-specific parameters
- * @access private
- * @static
- */
- function _autoFormatter($data, $params)
- {
- $value = $data['record'][$data['fieldName']];
- $type = $params[0];
-
- switch ($type) {
- case 'dateFromTimestamp':
- $format = $params[1];
- return date($format, $value);
- case 'dateFromMysql':
- $format = $params[1];
- if (preg_match('/^([0-9]+)-([0-9]+)-([0-9]+) '.
- '*([0-9]+):([0-9]+):([0-9]+)$/', $value, $r)) {
- $time = mktime($r[4], $r[5], $r[6], $r[2], $r[3], $r[1]);
- return date($format, $time);
- } elseif (preg_match('/^([0-9]+)-([0-9]+)-([0-9]+)$/', $value, $r)){
- $time = mktime(0, 0, 0, $r[2], $r[3], $r[1]);
- return date($format, $time);
- } else {
- return "Unrecognized date format";
- }
- case 'number':
- switch (count($params)) {
- case 4:
- return number_format($value, $params[1],
- $params[2], $params[3]);
- case 3:
- return "Wrong parameter count for the 'number' format";
- case 2:
- return number_format($value, $params[1]);
- default:
- return number_format($value);
- }
- case 'printfURL':
- $value = urlencode($value);
- case 'printf':
- return sprintf($params[1], $value);
- }
- }
-
- /**
- * Parse a callback function string
- *
- * This method parses a string of the type "myFunction($param1=foo,...)",
- * return the isolated function name ("myFunction") and fills $paramList
- * with the extracted parameters (array('param1' => foo, ...))
- *
- * @param string $callback Callback function string
- * @param array $paramList Reference to an array of parameters
- * @return string Function name
- * @access private
- */
- function _parseCallbackString($callback, &$paramList)
- {
- if ($size = strpos($callback, '(')) {
- $orig_callback = $callback;
- // Retrieve the name of the function to call
- $callback = substr($callback, 0, $size);
- if (strstr($callback, '->')) {
- $callback = explode('->', $callback);
- } elseif (strstr($callback, '::')) {
- $callback = explode('::', $callback);
- }
-
- // Build the list of parameters
- $length = strlen($orig_callback) - $size - 2;
- $parameters = substr($orig_callback, $size + 1, $length);
- $parameters = ($parameters === '') ? array() : split(',', $parameters);
-
- // Process the parameters
- foreach($parameters as $param) {
- if ($param != '') {
- $param = str_replace('$', '', $param);
- if (strpos($param, '=') != false) {
- $vars = split('=', $param);
- $paramList[trim($vars[0])] = trim($vars[1]);
- } else {
- $paramList[$param] = $$param;
- }
- }
- }
- }
-
- return $callback;
- }
-
- /**
- * Formatter
- *
- * This method is not meant to be called by user-space code.
- *
- * Calls a predefined function to develop custom output for the column. The
- * defined function can accept parameters so that each cell in the column
- * can be unique based on the record. The function will also automatically
- * receive the record array as a parameter. All parameters passed into the
- * function will be in one array.
- *
- * @access public
- */
- function formatter($record, $row, $col)
- {
- // Define the parameter list
- $paramList = array();
- $paramList['record'] = $record;
- $paramList['fieldName'] = $this->fieldName;
- $paramList['columnName'] = $this->columnName;
- $paramList['orderBy'] = $this->orderBy;
- $paramList['attribs'] = $this->attribs;
- $paramList['currRow'] = $row;
- $paramList['currCol'] = $col;
-
- // Call the formatter
- if (isset($GLOBALS['_STRUCTURES_DATAGRID']['column_formatter_BC'])) {
- $paramList = array_merge($this->formatterArgs, $paramList);
- $formatted = call_user_func($this->formatter, $paramList);
- } else {
- if ($this->formatterArgs) {
- $formatted = call_user_func($this->formatter, $paramList,
- $this->formatterArgs);
- } else {
- $formatted = call_user_func($this->formatter, $paramList);
- }
- }
-
- return $formatted;
- }
-
-}
-
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-?>
+++ /dev/null
-<?php
-/**
- * Base abstract class for data source drivers
- *
- * PHP versions 4 and 5
- *
- * LICENSE:
- *
- * Copyright (c) 1997-2007, Andrew Nagy <asnagy@webitecture.org>,
- * Olivier Guilyardi <olivier@samalyse.com>,
- * Mark Wiesemann <wiesemann@php.net>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * The names of the authors may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * CVS file id: $Id: DataSource.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
- *
- * @version $Revision: 1.1.1.1 $
- * @package Structures_DataGrid
- * @category Structures
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- */
-
-/**
- * Base abstract class for DataSource drivers
- *
- * SUPPORTED OPTIONS:
- *
- * - fields: (array) Which data fields to fetch from the datasource.
- * An empty array means: all fields.
- * Form: array(field1, field2, ...)
- * - primaryKey: (array) Name(s), or numerical index(es) of the
- * field(s) which contain a unique record
- * identifier (only use several fields in case
- * of a multiple-fields primary key)
- * - generate_columns: (bool) Generate Structures_DataGrid_Column objects
- * with labels. See the 'labels' option.
- * DEPRECATED:
- * use Structures_DataGrid::generateColumns() instead
- * - labels: (array) Data field to column label mapping. Only used
- * when 'generate_columns' is true.
- * Form: array(field => label, ...)
- * DEPRECATED:
- * use Structures_DataGrid::generateColumns() instead
- *
- * @author Olivier Guilyardi <olivier@samalyse.com>
- * @author Andrew Nagy <asnagy@webitecture.org>
- * @author Mark Wiesemann <wiesemann@php.net>
- * @package Structures_DataGrid
- * @category Structures
- * @version $Revision: 1.1.1.1 $
- */
-class Structures_DataGrid_DataSource
-{
- /**
- * Common and driver-specific options
- *
- * @var array
- * @access protected
- * @see Structures_DataGrid_DataSource::_setOption()
- * @see Structures_DataGrid_DataSource::addDefaultOptions()
- */
- var $_options = array();
-
- /**
- * Special driver features
- *
- * @var array
- * @access protected
- */
- var $_features = array();
-
- /**
- * Constructor
- *
- */
- function Structures_DataGrid_DataSource()
- {
- $this->_options = array('generate_columns' => false,
- 'labels' => array(),
- 'fields' => array(),
- 'primaryKey' => null,
- );
-
- $this->_features = array(
- 'multiSort' => false, // Multiple field sorting
- 'writeMode' => false, // insert, update and delete records
- );
- }
-
- /**
- * Adds some default options.
- *
- * This method is meant to be called by drivers. It allows adding some
- * default options.
- *
- * @access protected
- * @param array $options An associative array of the form:
- * array(optionName => optionValue, ...)
- * @return void
- * @see Structures_DataGrid_DataSource::_setOption
- */
- function _addDefaultOptions($options)
- {
- $this->_options = array_merge($this->_options, $options);
- }
-
- /**
- * Add special driver features
- *
- * This method is meant to be called by drivers. It allows specifying
- * the special features that are supported by the current driver.
- *
- * @access protected
- * @param array $features An associative array of the form:
- * array(feature => true|false, ...)
- * @return void
- */
- function _setFeatures($features)
- {
- $this->_features = array_merge($this->_features, $features);
- }
-
- /**
- * Set options
- *
- * @param mixed $options An associative array of the form:
- * array("option_name" => "option_value",...)
- * @access protected
- */
- function setOptions($options)
- {
- $this->_options = array_merge($this->_options, $options);
- }
-
- /**
- * Set a single option
- *
- * @param string $name Option name
- * @param mixed $value Option value
- * @access public
- */
- function setOption($name, $value)
- {
- $this->_options[$name] = $value;
- }
-
- /**
- * Generate columns if options are properly set
- *
- * Note: must be called after fetch()
- *
- * @access public
- * @return array Array of Column objects. Empty array if irrelevant.
- * @deprecated This method relates to the deprecated "generate_columns" option.
- */
- function getColumns()
- {
- $columns = array();
- if ($this->_options['generate_columns']
- and $fieldList = $this->_options['fields']) {
- include_once 'Structures/DataGrid/Column.php';
-
- foreach ($fieldList as $field) {
- $label = strtr($field, $this->_options['labels']);
- $col = new Structures_DataGrid_Column($label, $field, $field);
- $columns[] = $col;
- }
- }
-
- return $columns;
- }
-
-
- // Begin driver method prototypes DocBook template
-
- /**#@+
- *
- * This method is public, but please note that it is not intended to be
- * called by user-space code. It is meant to be called by the main
- * Structures_DataGrid class.
- *
- * It is an abstract method, part of the DataGrid Datasource driver
- * interface, and must/may be overloaded by drivers.
- */
-
- /**
- * Fetching method prototype
- *
- * When overloaded this method must return an array of records.
- * Each record can be either an associative array of field name/value
- * pairs, or an object carrying fields as properties.
- *
- * This method must return a PEAR_Error object on failure.
- *
- * @abstract
- * @param integer $offset Limit offset (starting from 0)
- * @param integer $len Limit length
- * @return object PEAR_Error with message
- * "No data source driver loaded"
- * @access public
- */
- function &fetch($offset = 0, $len = null)
- {
- return PEAR::raiseError("No data source driver loaded");
- }
-
- /**
- * Counting method prototype
- *
- * Note: must be called before fetch()
- *
- * When overloaded, this method must return the total number or records
- * or a PEAR_Error object on failure
- *
- * @abstract
- * @return object PEAR_Error with message
- * "No data source driver loaded"
- * @access public
- */
- function count()
- {
- return PEAR::raiseError("No data source driver loaded");
- }
-
- /**
- * Sorting method prototype
- *
- * When overloaded this method must return true on success or a PEAR_Error
- * object on failure.
- *
- * Note: must be called before fetch()
- *
- * @abstract
- * @param string $sortSpec If the driver supports the "multiSort"
- * feature this can be either a single field
- * (string), or a sort specification array of
- * the form: array(field => direction, ...)
- * If "multiSort" is not supported, then this
- * can only be a string.
- * @param string $sortDir Sort direction: 'ASC' or 'DESC'
- * @return object PEAR_Error with message
- * "No data source driver loaded"
- * @access public
- */
- function sort($sortSpec, $sortDir = null)
- {
- return PEAR::raiseError("No data source driver loaded");
- }
-
- /**
- * Datasource binding method prototype
- *
- * When overloaded this method must return true on success or a PEAR_Error
- * object on failure.
- *
- * @abstract
- * @param mixed $container The datasource container
- * @param array $options Binding options
- * @return object PEAR_Error with message
- * "No data source driver loaded"
- * @access public
- */
- function bind($container, $options = array())
- {
- return PEAR::raiseError("No data source driver loaded");
- }
-
- /**
- * Record insertion method prototype
- *
- * Drivers that support the "writeMode" feature must implement this method.
- *
- * When overloaded this method must return true on success or a PEAR_Error
- * object on failure.
- *
- * @abstract
- * @param array $data Associative array of the form:
- * array(field => value, ..)
- * @return object PEAR_Error with message
- * "No data source driver loaded or write mode not
- * supported by the current driver"
- * @access public
- */
- function insert($data)
- {
- return PEAR::raiseError("No data source driver loaded or write mode not".
- "supported by the current driver");
- }
-
- /**
- * Return the primary key specification
- *
- * This method always returns an array containing:
- * - either one field name or index in case of a single-field key
- * - or several field names or indexes in case of a multiple-fields key
- *
- * Drivers that support the "writeMode" feature should overload this method
- * if the key can be detected. However, the detection must not override the
- * "primaryKey" option.
- *
- * @return array Field(s) name(s) or numerical index(es)
- * @access protected
- */
- function getPrimaryKey()
- {
- return $this->_options['primaryKey'];
- }
-
- /**
- * Record updating method prototype
- *
- * Drivers that support the "writeMode" feature must implement this method.
- *
- * When overloaded this method must return true on success or a PEAR_Error
- * object on failure.
- *
- * @abstract
- * @param array $key Unique record identifier
- * @param array $data Associative array of the form:
- * array(field => value, ..)
- * @return object PEAR_Error with message
- * "No data source driver loaded or write mode
- * not supported by the current driver"
- * @access public
- */
- function update($key, $data)
- {
- return PEAR::raiseError("No data source driver loaded or write mode not".
- "supported by the current driver");
- }
-
- /**
- * Record deletion method prototype
- *
- * Drivers that support the "writeMode" feature must implement this method.
- *
- * When overloaded this method must return true on success or a PEAR_Error
- * object on failure.
- *
- * @abstract
- * @param array $key Unique record identifier
- * @return object PEAR_Error with message
- * "No data source driver loaded or write mode
- * not supported by the current driver"
- * @access public
- */
- function delete($key)
- {
- return PEAR::raiseError("No data source driver loaded or write mode not".
- "supported by the current driver");
- }
-
- /**
- * Resources cleanup method prototype
- *
- * This is where drivers should close sql connections, files, etc...
- * if needed.
- *
- * @abstract
- * @return void
- * @access public
- */
- function free()
- {
- }
-
- /**#@-*/
-
- // End DocBook template
-
- /**
- * List special driver features
- *
- * @return array Of the form: array(feature => true|false, etc...)
- * @access public
- */
- function getFeatures()
- {
- return $this->_features;
- }
-
- /**
- * Tell if the driver as a specific feature
- *
- * @param string $name Feature name
- * @return bool
- * @access public
- */
- function hasFeature($name)
- {
- return $this->_features[$name];
- }
-
- /**
- * Dump the data as returned by fetch().
- *
- * This method is meant for debugging purposes. It returns what fetch()
- * would return to its DataGrid host as a nicely formatted console-style
- * table.
- *
- * @param integer $offset Limit offset (starting from 0)
- * @param integer $len Limit length
- * @param string $sortField Field to sort by
- * @param string $sortDir Sort direction: 'ASC' or 'DESC'
- * @return string The table string, ready to be printed
- * @uses Structures_DataGrid_DataSource::fetch()
- * @access public
- */
- function dump($offset=0, $len=null, $sortField=null, $sortDir='ASC')
- {
- $records =& $this->fetch($offset, $len, $sortField, $sortDir);
- $columns = $this->getColumns();
-
- if (!$columns and !$records) {
- return "<Empty set>\n";
- }
-
- include_once 'Console/Table.php';
- $table = new Console_Table();
-
- $headers = array();
- if ($columns) {
- foreach ($columns as $col) {
- $headers[] = is_null($col->fieldName)
- ? $col->columnName
- : "{$col->columnName} ({$col->fieldName})";
- }
- } else {
- $headers = array_keys($records[0]);
- }
-
- $table->setHeaders($headers);
-
- foreach ($records as $rec) {
- $table->addRow($rec);
- }
-
- return $table->getTable();
- }
-
-}
-
-/**
- * Base abstract class for SQL query based DataSource drivers
- *
- * SUPPORTED OPTIONS:
- *
- * - db_options: (array) Options for the created database object. This option
- * is only used when the 'dsn' option is given.
- * - count_query: (string) Query that calculates the number of rows. See below
- * for more information about when such a count query
- * is needed.
- *
- * @author Olivier Guilyardi <olivier@samalyse.com>
- * @author Mark Wiesemann <wiesemann@php.net>
- * @package Structures_DataGrid
- * @category Structures
- * @version $Revision: 1.1.1.1 $
- */
-class Structures_DataGrid_DataSource_SQLQuery
- extends Structures_DataGrid_DataSource
-{
- /**
- * SQL query
- * @var string
- * @access protected
- */
- var $_query;
-
- /**
- * Fields/directions to sort the data by
- * @var array
- * @access protected
- */
- var $_sortSpec;
-
- /**
- * Instantiated database object
- * @var object
- * @access protected
- */
- var $_handle;
-
- /**
- * Total number of rows
- *
- * This property caches the result of count() to avoid running the same
- * database query multiple times.
- *
- * @var int
- * @access private
- */
- var $_rowNum = null;
-
- /**
- * Constructor
- *
- */
- function Structures_DataGrid_DataSource_SQLQuery()
- {
- parent::Structures_DataGrid_DataSource();
- $this->_addDefaultOptions(array('dbc' => null,
- 'dsn' => null,
- 'db_options' => array(),
- 'count_query' => ''));
- $this->_setFeatures(array('multiSort' => true));
- }
-
- /**
- * Bind
- *
- * @param string $query The query string
- * @param mixed $options array('dbc' => [connection object])
- * or
- * array('dsn' => [dsn string])
- * @access public
- * @return mixed True on success, PEAR_Error on failure
- */
- function bind($query, $options = array())
- {
- if ($options) {
- $this->setOptions($options);
- }
-
- if (isset($this->_options['dbc']) &&
- $this->_isConnection($this->_options['dbc'])) {
- $this->_handle = &$this->_options['dbc'];
- } elseif (isset($this->_options['dsn'])) {
- $dbOptions = array();
- if (array_key_exists('db_options', $options)) {
- $dbOptions = $options['db_options'];
- }
- $this->_handle =& $this->_connect();
- if (PEAR::isError($this->_handle)) {
- return PEAR::raiseError('Could not create connection: ' .
- $this->_handle->getMessage() . ', ' .
- $this->_handle->getUserInfo());
- }
- } else {
- return PEAR::raiseError('No Database object or dsn string specified');
- }
-
- if (is_string($query)) {
- $this->_query = $query;
- return true;
- } else {
- return PEAR::raiseError('Query parameter must be a string');
- }
- }
-
- /**
- * Fetch
- *
- * @param integer $offset Offset (starting from 0)
- * @param integer $limit Limit
- * @access public
- * @return mixed The 2D Array of the records on success,
- * PEAR_Error on failure
- */
- function &fetch($offset = 0, $limit = null)
- {
- if (!empty($this->_sortSpec)) {
- foreach ($this->_sortSpec as $field => $direction) {
- $sortArray[] = $this->_quoteIdentifier($field) . ' ' . $direction;
- }
- $sortString = join(', ', $sortArray);
- } else {
- $sortString = '';
- }
-
- $query = $this->_query;
-
- // drop LIMIT statement
- $query = preg_replace('#\sLIMIT\s.*$#isD', ' ', $query);
-
- // if we have a sort string, we need to add it to the query string
- if ($sortString != '') {
- // if there is an existing ORDER BY statement, we can just add the
- // sort string
- $result = preg_match('#ORDER\s+BY#is', $query);
- if ($result === 1) {
- $query .= ', ' . $sortString;
- } else { // otherwise we need to specify 'ORDER BY'
- $query .= ' ORDER BY ' . $sortString;
- }
- }
-
- //FIXME: What about SQL injection ?
- $recordSet = $this->_getRecords($query, $limit, $offset);
-
- if (PEAR::isError($recordSet)) {
- return $result;
- }
-
- // Determine fields to render
- if (!$this->_options['fields'] && count($recordSet)) {
- $this->setOptions(array('fields' => array_keys($recordSet[0])));
- }
-
- return $recordSet;
- }
-
- /**
- * Count
- *
- * @access public
- * @return mixed The number or records (int),
- * PEAR_Error on failure
- */
- function count()
- {
- // do we already have the cached number of records? (if yes, return it)
- if (!is_null($this->_rowNum)) {
- return $this->_rowNum;
- }
- // try to fetch the number of records
- if ($this->_options['count_query'] != '') {
- // complex queries might require special queries to get the
- // right row count
- $count = $this->_getOne($this->_options['count_query']);
- // $count has an integer value with number of rows or is a
- // PEAR_Error instance on failure
- }
- elseif (preg_match('#GROUP\s+BY#is', $this->_query) === 1 ||
- preg_match('#SELECT.+SELECT#is', $this->_query) === 1 ||
- preg_match('#\sUNION\s#is', $this->_query) === 1 ||
- preg_match('#SELECT.+DISTINCT.+FROM#is', $this->_query) === 1
- ) {
- // GROUP BY, DISTINCT, UNION and subqueries are special cases
- // ==> use the normal query and then numRows()
- $count = $this->_getRecordsNum($this->_query);
- if (PEAR::isError($count)) {
- return $count;
- }
- } else {
- // don't query the whole table, just get the number of rows
- $query = preg_replace('#SELECT\s.+\sFROM#is',
- 'SELECT COUNT(*) FROM',
- $this->_query);
- $count = $this->_getOne($query);
- // $count has an integer value with number of rows or is a
- // PEAR_Error instance on failure
- }
- // if we've got a number of records, save it to avoid running the same
- // query multiple times
- if (!PEAR::isError($count)) {
- $this->_rowNum = $count;
- }
- return $count;
- }
-
- /**
- * Disconnect from the database, if needed
- *
- * @abstract
- * @return void
- * @access public
- */
- function free()
- {
- if ($this->_handle && is_null($this->_options['dbc'])) {
- $this->_disconnect();
- unset($this->_handle);
- }
- }
-
- /**
- * This can only be called prior to the fetch method.
- *
- * @access public
- * @param mixed $sortSpec A single field (string) to sort by, or a
- * sort specification array of the form:
- * array(field => direction, ...)
- * @param string $sortDir Sort direction: 'ASC' or 'DESC'
- * This is ignored if $sortDesc is an array
- */
- function sort($sortSpec, $sortDir = 'ASC')
- {
- if (is_array($sortSpec)) {
- $this->_sortSpec = $sortSpec;
- } else {
- $this->_sortSpec[$sortSpec] = $sortDir;
- }
- }
-
-}
-
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-?>
+++ /dev/null
-<?php
-/**
- * PEAR::MDB2 SQL Query Data Source Driver
- *
- * PHP versions 4 and 5
- *
- * LICENSE:
- *
- * Copyright (c) 1997-2007, Andrew Nagy <asnagy@webitecture.org>,
- * Olivier Guilyardi <olivier@samalyse.com>,
- * Mark Wiesemann <wiesemann@php.net>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * The names of the authors may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * CSV file id: $Id: MDB2.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
- *
- * @version $Revision: 1.1.1.1 $
- * @category Structures
- * @package Structures_DataGrid_DataSource_MDB2
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- */
-
-require_once 'MDB2.php';
-require_once 'Structures/DataGrid/DataSource.php';
-
-/**
- * PEAR::MDB2 SQL Query Data Source Driver
- *
- * This class is a data source driver for the PEAR::MDB2 object
- *
- * SUPPORTED OPTIONS:
- *
- * - dbc: (object) A PEAR::MDB2 instance that will be used by this
- * driver. Either this or the 'dsn' option is required.
- * - dsn: (string) A PEAR::MDB2 dsn string. The MDB2 connection will be
- * established by this driver. Either this or the 'dbc'
- * option is required.
- *
- * GENERAL NOTES:
- *
- * You need to specify either a MDB2 instance or a MDB2 compatible dsn string as
- * an option to use this driver.
- *
- * If you use complex queries (e.g. with complex joins or with aliases),
- * $datagrid->getRecordCount() might return a wrong result. For the case of
- * GROUP BY, UNION, or DISTINCT in your queries, and for the case of subqueries,
- * this driver already has special handling. However, if you observe wrong
- * record counts, you need to specify a special query that returns only the
- * number of records (e.g. 'SELECT COUNT(*) FROM ...') as an additional option
- * 'count_query' to the bind() call.
- *
- * You can specify an ORDER BY statement in your query. Please be aware that this
- * sorting statement is then used in *every* query before the sorting options
- * that come from a renderer (e.g. by clicking on the column header when using
- * the HTML_Table renderer which is sent in the HTTP request).
- * If you want to give a default sorting statement that is only used if there is
- * no sorting query in the HTTP request, then use $datagrid->setDefaultSort().
- *
- * @version $Revision: 1.1.1.1 $
- * @author Andrew S. Nagy <asnagy@php.net>
- * @author Mark Wiesemann <wiesemann@php.net>
- * @author Olivier Guilyardi <olivier@samalyse.com>
- * @access public
- * @package Structures_DataGrid_DataSource_MDB2
- * @category Structures
- */
-class Structures_DataGrid_DataSource_MDB2
- extends Structures_DataGrid_DataSource_SQLQuery
-{
- /**
- * Bind
- *
- * @param string $query The query string
- * @param mixed $options array('dbc' => [connection object])
- * or
- * array('dsn' => [dsn string])
- * @access public
- * @return mixed True on success, PEAR_Error on failure
- */
- function bind($query, $options = array())
- {
- $result = parent::bind($query, $options);
- if (!PEAR::isError($result)) {
- $this->_handle->loadModule('Extended', null, false);
- }
- return $result;
- }
-
- /**
- * Connect to the database
- *
- * @access protected
- * @return mixed Instantiated databased object, PEAR_Error on failure
- */
- function &_connect()
- {
- return MDB2::connect($this->_options['dsn'], $this->_options['db_options']);
- }
-
- /**
- * Disconnect from the database
- *
- * @access protected
- * @return void
- */
- function _disconnect()
- {
- $this->_handle->disconnect();
- }
-
- /**
- * Whether the parameter is a MDB2 object
- *
- * @access protected
- * @param object $dbc MDB2 object
- * @return bool Whether the parameter is a MDB2 object
- */
- function _isConnection($dbc)
- {
- return MDB2::isConnection($dbc);
- }
-
- /**
- * Fetches and returns the records
- *
- * @access protected
- * @param string $query The (modified) query string
- * @param integer $offset Offset (starting from 0)
- * @param integer $limit Limit
- * @return mixed The fetched records, PEAR_Error on failure
- */
- function _getRecords($query, $limit, $offset)
- {
- if (is_null($limit)) {
- if ($offset == 0) {
- $result = $this->_handle->query($query);
- } else {
- $result = $this->_handle->extended->limitQuery($query, null,
- PHP_INT_MAX, $offset);
- }
- } else {
- $result = $this->_handle->extended->limitQuery($query, null,
- $limit, $offset);
- }
-
- if (PEAR::isError($result)) {
- return $result;
- }
-
- $recordSet = array();
-
- // Fetch the data
- if ($result->numRows()) {
- while ($record = $result->fetchRow(MDB2_FETCHMODE_ASSOC)) {
- $recordSet[] = $record;
- }
- }
-
- $result->free();
-
- return $recordSet;
- }
-
- /**
- * Returns a quoted identifier
- *
- * @access protected
- * @return string The quoted identifier
- */
- function _quoteIdentifier($field)
- {
- return $this->_handle->quoteIdentifier($field);
- }
-
- /**
- * Fetches and returns a single value
- *
- * @access protected
- * @param string $query The query string
- * @return mixed The fetched value, PEAR_Error on failure
- */
- function _getOne($query)
- {
- return $this->_handle->extended->getOne($query);
- }
-
- /**
- * Calculates (and returns) the number of records by getting all records
- *
- * @access protected
- * @param string $query The query string
- * @return mixed The numbers row records, PEAR_Error on failure
- */
- function _getRecordsNum($query)
- {
- $result = $this->_handle->query($query);
- if (PEAR::isError($result)) {
- return $result;
- }
- return $result->numRows();
- }
-
-}
-
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-?>
+++ /dev/null
-<?php
-/**
- * Base class of all Renderer drivers
- *
- * PHP versions 4 and 5
- *
- * LICENSE:
- *
- * Copyright (c) 1997-2007, Andrew Nagy <asnagy@webitecture.org>,
- * Olivier Guilyardi <olivier@samalyse.com>,
- * Mark Wiesemann <wiesemann@php.net>
- * Sascha Grossenbacher <saschagros@bluewin.ch>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * The names of the authors may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * CSV file id: $Id: Renderer.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
- *
- * @version $Revision: 1.1.1.1 $
- * @package Structures_DataGrid
- * @category Structures
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- */
-
-/**
- * Base class of all Renderer drivers
- *
- * SUPPORTED OPTIONS:
- *
- * - buildHeader: (bool) Whether to build the header.
- * - buildFooter: (bool) Whether to build the footer.
- * - fillWithEmptyRows: (bool) Ensures that all pages have the same number of
- * rows.
- * - numberAlign: (bool) Whether to right-align numeric values.
- * - defaultCellValue: (string) What value to put by default into empty cells.
- * - defaultColumnValues: (array) Per-column default cell value. This is an array
- * of the form: array(fieldName => value, ...).
- * - hideColumnLinks: (array) By default sorting links are enabled on all
- * columns. With this option it is possible to
- * disable sorting links on specific columns. This
- * is an array of the form: array(fieldName, ...).
- * This option only affects drivers that support
- * sorting.
- * - encoding: (string) The content encoding. If the mbstring extension
- * is present the default value is set from
- * mb_internal_encoding(), otherwise it is ISO-8859-1.
- * - extraVars: (array) Variables to be added to the generated HTTP
- * queries.
- * - excludeVars: (array) Variables to be removed from the generated
- * HTTP queries.
- * - columnAttributes: (array) Column cells attributes. This is an array of
- * the form:
- * array(fieldName => array(attribute => value, ...) ...)
- * This option is only used by XML/HTML based
- * drivers.
- * - onMove: (string) Name of a Javascript function to call on
- * onClick/onSubmit events when the user is either paging
- * or sorting the data. This function
- * receives a single object argument of the
- * form: { page: <page>, sort: [{field: <field>,
- * direction: <direction>}, ...],
- * data: <user_data> }. Remark: setting this
- * option doesn't remove the href attribute,
- * you should return false from your handler
- * function to void it (eg: for AJAX, etc..).
- * - onMoveData: (string) User data passed in the "data" member of the
- * object argument passed to onMove. No JSON
- * serialization is performed, this is assigned
- * as a raw string to the "data" attribute.
- * It's up to you to add quotes, slashes, etc...
- *
- * --- DRIVER INTERFACE ---
- *
- * Methods (none required):
- * - Constructor
- * - setContainer()
- * - getContainer()
- * - init()
- * - defaultCellFormatter()
- * - buildHeader()
- * - buildBody()
- * - buildRow()
- * - buildEmptyRow()
- * - buildFooter()
- * - finalize()
- * - flatten()
- * - render()
- * - getPaging() (deprecated)
- *
- * Properties (all read-only):
- * - $_columns
- * - $_columnsNum
- * - $_currentSort
- * - $_firstRecord
- * - $_lastRecord
- * - $_multiSort
- * - $_options
- * - $_page
- * - $_pageLimit
- * - $_pagesNum
- * - $_records
- * - $_recordsNum
- * - $_requestPrefix
- * - $_sortableFields
- * - $_totalRecordsNum
- *
- * Options that drivers may handle:
- * - encoding
- * - fillWithEmptyRows
- * - numberAlign
- * - extraVars
- * - excludeVars
- *
- * @version $Revision: 1.1.1.1 $
- * @author Olivier Guilyardi <olivier@samalyse.com>
- * @author Mark Wiesemann <wiesemann@php.net>
- * @author Sascha Grossenbacher <saschagros@bluewin.ch>
- * @access public
- * @package Structures_DataGrid
- * @category Structures
- * @abstract
- */
-class Structures_DataGrid_Renderer
-{
- /**
- * Columns' fields names and labels
- *
- * Drivers can read the content of this property but must not change it.
- *
- * @var array Structure:
- * array(<columnIndex> => array(field => <fieldName>,
- * label=> <label>), ...)
- * Where <columnIndex> is zero-based
- * @access protected
- */
- var $_columns = array();
-
- /**
- * Records content
- *
- * Drivers can read the content of this property but must not change it.
- *
- * @var array Structure:
- * array(
- * <rowIndex> => array(
- * <columnIndex> => array(<cellValue>, ...),
- * ...),
- * ...)
- * Where <rowIndex> and <columnIndex> are zero-based
- * @access protected
- */
- var $_records = array();
-
- /**
- * Fields/directions the data is currently sorted by
- *
- * Drivers can read the content of this property but must not change it.
- *
- * @var array Structure: array(fieldName => direction, ....)
- * @access protected
- */
- var $_currentSort = array();
-
- /**
- * Whether the backend support sorting by multiple fields
- *
- * Drivers can read the content of this property but must not change it.
- *
- * @var bool
- * @access protected
- */
- var $_multiSort = false;
-
- /**
- * Number of columns
- *
- * Drivers can read the content of this property but must not change it.
- *
- * @var int
- * @access protected
- */
- var $_columnsNum;
-
- /**
- * Number of records in the current page
- *
- * Drivers can read the content of this property but must not change it.
- *
- * @var int
- * @access protected
- */
- var $_recordsNum = 0;
-
- /**
- * Total number of records as reported by the datasource
- *
- * Drivers can read the content of this property but must not change it.
- *
- * @var int
- * @access protected
- */
- var $_totalRecordsNum;
-
- /**
- * First record number (starting from 1), in the current page
- *
- * Drivers can read the content of this property but must not change it.
- *
- * @var int
- * @access protected
- */
- var $_firstRecord;
-
- /**
- * Last record number (starting from 1), in the current page
- *
- * Drivers can read the content of this property but must not change it.
- *
- * @var int
- * @access protected
- */
- var $_lastRecord;
-
- /**
- * Current page
- *
- * Page number starting from 1.
- *
- * Drivers can read the content of this property but must not change it.
- *
- * @var int
- * @access protected
- */
- var $_page = 1;
-
- /**
- * Number of records per page
- *
- * Drivers can read the content of this property but must not change it.
- *
- * @var int
- * @access protected
- */
- var $_pageLimit = null;
-
- /**
- * Number of pages
- *
- * Drivers can read the content of this property but must not change it.
- *
- * @var int
- * @access protected
- */
- var $_pagesNum;
-
- /**
- * GET/POST/Cookie parameters prefix
- *
- * Drivers can read the content of this property but must not change it.
- *
- * @var string
- * @access protected
- */
- var $_requestPrefix = '';
-
- /**
- * Which fields the datagrid may be sorted by
- *
- * Drivers can read the content of this property but must not change it.
- *
- * @var array Field names
- * @access protected
- */
- var $_sortableFields = array();
-
- /**
- * The default directions to sort by
- *
- * Drivers can read the content of this property but must not change it.
- *
- * @var array Structure: array(field => ASC|DESC, ...)
- * @access protected
- */
- var $_defaultDirections = array();
-
- /**
- * Common and driver-specific options
- *
- * Drivers can read the content of this property but must not change it.
- *
- * @var array
- * @access protected
- * @see Structures_DataGrid_Renderer::setOption()
- * @see Structures_DataGrid_Renderer::_addDefaultOptions()
- */
- var $_options = array();
-
- /**
- * Special driver features
- *
- * @var array
- * @access protected
- */
- var $_features = array();
-
- /**
- * Columns objects
- *
- * Beware: this is a private property, it is not meant to be accessed
- * by drivers. Use the $_columns property instead
- *
- * @var array
- * @access private
- * @see Structures_DataGrid_Renderer::_columns
- */
- var $_columnObjects = array();
-
- /**
- * Whether the datagrid has been built or not
- * @var bool
- * @access private
- * @see Structures_DataGrid_Renderer::isBuilt()
- */
- var $_isBuilt = false;
-
- /**
- * Cache for the GET parameters that are common to all sorting http queries
- *
- * @var array
- * @access private
- * @see Structures_DataGrid_Renderer::_buildSortingHttpQuery()
- */
- var $_sortingHttpQueryCommon = null;
-
- /**
- * Whether streaming is enabled or not
- *
- * @var bool
- * @access private
- */
- var $_streamingEnabled = false;
-
- /**
- * URL mapper instance, if provided
- *
- * @var object Net_URL_Mapper
- * @access protected
- */
- var $_urlMapper = null;
-
- /**
- * Instantiate the driver and set default options and features
- *
- * Drivers may overload this method in order to change/add default options.
- *
- * @access public
- * @see Structures_DataGrid_Renderer::_addDefaultOptions()
- */
- function Structures_DataGrid_Renderer()
- {
- $this->_options = array(
-
- /* Options that the drivers may/should handle */
- 'encoding' => 'ISO-8859-1',
- 'fillWithEmptyRows' => false,
- 'numberAlign' => true,
- 'extraVars' => array(),
- 'excludeVars' => array(),
- 'columnAttributes' => array(),
-
- /* Options that must not be accessed by drivers */
- 'buildHeader' => true,
- 'buildFooter' => true,
- 'defaultCellValue' => null,
- 'defaultColumnValues' => array(),
- 'hideColumnLinks' => array(),
- 'onMove' => null,
- 'onMoveData' => '',
- );
-
- $this->_features = array(
- 'streaming' => false,
- 'outputBuffering' => false,
- 'objectPreserving' => false,
- );
-
- if (function_exists('mb_internal_encoding')) {
- $encoding = mb_internal_encoding();
- if ($encoding != 'pass') {
- $this->_options['encoding'] = $encoding;
- }
- }
-
- }
-
- /**
- * Adds some default options.
- *
- * This method is meant to be called by drivers. It allows adding some
- * default options.
- *
- * @access protected
- * @param array $options An associative array of the from:
- * array(optionName => optionValue, ...)
- * @return void
- * @see Structures_DataGrid_Renderer::setOption()
- */
- function _addDefaultOptions($options)
- {
- $this->_options = array_merge($this->_options, $options);
- }
-
- /**
- * Add special driver features
- *
- * This method is meant to be called by drivers. It allows specifying
- * the special features that are supported by the current driver.
- *
- * @access protected
- * @param array $features An associative array of the form:
- * array(feature => true|false, ...)
- * @return void
- */
- function _setFeatures($features)
- {
- $this->_features = array_merge($this->_features, $features);
- }
-
- /**
- * Set multiple options
- *
- * @param mixed $options An associative array of the form:
- * array("option_name" => "option_value",...)
- * @access public
- */
- function setOptions($options)
- {
- $this->_options = array_merge($this->_options, $options);
- }
-
- /**
- * Set a single option
- *
- * @param string $name Option name
- * @param mixed $value Option value
- * @access public
- */
- function setOption($name, $value)
- {
- $this->_options[$name] = $value;
- }
-
- /**
- * Provide columns
- *
- * This method is supposed to be called ONLY by the code that loads the
- * driver. In most cases, that'll be the Structures_DataGrid class.
- *
- * @param array $columns Array of Structures_DataGrid_Column objects
- * @access public
- */
- function setColumns(&$columns)
- {
- $this->_columnObjects = &$columns;
- }
-
- /**
- * Specify how the datagrid is currently sorted
- *
- *
- * This method is supposed to be called ONLY by the code that loads the
- * driver. In most cases, that'll be the Structures_DataGrid class.
- *
- * The multiSort capabilities is related to the multiSort DataSource
- * feature. In short : the DataGrid checks if the DataSource supports
- * multiSort and informs the Renderer about it.
- *
- * @param array $currentSort Structure:
- * array(fieldName => direction, ....)
- * @param bool $multiSortCapable Whether the backend support sorting by
- * multiple fields
- * @access public
- */
- function setCurrentSorting($currentSort, $multiSortCapable = false)
- {
- $this->_currentSort = $currentSort;
- $this->_multiSort = $multiSortCapable;
- }
-
- /**
- * Specify page and row limits
- *
- * This method is supposed to be called ONLY by the code that loads the
- * driver. In most cases, that'll be the Structures_DataGrid class.
- *
- * @param int $currentPage Current page number
- * @param int $rowsPerPage Maximum number of rows per page
- * @param int $totalRowNum Total number of data rows
- * @access public
- */
- function setLimit($currentPage, $rowsPerPage, $totalRowNum) {
- $this->_page = $currentPage;
- $this->_pageLimit = $rowsPerPage;
- $this->_totalRecordsNum = $totalRowNum;
- $this->_pagesNum = (is_null($rowsPerPage) or $totalRowNum == 0) ?
- 1 : ceil($totalRowNum / $rowsPerPage);
- $this->_firstRecord = ($currentPage - 1) * $rowsPerPage + 1;
- $this->_lastRecord = (is_null($rowsPerPage))
- ? $totalRowNum
- : min($this->_firstRecord + $rowsPerPage - 1,
- $totalRowNum);
- if ($this->_lastRecord > $totalRowNum) {
- $this->_lastRecord = $totalRowNum;
- }
- }
-
- /**
- * Tell the renderer whether streaming is enabled or not
- *
- * This method is supposed to be called ONLY by the code that loads the
- * driver. In most cases, that'll be the Structures_DataGrid class.
- *
- * @param int $status Whether streaming is enabled or not
- * @access public
- */
- function setStreaming($status) {
- $this->_streamingEnabled = (boolean)$status;
- }
-
- /**
- * Attach a container object
- *
- * Drivers that provide support for the Structures_DataGrid::fill() method
- * must implement this method.
- *
- * @abstract
- * @param object Container of the class supported by the driver
- * @access public
- * @return mixed True or PEAR_Error
- */
- function setContainer(&$container)
- {
- return $this->_noSupport(__FUNCTION__);
- }
-
- /**
- * Return the container used by the driver
- *
- * Drivers should implement this method when they have some kind of support
- * for rendering containers.
- *
- * @abstract
- * @return object Container of the class supported by the driver
- * or PEAR_Error
- * @access public
- */
- function &getContainer()
- {
- return $this->_noSupport(__FUNCTION__);
- }
-
- /**
- * Create or/and prepare the container
- *
- * Drivers may optionally implement this method for any pre-build()
- * operations.
- *
- * For the container support, it is responsible for creating the
- * container if it has not already been provided by the user with
- * the setContainer() method. It is where preliminary container
- * setup should also be done.
- *
- * @abstract
- * @access protected
- */
- function init()
- {
- }
-
- /**
- * Build the header
- *
- * Drivers may optionally implement this method.
- *
- * @abstract
- *
- * @param array $columns Columns' fields names and labels (This is a
- * convenient reference to the $_columns protected
- * property)
- * @access protected
- * @return void or PEAR_Error
- */
- function buildHeader(&$columns)
- {
- }
-
- /**
- * Stream a chunk of records
- *
- * @param array $records 2D array of records
- * @param integer $startRow Starting row number
- * @param boolean $eof Whether the current chunk is the last chunk
- * @access protected
- * @return void or PEAR_Error
- */
- function streamBody($records, $startRow, $eof = false)
- {
- $rowNum = count($records);
- for ($row = 0; $row < $rowNum; $row++) {
- $result = $this->buildRow($row + $startRow, $records[$row]);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
-
- if ($eof && $this->_options['fillWithEmptyRows'] && !is_null($this->_pageLimit)) {
- for ($row = $this->_recordsNum; $row < $this->_pageLimit; $row++) {
- $result = $this->buildEmptyRow($row);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- }
- }
-
- /**
- * Build the body
- *
- * Drivers may overload() this method, if buildRow() and buildEmptyRow()
- * are not flexible enough.
- *
- * @access protected
- * @return void or PEAR_Error
- */
- function buildBody()
- {
- for ($row = 0; $row < $this->_recordsNum; $row++) {
- $result = $this->buildRow($row, $this->_records[$row]);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
-
- if ($this->_options['fillWithEmptyRows'] && !is_null($this->_pageLimit)) {
- for ($row = $this->_recordsNum; $row < $this->_pageLimit; $row++) {
- $result = $this->buildEmptyRow($row);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- }
- }
-
- /**
- * Build a body row
- *
- * This is a very simple method for drivers to build a row.
- * For more flexibility, drivers should overload buildBody()
- *
- * @param int $index Row index (zero-based)
- * @param array $data Record data.
- * Structure: array(0 => <value0>, 1 => <value1>, ...)
- * @return void or PEAR_Error
- * @access protected
- * @abstract
- */
- function buildRow($index, $data)
- {
- }
-
- /**
- * Build an empty row
- *
- * Drivers must overload this method if they need to do something with
- * empty rows that remain at the end of the body.
- *
- * This method will only be called if the "fillWithEmptyRows" option is
- * enabled.
- *
- * @param int $index Row index (zero-based)
- * @return void or PEAR_Error
- * @access protected
- * @abstract
- */
- function buildEmptyRow($index)
- {
- }
-
- /**
- * Build the footer
- *
- * Drivers may optionally implement this method.
- *
- * @abstract
- * @access protected
- * @return void or PEAR_Error
- */
- function buildFooter()
- {
- }
-
- /**
- * Finish building the datagrid.
- *
- * Drivers may optionally implement this method for any post-build()
- * operations.
- *
- * @abstract
- * @access protected
- * @return void or PEAR_Error
- */
- function finalize()
- {
- }
-
- /**
- * Retrieve output from the container object
- *
- * Drivers may optionally implement this method.
- *
- * This method is meant to retrieve final output from the container.
- *
- * Usually the container is an object (ex: HTMLTable instance),
- * and the final output a string.
- *
- * The driver knows how to retrieve such final output from a given
- * container (ex: HTMLTable::toHTML()), and this is where to do it.
- *
- * Sometimes the container may not be an object, but the final output
- * itself. In this case, this method should simply return the container.
- *
- * This method mustn't output anything directly to the standard output.
- *
- * @abstract
- * @return mixed Output
- * @access protected
- */
- function flatten()
- {
- return $this->_noSupport(__FUNCTION__);
- }
-
- /**
- * Default formatter for all cells
- *
- * Drivers may optionally implement this method.
- *
- * @abstract
- * @param string Cell value
- * @return string Formatted cell value
- * @access protected
- */
- function defaultCellFormatter($value)
- {
- return $value;
- }
-
- /**
- * Build the grid
- *
- * Drivers must not overload this method. Pre and post-build operations
- * can be performed in init() and finalize()
- *
- * @param array $chunk 2D array of records
- * @param integer $startRow Starting row number of current chunk
- * @param boolean $eof Whether the current chunk is the last chunk
- * @access public
- * @return void
- */
- function build($chunk, $startRow, $eof = false)
- {
- // on first call of build(): initialize the columns and prepare the header
- if (empty($this->_columns)) {
- $this->_columns = array();
- foreach ($this->_columnObjects as $index => $column) {
- if (!is_null($column->orderBy)) {
- $field = $column->orderBy;
- if (!in_array($field,$this->_sortableFields) and
- !in_array($field, $this->_options['hideColumnLinks'])
- ) {
- $this->_sortableFields[] = $field;
- }
- } else if (!is_null($column->fieldName)) {
- $field = $column->fieldName;
- } else {
- $field = $column->columnName;
- }
-
- $label = $column->columnName;
-
- if (isset($this->_options['defaultColumnValues'][$field])) {
- $column->setAutoFillValue($this->_options['defaultColumnValues'][$field]);
- } else if (!is_null($this->_options['defaultCellValue'])) {
- $column->setAutoFillValue($this->_options['defaultCellValue']);
- }
-
- if (is_array($column->attribs)) {
- if (!array_key_exists($field, $this->_options['columnAttributes'])) {
- $this->_options['columnAttributes'][$field] = array();
- }
- $this->_options['columnAttributes'][$field] =
- array_merge($this->_options['columnAttributes'][$field],
- $column->attribs);
- }
-
- $this->_defaultDirections[$field] = $column->defaultDirection;
-
- $this->_columns[$index] = compact('field','label');
- }
-
- $this->_columnsNum = count($this->_columns);
-
- $result = $this->init();
- if (PEAR::isError($result)) {
- return $result;
- }
-
- if ($this->_options['buildHeader']) {
- $result = $this->buildHeader($this->_columns);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- }
-
- $chunkSize = count($chunk);
- $this->_recordsNum += $chunkSize;
-
- $row = 0;
- for ($rec = 0; $rec < $chunkSize; $rec++) {
- // Currently, no formatting is performed on object records.
- // These are not converted to indexed arrays, so that some
- // renderer drivers might fail to process them.
- if (is_array($chunk[$rec]) or !$this->hasFeature('objectPreserving')) {
- $content = array();
- $col = 0;
- foreach ($this->_columnObjects as $column) {
- $content[] = $this->recordToCell($column, $chunk[$rec],
- $row + $startRow, $col);
- $col++;
- }
- $chunk[$rec] = $content;
- }
- $row++;
- }
-
- if (!$this->hasFeature('streaming')) {
- $this->_records = array_merge($this->_records, $chunk);
- } else {
- $result = $this->streamBody($chunk, $startRow, $eof);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
-
- // if this is the last chunk, do some final operations
- if ($eof) {
- if (is_null($this->_pageLimit)) {
- $result = $this->_pageLimit = $this->_recordsNum;
- if (PEAR::isError($result)) {
- return $result;
- }
- }
-
- if (!$this->hasFeature('streaming')) {
- $result = $this->buildBody();
- if (PEAR::isError($result)) {
- return $result;
- }
- }
-
- if ($this->_options['buildFooter']) {
- $result = $this->buildFooter();
- if (PEAR::isError($result)) {
- return $result;
- }
- }
-
- $result = $this->finalize();
- if (PEAR::isError($result)) {
- return $result;
- }
-
- $this->_isBuilt = true;
- }
- }
-
- /**
- * Returns the output from the renderer (e.g. HTML table, XLS object, ...)
- *
- * Drivers must not overload this method. Output generation has to be
- * implemented in flatten().
- *
- * @access public
- * @return mixed The output from the renderer
- */
- function getOutput()
- {
- if ($this->_streamingEnabled) {
- return PEAR::raiseError('getOutput() cannot be used together with ' .
- 'streaming.');
- }
-
- if ($this->hasFeature('outputBuffering')) {
- return $this->flatten();
- } else {
- return $this->_noSupport(__FUNCTION__);
- }
- }
-
- /**
- * Render to the standard output
- *
- * This method may be overloaded by renderer drivers in order to prepare
- * writing to the standard output (like calling header(), etc...).
- *
- * @access public
- * @return void or object PEAR_Error
- */
- function render()
- {
- if ($this->hasFeature('outputBuffering')) {
- echo $this->flatten();
- } else {
- $result = $this->build(array(), 0);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- }
-
- /**
- * Return an error related to an unsupported public method
- *
- * When a given public method is not implemented/supported by the driver
- * it must return a PEAR_Error object with code DATAGRID_ERROR_UNSUPPORTED.
- * This is a helper method for generating such PEAR_Error objects.
- *
- * Example:
- *
- * <code>
- * function anUnsupportedMethod()
- * {
- * return $this->_noSupport(__FUNCTION__);
- * }
- * </code>
- *
- * @param string $method The name of the unsupported method
- * @return object PEAR_Error with code DATAGRID_ERROR_UNSUPPORTED
- * @access protected
- */
- function _noSupport($method)
- {
- return PEAR::raiseError("The renderer driver class \"" .get_class($this).
- "\" does not support the $method() method",
- DATAGRID_ERROR_UNSUPPORTED);
- }
-
- /**
- * Sets the rendered status. This can be used to "flush the cache" in case
- * you need to render the datagrid twice with the second time having changes
- *
- * This is quite an obsolete method...
- *
- * @access public
- * @param bool $status The rendered status of the DataGrid
- */
- function setRendered($status = false)
- {
- if (!$status) {
- $this->_isBuilt = false;
- }
- /* What are we supposed to do with $status = true ? */
- }
-
- /**
- * Set the HTTP Request prefix
- *
- * @param string $prefix The prefix string
- * @return void
- * @access public
- */
- function setRequestPrefix($prefix)
- {
- $this->_requestPrefix = $prefix;
- }
-
- /**
- * Perform record/column to cell intersection and formatting
- *
- * @param object $column The column object
- * @param array $record Array of record values
- * @param int $row The row number of the cell
- * @param int $col The column number of the cell
- * @return string Formatted cell value
- * @access private
- */
- function recordToCell(&$column, $record, $row = null, $col = null)
- {
- $value = '';
- if (isset($column->formatter) and !empty($column->formatter)) {
- $value = $column->formatter($record, $row, $col);
- } else if (isset($column->fieldName)) {
- $record = (array) $record; // record might be an object
- if (isset($record[$column->fieldName])) {
- $value = $this->defaultCellFormatter($record[$column->fieldName]);
- }
- }
-
- if (empty($value) and !is_null($column->autoFillValue)) {
- $value = $column->autoFillValue;
- }
-
- return $value;
- }
-
- /**
- * Query the grid build status
- *
- * @return bool Whether the grid has already been built or not
- * @access public
- */
- function isBuilt()
- {
- return $this->_isBuilt;
- }
-
- /**
- * Build an HTTP query for sorting a given column
- *
- * This is a handy method that most drivers can use in order to build
- * the HTTP queries that are used to sort columns.
- *
- * It takes the global "extraVars", "excludeVars" options as well as the
- * $_requestPrefix property into account and can also convert the ampersand
- * to XML/HTML entities according to the "encoding" option.
- *
- * @param string $field Sort field name
- * @param string $direction Sort direction
- * @param bool $convertAmpersand Whether to convert ampersands to
- * XML/HTML compliant entities
- * @param array $extraParameters Optional extra HTTP parameters
- * @return string Query string of the
- * @access protected
- *
- */
- function _buildSortingHttpQuery($field, $direction, $convertAmpersand = false,
- $extraParameters = array())
- {
- $prefix = $this->_requestPrefix;
-
- if (is_null($this->_sortingHttpQueryCommon)) {
- // Build and cache the list of common get parameters
- $this->_sortingHttpQueryCommon = $this->_options['extraVars'];
- $ignore = $this->_options['excludeVars'];
- $ignore[] = $prefix . 'orderBy';
- $ignore[] = $prefix . 'direction';
- foreach ($extraParameters as $var => $value) {
- $ignore[] = $prefix . $var;
- }
- foreach ($_GET as $key => $val) {
- if (!in_array($key, $ignore)) {
- $this->_sortingHttpQueryCommon[$key] = $val;
- }
- }
- }
-
- // Build list of GET variables
- $get = array();
- $get[$prefix . 'orderBy'] = $field;
- $get[$prefix . 'direction'] = $direction;
- foreach ($extraParameters as $var => $value) {
- $get[$prefix . $var] = $value;
- }
-
- // Merge common and column-specific GET variables
- $get = array_merge($this->_sortingHttpQueryCommon, $get);
-
- // Build query
- if ($convertAmpersand and ini_get('arg_separator.output') == '&') {
- $query = htmlentities(http_build_query($get),ENT_QUOTES,
- $this->_options['encoding']);
- } else {
- $query = http_build_query($get);
- }
-
- return $query;
- }
-
- /**
- * Builds a HTTP URL for sorting and paging.
- *
- * It uses NUM and optionally adds a query string with extraVars/GET
- *
- * @param string $field Sort field name
- * @param string $direction Sort direction
- * @param int $page Pager index
- *
- * @return string generated HTTP URL
- */
- function _buildMapperURL($field, $direction, $page = 1)
- {
- if (!empty($direction)) {
- $direction = strtolower($direction);
- }
-
- $params = array('page' => $page,
- 'orderBy' => $field,
- 'direction' => $direction);
-
- if (is_null($this->_sortingHttpQueryCommon)) {
- // Build and cache the list of common get parameters
- $prefix = $this->_requestPrefix;
- $this->_sortingHttpQueryCommon = $this->_options['extraVars'];
- $ignore = $this->_options['excludeVars'];
- $ignore[] = $prefix . 'orderBy';
- $ignore[] = $prefix . 'direction';
- foreach ($_GET as $key => $val) {
- if (!in_array($key, $ignore)) {
- $this->_sortingHttpQueryCommon[$key] = $val;
- }
- }
- }
-
- return $this->_urlMapper->generate($params, $this->_sortingHttpQueryCommon);
- }
-
- /**
- * Build a Javascript handler call for a given page and sorting spec
- *
- * @param string $page Page number (can also be "%d" for replacement
- * by Pager, etc...)
- * @param mixed $sortSpec Array of fields and directions, or raw
- * javascript string
- * @return string JS function string, semi-colon included
- * @access protected
- */
- function _buildOnMoveCall($page, $sortSpec)
- {
- $handler = '';
- if ($this->_options['onMove']) {
- if (is_array($sortSpec)) {
- $sort = array();
- foreach ($sortSpec as $field => $direction) {
- $sort[] = "{field: '" . addslashes($field) . "', " .
- "direction:'$direction'}";
- }
- $sort = "[" . join(',', $sort) . "]";
- } else {
- $sort = $sortSpec;
- }
- $data = $this->_options['onMoveData'] or $data = "''";
- $handler = $this->_options['onMove'] .
- "({ page: $page, sort: $sort, data: $data });";
- }
- return $handler;
- }
-
- /**
- * List special driver features
- *
- * @return array Of the form: array(feature => true|false, etc...)
- * @access public
- */
- function getFeatures()
- {
- return $this->_features;
- }
-
- /**
- * Tell if the driver as a specific feature
- *
- * @param string $name Feature name
- * @return bool
- * @access public
- */
- function hasFeature($name)
- {
- return $this->_features[$name];
- }
-
- /**
- * Set the URL mapper
- *
- * @param object $instance Net_URL_Mapper instance
- * @return void
- * @access public
- */
- function setUrlMapper($instance)
- {
- $this->_urlMapper = $instance;
- }
-
- /**
- * Return the URL mapper
- *
- * @return object Net_URL_Mapper instance or null
- * @access public
- */
- function getUrlMapper()
- {
- return $this->_urlMapper;
- }
-
-}
-
-// This function is here because we can't depend on PHP_Compat
-if (!function_exists('http_build_query')) {
- function http_build_query($formdata, $numeric_prefix = null)
- {
- // If $formdata is an object, convert it to an array
- if (is_object($formdata)) {
- $formdata = get_object_vars($formdata);
- }
-
- // Check we have an array to work with
- if (!is_array($formdata)) {
- user_error('http_build_query() Parameter 1 expected to be Array or Object. Incorrect value given.',
- E_USER_WARNING);
- return false;
- }
-
- // If the array is empty, return null
- if (empty($formdata)) {
- return;
- }
-
- // Argument seperator
- $separator = ini_get('arg_separator.output');
- if (strlen($separator) == 0) {
- $separator = '&';
- }
-
- // Start building the query
- $tmp = array ();
- foreach ($formdata as $key => $val) {
- if (is_null($val)) {
- continue;
- }
-
- if (is_integer($key) && $numeric_prefix != null) {
- $key = $numeric_prefix . $key;
- }
-
- if (is_scalar($val)) {
- array_push($tmp, urlencode($key) . '=' . urlencode($val));
- continue;
- }
-
- // If the value is an array, recursively parse it
- if (is_array($val) || is_object($val)) {
- array_push($tmp, http_build_query_helper($val, urlencode($key)));
- continue;
- }
-
- // The value is a resource
- return null;
- }
-
- return implode($separator, $tmp);
- }
-
- // Helper function
- function http_build_query_helper($array, $name)
- {
- $tmp = array ();
- foreach ($array as $key => $value) {
- if (is_array($value)) {
- array_push($tmp, http_build_query_helper($value, sprintf('%s[%s]', $name, $key)));
- } elseif (is_scalar($value)) {
- array_push($tmp, sprintf('%s[%s]=%s', $name, urlencode($key), urlencode($value)));
- } elseif (is_object($value)) {
- array_push($tmp, http_build_query_helper(get_object_vars($value), sprintf('%s[%s]', $name, $key)));
- }
- }
-
- // Argument seperator
- $separator = ini_get('arg_separator.output');
- if (strlen($separator) == 0) {
- $separator = '&';
- }
-
- return implode($separator, $tmp);
- }
-}
-
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-?>
+++ /dev/null
-<?php
-/**
- * HTML Table Rendering Driver
- *
- * PHP versions 4 and 5
- *
- * LICENSE:
- *
- * Copyright (c) 1997-2007, Andrew Nagy <asnagy@webitecture.org>,
- * Olivier Guilyardi <olivier@samalyse.com>,
- * Mark Wiesemann <wiesemann@php.net>
- * Sascha Grossenbacher <saschagros@bluewin.ch>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * The names of the authors may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * CSV file id: $Id: HTMLTable.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
- *
- * @version $Revision: 1.1.1.1 $
- * @package Structures_DataGrid_Renderer_HTMLTable
- * @category Structures
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- */
-
-require_once 'Structures/DataGrid/Renderer.php';
-require_once 'HTML/Table.php';
-
-/**
- * HTML Table Rendering Driver
- *
- * Driver for rendering the DataGrid as an HTMLTable
- *
- * SUPPORTED OPTIONS:
- *
- * - evenRowAttributes: (array) An associative array containing each attribute
- * of the even rows.
- * - oddRowAttributes: (array) An associative array containing each attribute
- * of the odd rows.
- * - emptyRowAttributes: (array) An associative array containing the attributes
- * for empty rows.
- * - selfPath: (string) The complete path for sorting and paging links.
- * (default: $_SERVER['PHP_SELF'])
- * - sortIconASC: (string) The icon to define that sorting is currently
- * ascending. Can be text or HTML to define an image.
- * - sortIconDESC: (string) The icon to define that sorting is currently
- * descending. Can be text or HTML to define an image.
- * - classASC: (string) A CSS class name for TH elements to define that
- * sorting is currently ascending.
- * - classDESC: (string) A CSS class name for TH elements to define that
- * sorting is currently descending.
- * - headerAttributes: (array) Attributes for the header row. This is an array
- * of the form: array(attribute => value, ...)
- * - convertEntities: (bool) Whether or not to convert html entities.
- * This calls htmlspecialchars().
- * - sortingResetsPaging: (bool) Whether sorting HTTP queries reset paging.
- *
- * SUPPORTED OPERATION MODES:
- *
- * - Container Support: yes
- * - Output Buffering: yes
- * - Direct Rendering: no
- * - Streaming: no
- * - Object Preserving: no
- *
- * @version $Revision: 1.1.1.1 $
- * @example ajax-simple.php Simple AJAX support using the Prototype framework
- * @author Andrew S. Nagy <asnagy@webitecture.org>
- * @author Olivier Guilyardi <olivier@samalyse.com>
- * @author Mark Wiesemann <wiesemann@php.net>
- * @author Sascha Grossenbacher <saschagros@bluewin.ch>
- * @access public
- * @package Structures_DataGrid_Renderer_HTMLTable
- * @category Structures
- */
-class Structures_DataGrid_Renderer_HTMLTable extends Structures_DataGrid_Renderer
-{
- /**
- * Rendering container
- * @var object HTML_Table object
- * @access protected
- */
- var $_table;
-
- /**
- * The html_table_storage object for the table header
- * @var object HTML_Table_Storage
- */
- var $_tableHeader;
-
- /**
- * The html_table_storage object for the table body
- * @var object HTML_Table_Storage
- */
- var $_tableBody;
-
- /**
- * The body row index to start rendering at
- * @var int
- */
- var $_bodyStartRow;
-
- /**
- * Constructor
- *
- * Build default values
- *
- * @access public
- */
- function Structures_DataGrid_Renderer_HTMLTable()
- {
- parent::Structures_DataGrid_Renderer();
- $this->_addDefaultOptions(
- array(
- 'evenRowAttributes' => array(),
- 'oddRowAttributes' => array(),
- 'emptyRowAttributes' => array(),
- 'selfPath' => htmlspecialchars($_SERVER['PHP_SELF']),
- 'sortIconASC' => '',
- 'sortIconDESC' => '',
- 'classASC' => '',
- 'classDESC' => '',
- 'headerAttributes' => array(),
- 'convertEntities' => true,
- 'sortingResetsPaging' => true,
- )
- );
- $this->_setFeatures(
- array(
- 'outputBuffering' => true,
- )
- );
- }
-
- /**
- * Attach an already instantiated HTML_Table object
- *
- * @var object HTML_Table object
- * @return mixed True or PEAR_Error
- * @access public
- */
- function setContainer(&$table)
- {
- $this->_table =& $table;
- return true;
- }
-
- /**
- * Return the currently used HTML_Table object
- *
- * @return object HTML_Table (reference to) or PEAR_Error
- * @access public
- */
- function &getContainer()
- {
- isset($this->_table) or $this->init();
- return $this->_table;
- }
-
- /**
- * Instantiate the HTML_Table container if needed, and set it up
- *
- * @access protected
- */
- function init()
- {
- if (!isset($this->_table)) {
- $this->_table = new HTML_Table(null, null, true);
- }
-
- $this->_tableHeader =& $this->_table->getHeader();
- $this->_tableBody =& $this->_table->getBody();
-
- $this->_bodyStartRow = $this->_tableBody->getRowCount();
- }
-
- /**
- * Set a table attribute
- *
- * @deprecated Use the HTML_Table constructor directly instead
- * @access public
- * @param string $attr The name of the attribute.
- * @param string $value The value of the attribute.
- */
- function setTableAttribute($attr, $value)
- {
- if (is_null($this->_table)) {
- $this->init();
- }
- $this->_table->updateAttributes(array($attr => $value));
- }
-
- /**
- * Define the table's header row attrbiutes
- *
- * @access public
- * @param array $attribs The attributes for the table header row.
- */
- function setTableHeaderAttributes($attribs)
- {
- $this->_options['headerAttributes'] = $attribs;
- }
-
- /**
- * Define the table's odd row attributes
- *
- * @access public
- * @param array $attribs The associative array of attributes for the
- * odd table row.
- * @see HTML_Table::setCellAttributes
- */
- function setTableOddRowAttributes($attribs)
- {
- $this->_options['oddRowAttributes'] = $attribs;
- }
-
- /**
- * Define the table's even row attributes
- *
- * @access public
- * @param array $attribs The associative array of attributes for the
- * even table row.
- * @see HTML_Table::setCellAttributes
- */
- function setTableEvenRowAttributes($attribs)
- {
- $this->_options['evenRowAttributes'] = $attribs;
- }
-
- /**
- * Define the table's autofill value. This value appears only in an empty
- * table cell.
- *
- * @access public
- * @param string $value The value to use for empty cells.
- */
- function setAutoFill($value)
- {
- if (is_null($this->_table)) {
- $this->init();
- }
- $this->_tableBody->setAutoFill($value);
- }
-
- /**
- * In order for the DataGrid to render "Empty Rows" to allow for uniformity
- * across pages with varying results, set this option to true. An example
- * of this would be when you have 11 results and have the DataGrid show 10
- * records per page. The last page will only show one row in the table,
- * unless this option is turned on in which it will render 10 rows, 9 of
- * which will be empty.
- *
- * @access public
- * @param bool $value A boolean value to determine whether or
- * not to display the empty rows.
- * @param array $attributes The empty row attributes defined in an
- * array.
- */
- function allowEmptyRows($value, $attributes = array())
- {
- $this->_options['fillWithEmptyRows'] = (bool)$value;
- $this->_options['emptyRowAttributes'] = $attributes;
- }
-
- /**
- * Determines whether or not to use the Header
- *
- * @deprecated Use the "buildHeader" option instead
- * @access public
- * @param bool $bool value to determine to use the header or not.
- */
- function useHeader($bool)
- {
- $this->_options['buildHeader'] = (bool)$bool;
- }
-
- /**
- * Add custom GET variables to the generated links
- *
- * This method adds the provided variables to the paging and sorting
- * links. The variable values are automatically url encoded.
- *
- * @deprecated Use the "extraVars" option instead
- * @param array $vars Array of the form (key => value, ...)
- * @access public
- * @return void
- */
- function setExtraVars($vars)
- {
- $this->_options['extraVars'] = $vars;
- }
-
- /**
- * Exclude GET variables from the generated links
- *
- * This method excludes the provided variables from the paging and sorting
- * links. This is helpful when using variables that determine what page to
- * show such as an 'action' variable, etc.
- *
- * @deprecated Use the "excludeVars" option instead
- * @param array $vars An array of variables to remove
- * @access public
- * @return void
- */
- function excludeVars($vars)
- {
- $this->_options['excludeVars'] = $vars;
- }
-
- /**
- * Generates the HTML for the DataGrid
- *
- * @deprecated Use getOutput() instead.
- * @access public
- * @return string The HTML of the DataGrid
- * @see Structures_DataGrid_Renderer::getOutput
- */
- function toHTML()
- {
- return $this->getOutput();
- }
-
- /**
- * Gets the HTML_Table object for the DataGrid
- *
- * @deprecated Use getContainer() instead.
- * @access public
- * @return object HTML_Table The HTML Table object for the DataGrid
- */
- function &getTable()
- {
- return $this->_table;
- }
-
- /**
- * Handles building the header of the DataGrid
- *
- * @param array $columns Columns' fields names and labels
- * @access protected
- * @return void
- * @see http://www.php.net/manual/en/function.http-build-query.php
- */
- function buildHeader(&$columns)
- {
- $row = $this->_tableHeader->getRowCount();
-
- foreach ($columns as $col => $spec) {
- $field = $spec['field'];
- $label = $spec['label'];
- $cssClass = '';
-
- // Define Content
- if (in_array($field, $this->_sortableFields)) {
-
- // Determine next sort direction and current sort icon
- reset($this->_currentSort);
- if (list($currentField,$currentDirection) = each($this->_currentSort)
- and $currentField == $field) {
- if ($currentDirection == 'ASC') {
- $icon = $this->_options['sortIconASC'];
- $cssClass = $this->_options['classASC'];
- $direction = 'DESC';
- } else {
- $icon = $this->_options['sortIconDESC'];
- $cssClass = $this->_options['classDESC'];
- $direction = 'ASC';
- }
- } else {
- $icon = '';
- $direction = $this->_defaultDirections[$field];
- }
-
- $page = $this->_options['sortingResetsPaging'] ? 1 : $this->_page;
-
- // Check if NUM is enabled
- if ($this->_urlMapper) {
- $url = $this->_buildMapperURL($field, $direction, $page);
- } else {
- // Build HTTP query
- $extra = array('page' => $page);
- $query = $this->_buildSortingHttpQuery($field, $direction, true, $extra);
-
- // Build Link URL
- $url = $this->_options['selfPath'] . '?' . $query;
- }
-
- // Build onclick attribute
- $onclick =
- $this->_buildOnMoveCall($page, array($field => $direction));
- $onclick = $onclick ? "onclick=\"return $onclick\"" : '';
-
- // Build HTML Link
- $str = "<a href=\"$url\" $onclick>$label$icon</a>";
- } else {
- $str = $label;
- }
-
- // Print Content to HTML_Table
- $this->_tableHeader->setHeaderContents($row, $col, $str);
-
- // Set TH attributes
- $attributes = isset($this->_options['columnAttributes'][$field])
- ? $this->_options['columnAttributes'][$field] : array();
- if ($cssClass) {
- $attributes['class'] = isset($attributes['class'])
- ? "{$attributes['class']} $cssClass" : $cssClass;
- }
- if ($attributes) {
- $this->_tableHeader->setCellAttributes($row, $col, $attributes);
- }
- }
- if (count($this->_options['headerAttributes']) > 0) {
- $this->_tableHeader->setRowAttributes($row, $this->_options['headerAttributes'], false);
- }
- }
-
- /**
- * Build a body row
- *
- * @param int $index Row index (zero-based)
- * @param array $data Record data.
- * Structure: array(0 => <value0>, 1 => <value1>, ...)
- * @return void
- * @access protected
- */
- function buildRow($index, $data)
- {
- $outputRow = $this->_bodyStartRow + $index;
- foreach ($data as $col => $value) {
- $field = $this->_columns[$col]['field'];
-
- // Right-align the content if it is numeric
- $attributes = ($this->_options['numberAlign'] and is_numeric($value))
- ? array('align' => 'right')
- : array();
-
- // merge auto-aligned and column attributes
- if (isset($this->_options['columnAttributes'][$field])) {
- $attributes = array_merge($attributes,
- $this->_options['columnAttributes'][$field]);
- }
-
- // Set content in HTML_Table
- $this->_tableBody->setCellContents($outputRow, $col, $value);
- if ($attributes) {
- $this->_tableBody->setCellAttributes($outputRow, $col, $attributes);
- }
- }
- }
-
- /**
- * Build an empty row
- *
- * This method will only be called if the "fillWithEmptyRows" option is
- * enabled.
- *
- * @param int $index Row index (zero-based)
- * @return void
- * @abstract
- */
- function buildEmptyRow($index)
- {
- $outputRow = $this->_bodyStartRow + $index;
- for ($col = 0; $col < $this->_columnsNum; $col++) {
- $this->_tableBody->setCellAttributes($outputRow, $col, $this->_options['emptyRowAttributes']);
- $this->_tableBody->setCellContents($outputRow, $col, ' ');
- }
- }
-
- /**
- * Default formatter for all cells
- *
- * @param string Cell value
- * @return string Formatted cell value
- * @access protected
- */
- function defaultCellFormatter($value)
- {
- return $this->_options['convertEntities']
- ? htmlspecialchars($value, ENT_COMPAT, $this->_options['encoding'])
- : $value;
- }
-
- /**
- * Finish building the datagrid.
- *
- * @access protected
- * @return void
- */
- function finalize()
- {
- // Define alternating row attributes
- if ($this->_options['evenRowAttributes']
- or $this->_options['oddRowAttributes']) {
-
- $this->_tableBody->altRowAttributes(
- 0,
- $this->_options['evenRowAttributes'],
- $this->_options['oddRowAttributes'],
- true
- );
- }
- }
-
- /**
- * Retrieve output from the container object
- *
- * @return mixed Output
- * @access protected
- */
- function flatten()
- {
- return $this->_table->toHTML();
- }
-
- /**
- * Handles the building of the page list for the DataGrid in HTML.
- *
- * This method uses the HTML::Pager class
- *
- * Useful options (See Pager's documentation for more):
- * mode: The mode of pager to use
- * separator: The string to use to separate each page link
- * prevImg: The string for the previous page link
- * nextImg: The string for the forward page link
- * delta: The number of pages to display before and
- * after the current page
- *
- * @deprecated Use Structures_DataGrid_Renderer_Pager instead
- * @access public
- * @param array $options Array of HTML::Pager options
- * @return string The HTML for the page links
- * @see HTML::Pager
- */
- function getPaging($options = array())
- {
- // This is a BC workaround for the old version of this method
- if (is_string($options)) {
- $argsNum = func_num_args();
- $args = func_get_args();
- $options = array();
-
- for ($i = 0; $i < $argsNum; $i++) {
- switch ($i) {
- case 0: $options['mode'] = $args[$i]; break;
- case 1: $options['separator'] = $args[$i]; break;
- case 2: $options['prevImg'] = $args[$i]; break;
- case 3: $options['nextImg'] = $args[$i]; break;
- case 4: $options['delta'] = $args[$i]; break;
- case 5: $options = array_merge($options, $args[$i]); break;
- }
- }
- }
-
- // Propagate the selfPath option. Do not override user params
- if (!isset($options['path']) && !isset($options['filename'])) {
- $options['path'] = dirname($this->_options['selfPath']);
- $options['fileName'] = basename($this->_options['selfPath']);
- $options['fixFileName'] = false;
- }
-
- // Load and get output from the Pager rendering driver
- $driver =& Structures_DataGrid::loadDriver('Structures_DataGrid_Renderer_Pager');
- $driver->setupAs($this, $options);
- $driver->build(array(), 0, true);
- return $driver->getOutput();
- }
-
-}
-
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-?>
+++ /dev/null
-<?php
-/**
- * Pager rendering driver
- *
- * PHP versions 4 and 5
- *
- * LICENSE:
- *
- * Copyright (c) 1997-2007, Andrew Nagy <asnagy@webitecture.org>,
- * Olivier Guilyardi <olivier@samalyse.com>,
- * Mark Wiesemann <wiesemann@php.net>
- * Sascha Grossenbacher <saschagros@bluewin.ch>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * The names of the authors may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * CSV file id: $Id: Pager.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
- *
- * @version $Revision: 1.1.1.1 $
- * @package Structures_DataGrid_Renderer_Pager
- * @category Structures
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- */
-
-require_once 'Structures/DataGrid/Renderer.php';
-require_once 'Pager/Pager.php';
-
-/**
- * Pager rendering driver
- *
- * This driver provides generic paging.
- *
- * This driver has full container support. You can use the
- * Structures_DataGrid::fill() method with it.
- *
- * It buffers output, you can use Structures_DataGrid::getOutput()
- *
- * SUPPORTED OPTIONS:
- *
- * - pagerOptions: (array) Options passed to Pager::factory().
- * Basic defaults are: mode: Sliding, delta: 5,
- * separator: "|", prevImg: "<<" (<<),
- * nextImg: ">>" (>>).
- * The extraVars and excludeVars options are
- * populated according to the Renderer common
- * extraVars and excludeVars options. You may also
- * specify some variables to be added or excluded
- * here.
- * The totalItems, perPage, urlVar, and currentPage
- * options are set accordingly to the data statistics
- * reported by the DataGrid and DataSource. You may
- * overload these values here if you know what you
- * are doing.
- * - columnAttributes: (-) IGNORED
- *
- * SUPPORTED OPERATION MODES:
- *
- * - Container Support: yes
- * - Output Buffering: yes
- * - Direct Rendering: no
- * - Streaming: no
- * - Object Preserving: no
- *
- * @version $Revision: 1.1.1.1 $
- * @author Olivier Guilyardi <olivier@samalyse.com>
- * @author Mark Wiesemann <wiesemann@php.net>
- * @author Andrew S. Nagy <asnagy@webitecture.org>
- * @author Sascha Grossenbacher <saschagros@bluewin.ch>
- * @access public
- * @package Structures_DataGrid_Renderer_Pager
- * @see Pager::factory()
- * @category Structures
- */
-class Structures_DataGrid_Renderer_Pager extends Structures_DataGrid_Renderer
-{
- /**
- * Rendering container
- * @var object Pager object
- * @access protected
- */
- var $_pager;
-
- /**
- * Constructor
- *
- * Set default options values
- *
- * @access public
- */
- function Structures_DataGrid_Renderer_Pager()
- {
- parent::Structures_DataGrid_Renderer();
- $this->_addDefaultOptions(
- array(
- 'pagerOptions' => array(
- 'mode' => 'Sliding',
- 'delta' => 5,
- 'separator' => '|',
- 'prevImg' => '<<',
- 'nextImg' => '>>',
- 'totalItems' => null, // dynamic; see init()
- 'perPage' => null, // dynamic; see init()
- 'urlVar' => null, // dynamic; see init()
- 'currentPage' => null, // dynamic; see init()
- 'onclick' => null, // dynamic; see init()
- 'extraVars' => array(),
- 'excludeVars' => array(),
- ),
- )
- );
- $this->_setFeatures(
- array(
- 'outputBuffering' => true,
- )
- );
- }
-
- /**
- * Attach an already instantiated Pager object
- *
- * @var object Pager object
- * @return mixed True or PEAR_Error
- * @access public
- */
- function setContainer(&$pager)
- {
- $this->_pager =& $pager;
- return true;
- }
-
- /**
- * Return the currently used Pager object
- *
- * @return object Pager (reference to) or PEAR_Error
- * @access public
- */
- function &getContainer()
- {
- isset($this->_pager) or $this->init();
- return $this->_pager;
- }
-
- /**
- * Instantiate the Pager container if needed, and set it up
- *
- * @access protected
- */
- function init()
- {
- $options = array();
-
- // Setting core pager options. Users can overwrite these
- if (is_null($this->_options['pagerOptions']['totalItems'])) {
- $options['totalItems'] = $this->_totalRecordsNum;
- }
-
- if (is_null($this->_options['pagerOptions']['perPage'])) {
- $options['perPage'] = is_null($this->_pageLimit)
- ? $this->_totalRecordsNum
- : $this->_pageLimit;
- }
-
- if (is_null($this->_options['pagerOptions']['urlVar'])) {
- $options['urlVar'] = $this->_requestPrefix . 'page';
- }
-
- if (is_null($this->_options['pagerOptions']['currentPage'])) {
- $options['currentPage'] = $this->_page;
- }
-
- if (is_null($this->_options['pagerOptions']['onclick'])) {
- $onclick = $this->_buildOnMoveCall('%d', $this->_currentSort);
- $options['onclick'] = $onclick ? "return $onclick" : '';
- }
-
- // Check if NUM is enabled
- if ($this->_urlMapper) {
- $options['append'] = false;
- $options['path'] = '';
-
- reset($this->_currentSort);
- $orderBy = key($this->_currentSort);
- $direction = current($this->_currentSort);
- $options['fileName'] = $this->_buildMapperURL($orderBy,
- $direction,
- '00000');
-
- // NUM does not allow a %d to be generated as page, hack needed..
- $options['fileName'] = str_replace('00000', '%d', $options['fileName']);
- }
-
- if (!isset($this->_pager)) {
- // No external container, Then we set our defaults.
- $options = array_merge($this->_options['pagerOptions'], $options);
-
- $options['excludeVars'] = array_merge($this->_options['excludeVars'],
- $options['excludeVars']);
-
- $options['extraVars'] = array_merge($this->_options['extraVars'],
- $options['extraVars']);
-
- $this->_pager =& Pager::factory($options);
- } else {
- // There is an external container. We try to be less intrusive as
- // possible. We need to set the core options anyway.
- $options = array_merge($this->_pager->getOptions(), $options);
-
- // FIXME: does not forward get arguments
-
- $options['excludeVars'] = array_merge($this->_options['excludeVars'],
- $options['excludeVars']);
-
- $options['extraVars'] = array_merge($this->_options['extraVars'],
- $options['extraVars']);
-
- $this->_pager->setOptions($options);
- }
- }
-
- /**
- * Retrieve links from the Pager object
- *
- * @return string HTML links
- * @access protected
- */
- function flatten()
- {
- return $this->_pager->links;
- }
-
- /**
- * Helper methods for drivers that automatically load this driver
- *
- * This is (or has been...) used by the HTMLTable and Smarty driver
- *
- * @param object $renderer External driver
- * @param array $pagerOptions pager options
- * @return void
- * @access public
- */
- function setupAs(&$renderer, $pagerOptions)
- {
- $this->setLimit($renderer->_page, $renderer->_pageLimit,
- $renderer->_totalRecordsNum);
- $this->setRequestPrefix($renderer->_requestPrefix);
- $this->setCurrentSorting($renderer->_currentSort, $renderer->_multiSort);
- $options['pagerOptions'] = array_merge($this->_options['pagerOptions'],
- $pagerOptions);
- $options['excludeVars'] = $renderer->_options['excludeVars'];
- $options['extraVars'] = $renderer->_options['extraVars'];
- $options['onMove'] = $renderer->_options['onMove'];
- $options['onMoveData'] = $renderer->_options['onMoveData'];
- $this->setOptions($options);
- $this->setUrlMapper($renderer->getUrlMapper());
- }
-
- /**
- * Set multiple options
- *
- * @param mixed $options An associative array of the form:
- * array("option_name" => "option_value",...)
- * @access public
- */
- function setOptions($options)
- {
- /* This method is overloaded here because array_merge() needs to be called
- * over the "pagerOptions" option. Otherwise, if the user only provide a few
- * pager options, built-in defaults generally get overwritten.
- *
- * setOptions() is a public method, so it can be overloaded. But, because
- * the $_options method is considered read-only, this method does not write
- * into this property directly. It calls parent::setOptions() instead.
- */
- if (isset($options['pagerOptions'])) {
- $options['pagerOptions'] = array_merge($this->_options['pagerOptions'],
- $options['pagerOptions']);
- if (isset($this->_pager)) {
- $this->_pager->setOptions($options['pagerOptions']);
- }
- }
- parent::setOptions($options);
- }
-
- /**
- * Set a single option
- *
- * @param string $name Option name
- * @param mixed $value Option value
- * @access public
- */
- function setOption($name, $value)
- {
- // see notes in setOptions()
- if ($name == 'pagerOptions') {
- $value = array_merge($this->_options['pagerOptions'],$value);
- if (isset($this->_pager)) {
- $this->_pager->setOptions($value);
- }
- }
- parent::setOption($name,$value);
- }
-
- /**
- * Rebuild the pager links
- *
- * This is useful because the pager options may change after it gets
- * instantiated.
- *
- * @access protected
- * @return void
- */
- function buildBody()
- {
- $this->_pager->build();
- }
-}
-
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-?>
+++ /dev/null
-<?php
-/**
- * Smarty Rendering Driver
- *
- * PHP versions 4 and 5
- *
- * LICENSE:
- *
- * Copyright (c) 1997-2007, Andrew Nagy <asnagy@webitecture.org>,
- * Olivier Guilyardi <olivier@samalyse.com>,
- * Mark Wiesemann <wiesemann@php.net>
- * Sascha Grossenbacher <saschagros@bluewin.ch>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * The names of the authors may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * CVS file id: $Id: Smarty.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
- *
- * @version $Revision: 1.1.1.1 $
- * @package Structures_DataGrid_Renderer_Smarty
- * @category Structures
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- */
-
-require_once 'Structures/DataGrid.php';
-require_once 'Structures/DataGrid/Renderer.php';
-
-/**
- * Smarty Rendering Driver
- *
- * SUPPORTED OPTIONS:
- *
- * - selfPath: (string) The complete path for sorting and paging links.
- * (default: $_SERVER['PHP_SELF'])
- * - sortingResetsPaging: (bool) Whether sorting HTTP queries reset paging.
- * - convertEntities: (bool) Whether or not to convert html entities.
- * This calls htmlspecialchars().
- * - varPrefix: (string) Prefix for smarty variables and functions
- * assigned by this driver. Can be used in
- * conjunction with
- * Structure_DataGrid::setRequestPrefix() for
- * displaying several grids on a single page.
- * - associative: (bool) By default the column set and the records
- * are numerically indexed arrays. By setting
- * this option to true the keys will be field
- * names instead.
- *
- * SUPPORTED OPERATION MODES:
- *
- * - Container Support: yes
- * - Output Buffering: yes
- * - Direct Rendering: no
- * - Streaming: no
- * - Object Preserving: yes
- *
- * GENERAL NOTES:
- *
- * To use this driver you need the Smarty template engine from
- * http://smarty.php.net
- *
- * This driver does not support the render() method, it is only able to:
- *
- * Either fill() a Smarty object by assigning variables and registering
- * the {getPaging} smarty function. It's up to you to call Smarty::display()
- * after the Smarty object has been filled.
- *
- * Or return all variables as a PHP array from getOutput(), for maximum
- * flexibility, so that you can assign them the way you like to your Smarty
- * instance.
- *
- * This driver assigns the following Smarty variables:
- * <code>
- * - $columnSet: array of columns specifications
- * structure:
- * array (
- * 0 => array (
- * 'name' => field name,
- * 'label' => column label,
- * 'link' => sorting link,
- * 'attributes' => attributes string,
- * 'direction' => 'ASC', 'DESC' or '',
- * 'onclick' => onMove call
- * ),
- * ...
- * )
- * - $recordSet: array of records values
- * - $currentPage: current page (starting from 1)
- * - $nextPage: next page
- * - $previousPage: previous page
- * - $recordLimit: number of rows per page
- * - $pagesNum: number of pages
- * - $columnsNum: number of columns
- * - $recordsNum: number of records in the current page
- * - $totalRecordsNum: total number of records
- * - $firstRecord: first record number (starting from 1)
- * - $lastRecord: last record number (starting from 1)
- * - $currentSort: array with column names and the directions used for sorting
- * - $datagrid: a reference that you can pass to {getPaging}
- * </code>
- *
- * This driver registers a Smarty custom function named getPaging
- * that can be called from Smarty templates with {getPaging} in order
- * to print paging links. This function accepts the same parameters as the
- * pagerOptions option of Structures_DataGrid_Renderer_Pager.
- *
- * {getPaging} accepts an optional "datagrid" parameter
- * which you can pass the $datagrid variable, to display paging for an
- * arbitrary datagrid (useful with multiple dynamic datagrids on a single page).
- *
- * Object Records : this drivers preserves object records if provided. This means
- * that if your datasource provides objects instead of associative arrays as
- * records, you can access their properties and methods in your smarty template,
- * with something like: {$recordSet[col]->getSomeInformation()}.
- *
- * @version $Revision: 1.1.1.1 $
- * @example smarty-simple.php Using the Smarty renderer
- * @example smarty-simple.tpl Smarty template with sorting and paging (smarty-simple.tpl)
- * @author Andrew S. Nagy <asnagy@webitecture.org>
- * @author Olivier Guilyardi <olivier@samalyse.com>
- * @author Sascha Grossenbacher <saschagros@bluewin.ch>
- * @access public
- * @package Structures_DataGrid_Renderer_Smarty
- * @see Structures_DataGrid_Renderer_Pager
- * @category Structures
- */
-class Structures_DataGrid_Renderer_Smarty extends Structures_DataGrid_Renderer
-{
- /**
- * Variables that get assigned into the Smarty container
- * @var array Associative array with smarty var names as keys
- */
- var $_data;
-
- /**
- * Smarty container
- * @var object Smarty object
- */
- var $_smarty = null;
-
- /**
- * Constructor
- *
- * @access public
- */
- function Structures_DataGrid_Renderer_Smarty()
- {
- parent::Structures_DataGrid_Renderer();
- $this->_addDefaultOptions(
- array(
- 'selfPath' => htmlspecialchars($_SERVER['PHP_SELF']),
- 'convertEntities' => true,
- 'sortingResetsPaging' => true,
- 'varPrefix' => '',
- 'associative' => false,
- )
- );
-
- $this->_setFeatures(
- array(
- 'outputBuffering' => true,
- 'objectPreserving' => true,
- )
- );
- }
-
- /**
- * Attach an already instantiated Smarty object
- *
- * @param object $smarty Smarty container
- * @return mixed True or PEAR_Error
- */
- function setContainer(&$smarty)
- {
- $this->_smarty =& $smarty;
- return true;
- }
-
- /**
- * Attach a Smarty instance
- *
- * @deprecated Use setContainer() instead
- * @param object Smarty instance
- * @access public
- */
- function setSmarty(&$smarty)
- {
- return $this->setContainer($smarty);
- }
-
- /**
- * Return the currently used Smarty object
- *
- * @return object Smarty or PEAR_Error object
- */
- function &getContainer()
- {
- return $this->_smarty;
- }
-
- /**
- * Initialize the Smarty container
- *
- * @access protected
- */
- function init()
- {
- $p = $this->_options['varPrefix'];
- $this->_data = array(
- "{$p}currentPage" => $this->_page,
- "{$p}nextPage" => ($this->_page < $this->_pagesNum) ? $this->_page + 1 : null,
- "{$p}previousPage" => ($this->_page > 1) ? $this->_page - 1 : null,
- "{$p}recordLimit" => $this->_pageLimit,
- "{$p}columnsNum" => $this->_columnsNum,
- "{$p}recordsNum" => $this->_recordsNum,
- "{$p}totalRecordsNum" => $this->_totalRecordsNum,
- "{$p}pagesNum" => $this->_pagesNum,
- "{$p}firstRecord" => $this->_firstRecord,
- "{$p}lastRecord" => $this->_lastRecord,
- "{$p}currentSort" => $this->_currentSort,
- );
- }
-
- /**
- * Build the header
- *
- * @param array $columns Columns' fields names and labels
- * @access protected
- * @return void
- */
- function buildHeader(&$columns)
- {
- $prepared = array();
- foreach ($columns as $index => $spec) {
- $key = $this->_options['associative'] ? $spec['field'] : $index;
- if (in_array($spec['field'], $this->_sortableFields)) {
- reset($this->_currentSort);
- if ((list($currentField, $currentDirection) = each($this->_currentSort))
- && isset($currentField)
- && $currentField == $spec['field']
- ) {
- if ($currentDirection == 'ASC') {
- $direction = 'DESC';
- } else {
- $direction = 'ASC';
- }
- $prepared[$key]['direction'] = $currentDirection;
- } else {
- $prepared[$key]['direction'] = '';
- $direction = $this->_defaultDirections[$spec['field']];
- }
- $page = $this->_options['sortingResetsPaging'] ? 1 : $this->_page;
- $extra = array('page' => $page);
- // Check if NUM is enabled
- if ($this->_urlMapper) {
- $prepared[$key]['link'] = $this->_buildMapperURL($spec['field'],
- $direction,
- $page);
- } else {
- $query = $this->_buildSortingHttpQuery($spec['field'],
- $direction, true, $extra);
- $prepared[$key]['link'] = "{$this->_options['selfPath']}?$query";
- }
- $prepared[$key]['onclick'] = $this->_buildOnMoveCall($page,
- array($spec['field'] => $direction));
- } else {
- $query = '';
- $prepared[$key]['link'] = "";
- }
- $prepared[$key]['name'] = $spec['field'];
- $prepared[$key]['label'] = $spec['label'];
-
- $prepared[$key]['attributes'] = "";
- if (isset($this->_options['columnAttributes'][$spec['field']])) {
- foreach ($this->_options['columnAttributes'][$spec['field']]
- as $name => $value) {
- $value = htmlspecialchars($value, ENT_COMPAT,
- $this->_options['encoding']);
- $prepared[$key]['attributes'] .= "$name=\"$value\" ";
- }
- }
- }
-
- $this->_data[$this->_options['varPrefix'] . 'columnSet'] = $prepared;
- }
-
- /**
- * Handles building the body of the table
- *
- * @access protected
- * @return void
- */
- function buildBody()
- {
- if ($this->_options['associative']) {
- $associative = array();
- foreach ($this->_records as $row => $rec) {
- if (is_array($rec)) { // object records are left untouched
- $associative[$row] = array();
- foreach ($this->_columns as $col => $spec) {
- $associative[$row][$spec['field']] = $rec[$col];
- }
- } else {
- $associative[$row] =& $this->_records[$row];
- }
- }
- $this->_data[$this->_options['varPrefix'] . 'recordSet']
- = $associative;
- } else {
- $this->_data[$this->_options['varPrefix'] . 'recordSet']
- = $this->_records;
- }
- }
-
- /**
- * Assign the computed variables to the Smarty container, if any
- *
- * @access protected
- * @return void
- */
- function finalize()
- {
- $p = $this->_options['varPrefix'];
-
- if ($this->_smarty) {
- foreach ($this->_data as $key => $val) {
- $this->_smarty->assign($key, $val);
- }
-
- $this->_smarty->assign("{$p}datagrid", $this->_getReference());
-
- $this->_smarty->register_function("{$p}getPaging",
- array(&$this, 'smartyGetPaging'));
- } else {
- $this->_data["{$p}datagrid"] = $this->_getReference();
- }
- }
-
- /**
- * Return the computed variables
- *
- * @access protected
- * @return array Array with smarty variable names as keys
- */
- function flatten()
- {
- return $this->_data;
- }
-
- /**
- * Discard the unsupported render() method
- *
- * This Smarty driver does not support the render() method.
- * It is required to use the setContainer() (or
- * Structures_DataGrid::fill()) method in order to do anything
- * with this driver.
- *
- */
- function render()
- {
- return $this->_noSupport(__FUNCTION__);
- }
-
- /**
- * Smarty custom function "getPaging"
- *
- * This is only meant to be called from a smarty template, using the
- * expression: {getPaging <options>}
- *
- * <options> are any Pager::factory() options
- *
- * @param array $params Options passed from the Smarty template
- * @param object $smarty Smarty object
- * @return string Paging HTML links
- * @access public
- */
- function smartyGetPaging($params, &$smarty)
- {
- // Load and get output from the Pager rendering driver
- $driver =& Structures_DataGrid::loadDriver('Structures_DataGrid_Renderer_Pager');
-
- // Propagate the selfPath option. Do not override user params
- if (!isset($params['path']) && !isset($params['filename'])) {
- $params['path'] = dirname($this->_options['selfPath']);
- $params['fileName'] = basename($this->_options['selfPath']);
- $params['fixFileName'] = false;
- }
-
- // Use a different renderer if provided
- if (isset($params['datagrid'])) {
- $renderer =& $this->_getReference($params['datagrid']);
- unset($params['datagrid']);
- } else {
- $renderer =& $this;
- }
-
- $driver->setupAs($renderer, $params);
- $driver->build(array(), 0);
- return $driver->getOutput();
- }
-
- /**
- * Return a renderer reference by id or create a new id
- *
- * @param int Renderer id
- * @return mixed New id or renderer object
- */
- function &_getReference($id = null)
- {
- static $references = array();
-
- if (!is_null($id)) {
- return $references[$id - 1];
- } else {
- $references[] =& $this;
- $id = count($references);
- return $id;
- }
- }
-
- /**
- * Default formatter for all cells
- *
- * @param string Cell value
- * @return string Formatted cell value
- * @access protected
- */
- function defaultCellFormatter($value)
- {
- return $this->_options['convertEntities']
- ? htmlspecialchars($value, ENT_COMPAT, $this->_options['encoding'])
- : $value;
- }
-}
-
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-?>
+++ /dev/null
-<?php
-/**
- * XML Rendering Driver
- *
- * PHP versions 4 and 5
- *
- * LICENSE:
- *
- * Copyright (c) 1997-2007, Andrew Nagy <asnagy@webitecture.org>,
- * Olivier Guilyardi <olivier@samalyse.com>,
- * Mark Wiesemann <wiesemann@php.net>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * The names of the authors may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * CSV file id: $Id: XML.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
- *
- * @version $Revision: 1.1.1.1 $
- * @category Structures
- * @package Structures_DataGrid_Renderer_XML
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- */
-
-require_once 'Structures/DataGrid/Renderer.php';
-require_once 'XML/Util.php';
-
-/**
- * XML Rendering Driver
- *
- * SUPPORTED OPTIONS:
- *
- * - useXMLDecl: (bool) Whether the XML declaration string should be added
- * to the output. The encoding attribute value will
- * get set from the common "encoding" option. If you
- * need to further customize the XML declaration
- * (version, etc..), then please set "useXMLDecl" to
- * false, and add your own declaration string.
- * - outerTag: (string) The name of the tag for the datagrid, without
- * brackets
- * - rowTag: (string) The name of the tag for each row, without brackets
- * - fieldTag: (string) The name of the tag for each field inside a row,
- * without brackets. The special value '{field}' is
- * replaced by the field name.
- * - fieldAttribute:(string) The name of the attribute for the field name.
- * null stands for no attribute
- * - labelAttribute:(string) The name of the attribute for the column label.
- * null stands for no attribute
- * - filename: (string) Filename of the generated XML file; boolean false
- * means that no filename will be sent
- * - saveToFile: (boolean) Whether the output should be saved on the local
- * filesystem. Please note that the 'filename' option
- * must be given if this option is set to true.
- * - writeMode: (string) The mode that is used in the internal fopen() calls.
- * Useful e.g. when you want to append to existing file.
- * C.p. the fopen() documentation for the allowed modes.
- *
- * SUPPORTED OPERATION MODES:
- *
- * - Container Support: no
- * - Output Buffering: yes
- * - Direct Rendering: yes
- * - Streaming: yes
- *
- * @version $Revision: 1.1.1.1 $
- * @author Andrew S. Nagy <asnagy@webitecture.org>
- * @author Olivier Guilyardi <olivier@samalyse.com>
- * @author Mark Wiesemann <wiesemann@php.net>
- * @access public
- * @category Structures
- * @package Structures_DataGrid_Renderer_XML
- */
-class Structures_DataGrid_Renderer_XML extends Structures_DataGrid_Renderer
-{
-
- /**
- * XML output
- * @var string
- * @access private
- */
- var $_xml;
-
- /**
- * Constructor
- *
- * Build default values
- *
- * @access public
- */
- function Structures_DataGrid_Renderer_XML()
- {
- parent::Structures_DataGrid_Renderer();
- $this->_addDefaultOptions(
- array(
- 'useXMLDecl' => true,
- 'outerTag' => 'DataGrid',
- 'rowTag' => 'Row',
- 'fieldTag' => '{field}',
- 'fieldAttribute' => null,
- 'labelAttribute' => null,
- 'filename' => false,
- 'saveToFile' => false,
- 'writeMode' => 'wb',
- )
- );
- $this->_setFeatures(
- array(
- 'streaming' => true,
- 'outputBuffering' => true,
- )
- );
- }
-
- /**
- * Initialize a string for the XML code if it is not already existing
- *
- * @access protected
- */
- function init()
- {
- $this->_xml = '';
- if ($this->_options['saveToFile'] === true) {
- if ($this->_options['filename'] === false) {
- return PEAR::raiseError('No filename specified via "filename" ' .
- 'option.');
- }
- $this->_fp = fopen($this->_options['filename'],
- $this->_options['writeMode']);
- if ($this->_fp === false) {
- return PEAR::raiseError('Could not open file "' .
- $this->_options['filename'] . '" ' .
- 'for writing.');
- }
- }
-
- $xml = '';
- if ($this->_options['useXMLDecl']) {
- $xml .= XML_Util::getXMLDeclaration('1.0',
- $this->_options['encoding']) . "\n";
- }
- $xml .= "<{$this->_options['outerTag']}>\n";
- if ($this->_options['saveToFile'] === true) {
- $res = fwrite($this->_fp, $xml);
- if ($res === false) {
- return PEAR::raiseError('Could not write into file "' .
- $this->_options['filename'] . '".');
- }
- } elseif ($this->_streamingEnabled) {
- echo $xml;
- } else {
- $this->_xml .= $xml;
- }
- }
-
- /**
- * Generates the XML for the DataGrid
- *
- * @access public
- * @return string The XML of the DataGrid
- */
- function toXML()
- {
- return $this->getOutput();
- }
-
- /**
- * Build a body row
- *
- * @param int $index Row index (zero-based)
- * @param array $data Record data.
- * @access protected
- * @return void
- */
- function buildRow($index, $data)
- {
- $xml = " <{$this->_options['rowTag']}>\n";
- foreach ($data as $col => $value) {
- $field = $this->_columns[$col]['field'];
- $tag = ($this->_options['fieldTag'] == '{field}')
- ? $field : $this->_options['fieldTag'];
-
- $attributes = array();
- if (!is_null($this->_options['fieldAttribute'])) {
- $attributes[$this->_options['fieldAttribute']]
- = $this->_columns[$col]['field'];
- }
- if (!is_null($this->_options['labelAttribute'])) {
- $attributes[$this->_options['labelAttribute']]
- = $this->_columns[$col]['label'];
- }
-
- if (isset($this->_options['columnAttributes'][$field])) {
- $attributes = array_merge (
- $this->_options['columnAttributes'][$field],
- $attributes);
- }
-
- $xml .= ' ' . XML_Util::createTag($tag, $attributes, $value) . "\n";
- }
- $xml .= " </{$this->_options['rowTag']}>\n";
- if ($this->_options['saveToFile'] === true) {
- $res = fwrite($this->_fp, $xml);
- if ($res === false) {
- return PEAR::raiseError('Could not write into file "' .
- $this->_options['filename'] . '".');
- }
- } elseif ($this->_streamingEnabled) {
- echo $xml;
- } else {
- $this->_xml .= $xml;
- }
- }
-
- /**
- * Retrieve output from the container object
- *
- * @return mixed Output
- * @access protected
- */
- function flatten()
- {
- return $this->_xml;
- }
-
- /**
- * Finish building the datagrid.
- *
- * @access protected
- * @return void
- */
- function finalize()
- {
- $xml = "</{$this->_options['outerTag']}>\n";
- if ($this->_options['saveToFile'] === true) {
- $res = fwrite($this->_fp, $xml);
- if ($res === false) {
- return PEAR::raiseError('Could not write into file "' .
- $this->_options['filename'] . '".');
- }
- $res = fclose($this->_fp);
- if ($res === false) {
- return PEAR::raiseError('Could not close file "' .
- $this->_options['filename'] . '".');
- }
- } elseif ($this->_streamingEnabled) {
- echo $xml;
- } else {
- $this->_xml .= $xml;
- }
- }
-
- /**
- * Render to the standard output
- *
- * @access public
- */
- function render()
- {
- if ($this->_options['saveToFile'] === false) {
- header('Content-type: text/xml');
- if ($this->_options['filename'] !== false) {
- header('Content-disposition: attachment; filename=' .
- $this->_options['filename']);
- }
- }
- parent::render();
- }
-}
-
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-?>
+++ /dev/null
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available through the world-wide-web at the following url: |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Tomas V.V.Cox <cox@idecnet.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: System.php,v 1.1.1.1 2008/04/28 15:20:46 jamie Exp $
-//
-
-require_once 'PEAR.php';
-require_once 'Console/Getopt.php';
-
-$GLOBALS['_System_temp_files'] = array();
-
-/**
-* System offers cross plattform compatible system functions
-*
-* Static functions for different operations. Should work under
-* Unix and Windows. The names and usage has been taken from its respectively
-* GNU commands. The functions will return (bool) false on error and will
-* trigger the error with the PHP trigger_error() function (you can silence
-* the error by prefixing a '@' sign after the function call).
-*
-* Documentation on this class you can find in:
-* http://pear.php.net/manual/
-*
-* Example usage:
-* if (!@System::rm('-r file1 dir1')) {
-* print "could not delete file1 or dir1";
-* }
-*
-* In case you need to to pass file names with spaces,
-* pass the params as an array:
-*
-* System::rm(array('-r', $file1, $dir1));
-*
-* @package System
-* @author Tomas V.V.Cox <cox@idecnet.com>
-* @version $Revision: 1.1.1.1 $
-* @access public
-* @see http://pear.php.net/manual/
-*/
-class System
-{
- /**
- * returns the commandline arguments of a function
- *
- * @param string $argv the commandline
- * @param string $short_options the allowed option short-tags
- * @param string $long_options the allowed option long-tags
- * @return array the given options and there values
- * @access private
- */
- function _parseArgs($argv, $short_options, $long_options = null)
- {
- if (!is_array($argv) && $argv !== null) {
- $argv = preg_split('/\s+/', $argv);
- }
- return Console_Getopt::getopt2($argv, $short_options);
- }
-
- /**
- * Output errors with PHP trigger_error(). You can silence the errors
- * with prefixing a "@" sign to the function call: @System::mkdir(..);
- *
- * @param mixed $error a PEAR error or a string with the error message
- * @return bool false
- * @access private
- */
- function raiseError($error)
- {
- if (PEAR::isError($error)) {
- $error = $error->getMessage();
- }
- trigger_error($error, E_USER_WARNING);
- return false;
- }
-
- /**
- * Creates a nested array representing the structure of a directory
- *
- * System::_dirToStruct('dir1', 0) =>
- * Array
- * (
- * [dirs] => Array
- * (
- * [0] => dir1
- * )
- *
- * [files] => Array
- * (
- * [0] => dir1/file2
- * [1] => dir1/file3
- * )
- * )
- * @param string $sPath Name of the directory
- * @param integer $maxinst max. deep of the lookup
- * @param integer $aktinst starting deep of the lookup
- * @return array the structure of the dir
- * @access private
- */
-
- function _dirToStruct($sPath, $maxinst, $aktinst = 0)
- {
- $struct = array('dirs' => array(), 'files' => array());
- if (($dir = @opendir($sPath)) === false) {
- System::raiseError("Could not open dir $sPath");
- return $struct; // XXX could not open error
- }
- $struct['dirs'][] = $sPath; // XXX don't add if '.' or '..' ?
- $list = array();
- while ($file = readdir($dir)) {
- if ($file != '.' && $file != '..') {
- $list[] = $file;
- }
- }
- closedir($dir);
- sort($list);
- if ($aktinst < $maxinst || $maxinst == 0) {
- foreach($list as $val) {
- $path = $sPath . DIRECTORY_SEPARATOR . $val;
- if (is_dir($path)) {
- $tmp = System::_dirToStruct($path, $maxinst, $aktinst+1);
- $struct = array_merge_recursive($tmp, $struct);
- } else {
- $struct['files'][] = $path;
- }
- }
- }
- return $struct;
- }
-
- /**
- * Creates a nested array representing the structure of a directory and files
- *
- * @param array $files Array listing files and dirs
- * @return array
- * @see System::_dirToStruct()
- */
- function _multipleToStruct($files)
- {
- $struct = array('dirs' => array(), 'files' => array());
- settype($files, 'array');
- foreach ($files as $file) {
- if (is_dir($file)) {
- $tmp = System::_dirToStruct($file, 0);
- $struct = array_merge_recursive($tmp, $struct);
- } else {
- $struct['files'][] = $file;
- }
- }
- return $struct;
- }
-
- /**
- * The rm command for removing files.
- * Supports multiple files and dirs and also recursive deletes
- *
- * @param string $args the arguments for rm
- * @return mixed PEAR_Error or true for success
- * @access public
- */
- function rm($args)
- {
- $opts = System::_parseArgs($args, 'rf'); // "f" do nothing but like it :-)
- if (PEAR::isError($opts)) {
- return System::raiseError($opts);
- }
- foreach($opts[0] as $opt) {
- if ($opt[0] == 'r') {
- $do_recursive = true;
- }
- }
- $ret = true;
- if (isset($do_recursive)) {
- $struct = System::_multipleToStruct($opts[1]);
- foreach($struct['files'] as $file) {
- if (!@unlink($file)) {
- $ret = false;
- }
- }
- foreach($struct['dirs'] as $dir) {
- if (!@rmdir($dir)) {
- $ret = false;
- }
- }
- } else {
- foreach ($opts[1] as $file) {
- $delete = (is_dir($file)) ? 'rmdir' : 'unlink';
- if (!@$delete($file)) {
- $ret = false;
- }
- }
- }
- return $ret;
- }
-
- /**
- * Make directories. Note that we use call_user_func('mkdir') to avoid
- * a problem with ZE2 calling System::mkDir instead of the native PHP func.
- *
- * @param string $args the name of the director(y|ies) to create
- * @return bool True for success
- * @access public
- */
- function mkDir($args)
- {
- $opts = System::_parseArgs($args, 'pm:');
- if (PEAR::isError($opts)) {
- return System::raiseError($opts);
- }
- $mode = 0777; // default mode
- foreach($opts[0] as $opt) {
- if ($opt[0] == 'p') {
- $create_parents = true;
- } elseif($opt[0] == 'm') {
- // if the mode is clearly an octal number (starts with 0)
- // convert it to decimal
- if (strlen($opt[1]) && $opt[1]{0} == '0') {
- $opt[1] = octdec($opt[1]);
- } else {
- // convert to int
- $opt[1] += 0;
- }
- $mode = $opt[1];
- }
- }
- $ret = true;
- if (isset($create_parents)) {
- foreach($opts[1] as $dir) {
- $dirstack = array();
- while (!@is_dir($dir) && $dir != DIRECTORY_SEPARATOR) {
- array_unshift($dirstack, $dir);
- $dir = dirname($dir);
- }
- while ($newdir = array_shift($dirstack)) {
- if (!call_user_func('mkdir', $newdir, $mode)) {
- $ret = false;
- }
- }
- }
- } else {
- foreach($opts[1] as $dir) {
- if (!@is_dir($dir) && !call_user_func('mkdir', $dir, $mode)) {
- $ret = false;
- }
- }
- }
- return $ret;
- }
-
- /**
- * Concatenate files
- *
- * Usage:
- * 1) $var = System::cat('sample.txt test.txt');
- * 2) System::cat('sample.txt test.txt > final.txt');
- * 3) System::cat('sample.txt test.txt >> final.txt');
- *
- * Note: as the class use fopen, urls should work also (test that)
- *
- * @param string $args the arguments
- * @return boolean true on success
- * @access public
- */
- function &cat($args)
- {
- $ret = null;
- $files = array();
- if (!is_array($args)) {
- $args = preg_split('/\s+/', $args);
- }
- for($i=0; $i < count($args); $i++) {
- if ($args[$i] == '>') {
- $mode = 'wb';
- $outputfile = $args[$i+1];
- break;
- } elseif ($args[$i] == '>>') {
- $mode = 'ab+';
- $outputfile = $args[$i+1];
- break;
- } else {
- $files[] = $args[$i];
- }
- }
- if (isset($mode)) {
- if (!$outputfd = fopen($outputfile, $mode)) {
- $err = System::raiseError("Could not open $outputfile");
- return $err;
- }
- $ret = true;
- }
- foreach ($files as $file) {
- if (!$fd = fopen($file, 'r')) {
- System::raiseError("Could not open $file");
- continue;
- }
- while ($cont = fread($fd, 2048)) {
- if (isset($outputfd)) {
- fwrite($outputfd, $cont);
- } else {
- $ret .= $cont;
- }
- }
- fclose($fd);
- }
- if (@is_resource($outputfd)) {
- fclose($outputfd);
- }
- return $ret;
- }
-
- /**
- * Creates temporary files or directories. This function will remove
- * the created files when the scripts finish its execution.
- *
- * Usage:
- * 1) $tempfile = System::mktemp("prefix");
- * 2) $tempdir = System::mktemp("-d prefix");
- * 3) $tempfile = System::mktemp();
- * 4) $tempfile = System::mktemp("-t /var/tmp prefix");
- *
- * prefix -> The string that will be prepended to the temp name
- * (defaults to "tmp").
- * -d -> A temporary dir will be created instead of a file.
- * -t -> The target dir where the temporary (file|dir) will be created. If
- * this param is missing by default the env vars TMP on Windows or
- * TMPDIR in Unix will be used. If these vars are also missing
- * c:\windows\temp or /tmp will be used.
- *
- * @param string $args The arguments
- * @return mixed the full path of the created (file|dir) or false
- * @see System::tmpdir()
- * @access public
- */
- function mktemp($args = null)
- {
- static $first_time = true;
- $opts = System::_parseArgs($args, 't:d');
- if (PEAR::isError($opts)) {
- return System::raiseError($opts);
- }
- foreach($opts[0] as $opt) {
- if($opt[0] == 'd') {
- $tmp_is_dir = true;
- } elseif($opt[0] == 't') {
- $tmpdir = $opt[1];
- }
- }
- $prefix = (isset($opts[1][0])) ? $opts[1][0] : 'tmp';
- if (!isset($tmpdir)) {
- $tmpdir = System::tmpdir();
- }
- if (!System::mkDir("-p $tmpdir")) {
- return false;
- }
- $tmp = tempnam($tmpdir, $prefix);
- if (isset($tmp_is_dir)) {
- unlink($tmp); // be careful possible race condition here
- if (!call_user_func('mkdir', $tmp, 0700)) {
- return System::raiseError("Unable to create temporary directory $tmpdir");
- }
- }
- $GLOBALS['_System_temp_files'][] = $tmp;
- if ($first_time) {
- PEAR::registerShutdownFunc(array('System', '_removeTmpFiles'));
- $first_time = false;
- }
- return $tmp;
- }
-
- /**
- * Remove temporary files created my mkTemp. This function is executed
- * at script shutdown time
- *
- * @access private
- */
- function _removeTmpFiles()
- {
- if (count($GLOBALS['_System_temp_files'])) {
- $delete = $GLOBALS['_System_temp_files'];
- array_unshift($delete, '-r');
- System::rm($delete);
- }
- }
-
- /**
- * Get the path of the temporal directory set in the system
- * by looking in its environments variables.
- * Note: php.ini-recommended removes the "E" from the variables_order setting,
- * making unavaible the $_ENV array, that s why we do tests with _ENV
- *
- * @return string The temporal directory on the system
- */
- function tmpdir()
- {
- if (OS_WINDOWS) {
- if ($var = isset($_ENV['TEMP']) ? $_ENV['TEMP'] : getenv('TEMP')) {
- return $var;
- }
- if ($var = isset($_ENV['TMP']) ? $_ENV['TMP'] : getenv('TMP')) {
- return $var;
- }
- if ($var = isset($_ENV['windir']) ? $_ENV['windir'] : getenv('windir')) {
- return $var;
- }
- return getenv('SystemRoot') . '\temp';
- }
- if ($var = isset($_ENV['TMPDIR']) ? $_ENV['TMPDIR'] : getenv('TMPDIR')) {
- return $var;
- }
- return '/tmp';
- }
-
- /**
- * The "which" command (show the full path of a command)
- *
- * @param string $program The command to search for
- * @return mixed A string with the full path or false if not found
- * @author Stig Bakken <ssb@php.net>
- */
- function which($program, $fallback = false)
- {
- // is_executable() is not available on windows
- if (OS_WINDOWS) {
- $pear_is_executable = 'is_file';
- } else {
- $pear_is_executable = 'is_executable';
- }
-
- // full path given
- if (basename($program) != $program) {
- return (@$pear_is_executable($program)) ? $program : $fallback;
- }
-
- // XXX FIXME honor safe mode
- $path_delim = OS_WINDOWS ? ';' : ':';
- $exe_suffixes = OS_WINDOWS ? array('.exe','.bat','.cmd','.com') : array('');
- $path_elements = explode($path_delim, getenv('PATH'));
- foreach ($exe_suffixes as $suff) {
- foreach ($path_elements as $dir) {
- $file = $dir . DIRECTORY_SEPARATOR . $program . $suff;
- if (@is_file($file) && @$pear_is_executable($file)) {
- return $file;
- }
- }
- }
- return $fallback;
- }
-
- /**
- * The "find" command
- *
- * Usage:
- *
- * System::find($dir);
- * System::find("$dir -type d");
- * System::find("$dir -type f");
- * System::find("$dir -name *.php");
- * System::find("$dir -name *.php -name *.htm*");
- * System::find("$dir -maxdepth 1");
- *
- * Params implmented:
- * $dir -> Start the search at this directory
- * -type d -> return only directories
- * -type f -> return only files
- * -maxdepth <n> -> max depth of recursion
- * -name <pattern> -> search pattern (bash style). Multiple -name param allowed
- *
- * @param mixed Either array or string with the command line
- * @return array Array of found files
- *
- */
- function find($args)
- {
- if (!is_array($args)) {
- $args = preg_split('/\s+/', $args, -1, PREG_SPLIT_NO_EMPTY);
- }
- $dir = array_shift($args);
- $patterns = array();
- $depth = 0;
- $do_files = $do_dirs = true;
- for ($i = 0; $i < count($args); $i++) {
- switch ($args[$i]) {
- case '-type':
- if (in_array($args[$i+1], array('d', 'f'))) {
- if ($args[$i+1] == 'd') {
- $do_files = false;
- } else {
- $do_dirs = false;
- }
- }
- $i++;
- break;
- case '-name':
- $patterns[] = "(" . preg_replace(array('/\./', '/\*/'),
- array('\.', '.*'),
- $args[$i+1])
- . ")";
- $i++;
- break;
- case '-maxdepth':
- $depth = $args[$i+1];
- break;
- }
- }
- $path = System::_dirToStruct($dir, $depth);
- if ($do_files && $do_dirs) {
- $files = array_merge($path['files'], $path['dirs']);
- } elseif ($do_dirs) {
- $files = $path['dirs'];
- } else {
- $files = $path['files'];
- }
- if (count($patterns)) {
- $patterns = implode('|', $patterns);
- $ret = array();
- for ($i = 0; $i < count($files); $i++) {
- if (preg_match("#^$patterns\$#", $files[$i])) {
- $ret[] = $files[$i];
- }
- }
- return $ret;
- }
- return $files;
- }
-}
-?>
+++ /dev/null
-<?php
-/**
- * Text_CAPTCHA - creates a CAPTCHA for Turing tests
- *
- * Class to create a Turing test for websites by
- * creating an image, ASCII art or something else
- * with some (obfuscated) characters
- *
- *
- * @package Text_CAPTCHA
- * @license PHP License, version 3.0
- * @author Christian Wenz <wenz@php.net>
- * @category Text
- */
-
-
-/**
- *
- * Require PEAR class for error handling.
- *
- */
-require_once 'PEAR.php';
-
-/**
- *
- * Require Text_Password class for generating the phrase.
- *
- */
-require_once 'Text/Password.php';
-
-/**
- * Text_CAPTCHA - creates a CAPTCHA for Turing tests
- *
- * Class to create a Turing test for websites by
- * creating an image, ASCII art or something else
- * with some (obfuscated) characters
- *
- * @package Text_CAPTCHA
- */
-
-/*
- // This is a simple example script
-
- <?php
- if (!function_exists('file_put_contents')) {
- function file_put_contents($filename, $content) {
- if (!($file = fopen($filename, 'w'))) {
- return false;
- }
- $n = fwrite($file, $content);
- fclose($file);
- return $n ? $n : false;
- }
- }
-
- // Start PHP session support
- session_start();
-
- $ok = false;
-
- $msg = 'Please enter the text in the image in the field below!';
-
- if ($_SERVER['REQUEST_METHOD'] == 'POST') {
-
- if (isset($_POST['phrase']) && is_string($_SESSION['phrase']) && isset($_SESSION['phrase']) &&
- strlen($_POST['phrase']) > 0 && strlen($_SESSION['phrase']) > 0 &&
- $_POST['phrase'] == $_SESSION['phrase']) {
- $msg = 'OK!';
- $ok = true;
- unset($_SESSION['phrase']);
- } else {
- $msg = 'Please try again!';
- }
-
- unlink(md5(session_id()) . '.png');
-
- }
-
- print "<p>$msg</p>";
-
- if (!$ok) {
-
- require_once 'Text/CAPTCHA.php';
-
- // Set CAPTCHA image options (font must exist!)
- $imageOptions = array(
- 'font_size' => 24,
- 'font_path' => './',
- 'font_file' => 'COUR.TTF',
- 'text_color' => '#DDFF99',
- 'lines_color' => '#CCEEDD',
- 'background_color' => '#555555'
- );
-
- // Set CAPTCHA options
- $options = array(
- 'width' => 200,
- 'height' => 80,
- 'output' => 'png',
- 'imageOptions' => $imageOptions
- );
-
- // Generate a new Text_CAPTCHA object, Image driver
- $c = Text_CAPTCHA::factory('Image');
- $retval = $c->init($options);
- if (PEAR::isError($retval)) {
- printf('Error initializing CAPTCHA: %s!',
- $retval->getMessage());
- exit;
- }
-
- // Get CAPTCHA secret passphrase
- $_SESSION['phrase'] = $c->getPhrase();
-
- // Get CAPTCHA image (as PNG)
- $png = $c->getCAPTCHA();
- if (PEAR::isError($png)) {
- printf('Error generating CAPTCHA: %s!',
- $png->getMessage());
- exit;
- }
- file_put_contents(md5(session_id()) . '.png', $png);
-
- echo '<form method="post">' .
- '<img src="' . md5(session_id()) . '.png?' . time() . '" />' .
- '<input type="text" name="phrase" />' .
- '<input type="submit" /></form>';
- }
- ?>
-*/
-
-class Text_CAPTCHA {
-
- /**
- * Version number
- *
- * @access private
- * @var string
- */
- var $_version = '0.3.1';
-
- /**
- * Phrase
- *
- * @access private
- * @var string
- */
- var $_phrase;
-
- /**
- * Create a new Text_CAPTCHA object
- *
- * @param string $driver name of driver class to initialize
- *
- * @return mixed a newly created Text_CAPTCHA object, or a PEAR
- * error object on error
- *
- * @see PEAR::isError()
- */
- function &factory($driver)
- {
- if ($driver == '') {
- return PEAR::raiseError('No CAPTCHA type specified ... aborting. You must call ::factory() with one parameter, the CAPTCHA type.', true);
- }
- $driver = basename($driver);
- include_once "Text/CAPTCHA/Driver/$driver.php";
-
- $classname = "Text_CAPTCHA_Driver_$driver";
- $obj =& new $classname;
- return $obj;
- }
-
- /**
- * Create random CAPTCHA phrase
- *
- * This method creates a random phrase, 8 characters long
- *
- * @access private
- */
- function _createPhrase()
- {
- $len = 8;
- $this->_phrase = Text_Password::create($len);
- }
-
- /**
- * Return secret CAPTCHA phrase
- *
- * This method returns the CAPTCHA phrase
- *
- * @access public
- * @return phrase secret phrase
- */
- function getPhrase()
- {
- return $this->_phrase;
- }
-
- /**
- * Sets secret CAPTCHA phrase
- *
- * This method sets the CAPTCHA phrase
- * (use null for a random phrase)
- *
- * @access public
- * @param string $phrase the (new) phrase
- * @void
- */
- function setPhrase($phrase = null)
- {
- if (!empty($phrase)) {
- $this->_phrase = $phrase;
- } else {
- $this->_createPhrase();
- }
- }
-
- /**
- * Place holder for the real init() method
- * used by extended classes to initialize CAPTCHA
- *
- * @access private
- * @return PEAR_Error
- */
- function init() {
- return PEAR::raiseError('CAPTCHA type not selected', true);
- }
-
- /**
- * Place holder for the real _createCAPTCHA() method
- * used by extended classes to generate CAPTCHA from phrase
- *
- * @access private
- * @return PEAR_Error
- */
- function _createCAPTCHA() {
- return PEAR::raiseError('CAPTCHA type not selected', true);
- }
-
- /**
- * Place holder for the real getCAPTCHA() method
- * used by extended classes to return the generated CAPTCHA
- * (as an image resource, as an ASCII text, ...)
- *
- * @access private
- * @return PEAR_Error
- */
- function getCAPTCHA() {
- return PEAR::raiseError('CAPTCHA type not selected', true);
- }
-
-}
-?>
+++ /dev/null
-<?php
-/**
- * Equation driver for Text_CAPTCHA.
- * Returns simple equations as string, e.g. "9 - 2"
- *
- * @author Christian Weiske <cweiske@php.net>
- * @author Christian Wenz <wenz@php.net>
- */
-require_once 'Text/CAPTCHA.php';
-
-class Text_CAPTCHA_Driver_Equation extends Text_CAPTCHA
-{
- /**
- * Operators that may be used in the equation.
- * Two numbers have to be filled in, and
- * %s is needed since number2text conversion
- * may be applied and strings filled in.
- *
- * @access protected
- * @var array
- */
- var $_operators = array(
- '%s * %s',
- '%s + %s',
- '%s - %s',
- 'min(%s, %s)',
- 'max(%s, %s)'
- );
-
- /**
- * The equation to solve.
- *
- * @access protected
- * @var string
- */
- var $_equation = null;
-
- /**
- * Minimal number to use in an equation.
- *
- * @access protected
- * @var int
- */
- var $_min = 1;
-
- /**
- * Maximum number to use in an equation.
- *
- * @access protected
- * @var int
- */
- var $_max = 10;
-
- /**
- * Whether numbers shall be converted to text
- *
- * @access protected
- * @var bool
- */
- var $_numbersToText = false;
-
- /**
- * Complexity of the generated equations.
- * 1 - simple ones such as "1 + 10"
- * 2 - harder ones such as "(3-2)*(min(5,6))"
- *
- * @access protected
- * @var int
- */
- var $_severity = 1;
-
- /**
- * Last error
- *
- * @access protected
- * @var PEAR_Error
- */
- var $_error = null;
-
-
- /**
- * Initialize the driver.
- *
- * @access public
- * @return true on success, PEAR_Error on error.
- */
- function init($options = array()) {
- if (isset($options['min'])) {
- $this->_min = (int)$options['min'];
- } else {
- $this->_min = 1;
- }
- if (isset($options['max'])) {
- $this->_max = (int)$options['max'];
- } else {
- $this->_max = 10;
- }
- if (isset($options['numbersToText'])) {
- $this->_numbersToText = (bool)$options['numbersToText'];
- } else {
- $this->_numbersToText = false;
- }
- if (isset($options['severity'])) {
- $this->_severity = (int)$options['severity'];
- } else {
- $this->_severity = 1;
- }
-
- if ($this->_numbersToText) {
- include_once 'Numbers/Words.php';
- if (!class_exists('Numbers_Words')) {
- $this->_error = PEAR::raiseError('Number_Words package required', true);
- return $this->_error;
- }
- }
-
- return $this->_createPhrase();
- }
-
- /**
- * Create random CAPTCHA equation.
- *
- * This method creates a random equation. The equation is
- * stored in $this->_equation, the solution in $this->_phrase.
- *
- * @access protected
- * @return mixed true on success, PEAR_Error on error
- */
- function _createPhrase()
- {
- switch ($this->_severity) {
- case 1:
- list($this->_equation, $this->_phrase) = $this->_createSimpleEquation();
- break;
-
- case 2:
- list($eq1, $sol1) = $this->_createSimpleEquation();
- list($eq2, $sol2) = $this->_createSimpleEquation();
- $op3 = $this->_operators[rand(0, count($this->_operators) - 1)];
- list($eq3, $this->_phrase) = $this->_solveSimpleEquation($sol1, $sol2, $op3);
- $this->_equation = sprintf($op3, '(' . $eq1 . ')', '(' . $eq2 . ')');
- break;
-
- default:
- $this->_error = PEAR::raiseError('Equation complexity of ' . $this->_severity . ' not supported', true);
- return $this->_error;
- }
- return true;
- }
-
- /**
- * Creates a simple equation of type (number operator number)
- *
- * @access protected
- * @return array Array with equation and solution
- */
- function _createSimpleEquation()
- {
- $one = rand($this->_min, $this->_max);
- $two = rand($this->_min, $this->_max);
- $operator = $this->_operators[rand(0, count($this->_operators) - 1)];
-
- return $this->_solveSimpleEquation($one, $two, $operator);
- }
-
- /**
- * Solves a simple equation with two given numbers
- * and one operator as defined in $this->_operators.
- *
- * Also converts the numbers to words if required.
- *
- * @access protected
- * @return array Array with equation and solution
- */
- function _solveSimpleEquation($one, $two, $operator)
- {
- $equation = sprintf($operator, $one, $two);
- $code = '$solution=' . $equation . ';';
- eval($code);
-
- if ($this->_numbersToText) {
- $equation = sprintf($operator, Numbers_Words::toWords($one), Numbers_Words::toWords($two));
- }
-
- return array($equation, $solution);
- }
-
- /**
- * Return the solution to the equation.
- *
- * This method returns the CAPTCHA phrase, which is
- * the solution to the equation.
- *
- * @access public
- * @return string secret phrase
- */
- function getPhrase()
- {
- return $this->_phrase;
- }
-
- /**
- * Creates the captcha. This method is a placeholder,
- * since the equation is created in _createPhrase()
- *
- * @access protected
- * @return PEAR_Error
- */
- function _createCAPTCHA() {
- //is already done in _createPhrase();
- }
-
- /**
- * Returns the CAPTCHA (as a string)
- *
- * @access public
- * @return string
- */
- function getCAPTCHA() {
- return $this->_equation;
- }
-
-}//class Text_CAPTCHA_Driver_TextEquation extends Text_CAPTCHA
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-/**
- *
- * Require Figlet class for rendering the text.
- *
- */
-require_once 'Text/CAPTCHA.php';
-require_once 'Text/Figlet.php';
-
-
-/**
- * Text_CAPTCHA_Driver_Figlet - Text_CAPTCHA driver Figlet based CAPTCHAs
- *
- * @license PHP License, version 3.0
- * @author Aaron Wormus <wormus@php.net>
- * @author Christian Wenz <wenz@php.net>
- * @todo define an obfuscation algorithm
- */
-
-class Text_CAPTCHA_Driver_Figlet extends Text_CAPTCHA
-{
- /**
- * Text_Figlet object
- *
- * @access private
- * @var resource
- */
- var $_fig;
-
- /**
- * Width of CAPTCHA
- *
- * @access private
- * @var int
- */
- var $_width;
-
- /**
- * Figlet output string
- *
- * @access private
- * @var string
- */
- var $_output_string;
-
- /**
- * Figlet font options
- *
- * @access private
- * @var array
- */
- var $_fonts = array();
-
- /**
- * Figlet font
- *
- * @access private
- * @var string
- */
- var $_font;
-
- /**
- * Figlet font
- *
- * @access private
- * @var array
- */
- var $_style = array();
-
- /**
- * Output Format
- *
- * @access private
- * @var string
- */
- var $_output;
-
- /**
- * Last error
- *
- * @access protected
- * @var PEAR_Error
- */
- var $_error = null;
-
- /**
- * init function
- *
- * Initializes the new Text_CAPTCHA_Driver_Figlet object and creates a GD image
- *
- * @param array $options CAPTCHA options
- * @access public
- * @return mixed true upon success, PEAR error otherwise
- */
- function init($options = array())
- {
- if (is_array($options)) {
- if (!empty($options['output'])){
- $this->_output = $options['output'];
- } else {
- $this->_output = 'html';
- }
-
- if (isset($options['width']) && is_int($options['width'])) {
- $this->_width = $options['width'];
- } else {
- $this->_width = 200;
- }
-
- if (!empty($options['length'])){
- $this->_length = $options['length'];
- } else {
- $this->_length = 6;
- }
-
- if (!isset($options['phrase']) || empty($options['phrase'])) {
- $this->_createPhrase($this->_length);
- } else {
- $this->_phrase = $options['phrase'];
- }
- }
-
- if (empty($options['options']) || !is_array($options['options'])){
- die;
- } else {
- if (!empty($options['options']['style']) && is_array($options['options']['style'])){
- $this->_style = $options['options']['style'];
- }
-
- if (empty($this->style['padding'])){
- $this->_style['padding'] = '5px';
- }
-
- if (!empty($options['options']['font_file'])){
- if (is_array($options['options']['font_file'])){
- $this->_font = $options['options']['font_file'][array_rand($options['options']['font_file'])];
- } else {
- $this->_font = $options['options']['font_file'];
- }
- }
- }
- }
-
- /**
- * Create random CAPTCHA phrase
- * This method creates a random phrase
- *
- * @access private
- */
- function _createPhrase()
- {
- $this->_phrase = Text_Password::create($this->_length);
- }
-
- /**
- * Create CAPTCHA image
- *
- * This method creates a CAPTCHA image
- *
- * @access private
- * @return void PEAR_Error on error
- */
- function _createCAPTCHA()
-
- {
- $this->_fig = new Text_Figlet();
-
- if (PEAR::isError($this->_fig->LoadFont($this->_font))){
- $this->_error = PEAR::raiseError('Error loading Text_Figlet font');
- return $this->_error;
- }
-
- $this->_output_string = $this->_fig->LineEcho($this->_phrase);
- }
-
- /**
- * Return CAPTCHA in the specified format
- *
- * This method returns the CAPTCHA depending on the output format
- *
- * @access public
- * @return mixed Formatted captcha or PEAR error
- */
- function getCAPTCHA()
- {
- $retval = $this->_createCAPTCHA();
- if (PEAR::isError($retval)) {
- return PEAR::raiseError($retval->getMessage());
- }
-
- switch ($this->_output) {
- case 'text':
- return $this->_output_string;
- break;
- case 'html':
- return $this->getCAPTCHAAsHTML();
- break;
- case 'javascript':
- return $this->getCAPTCHAAsJavascript();
- break;
- }
- }
-
- /**
- * Return CAPTCHA as HTML
- *
- * This method returns the CAPTCHA as HTML
- *
- * @access public
- * @return mixed HTML Figlet image or PEAR error
- */
- function getCAPTCHAAsHTML()
- {
- $retval = $this->_createCAPTCHA();
- if (PEAR::isError($retval)) {
- return PEAR::raiseError($retval->getMessage());
- }
-
- $charwidth = strpos($this->_output_string, "\n");
- $data = str_replace("\n", '<br />', $this->_output_string);
-
- $textsize = ($this->_width / $charwidth) * 1.4;
-
- $css_output = "";
- foreach ($this->_style as $key => $value){
- $css_output .= "$key: $value;";
- }
-
- $htmloutput = '<div style="font-family: courier;
- font-size: '.$textsize.'px;
- width:'.$this->_width.'px;
- text-align:center;">';
- $htmloutput .= '<div style="'.$css_output.'margin:0px;">
- <pre style="padding: 0px; margin: 0px;">'. $data. '</pre></div></div>';
-
- return $htmloutput;
- }
-
- /**
- * Return CAPTCHA as Javascript version of HTML
- *
- * This method returns the CAPTCHA as a Javascript string
- * I'm not exactly sure what the point of doing this would be.
- *
- * @access public
- * @return mixed javascript string or PEAR error
- */
- function getCAPTCHAAsJavascript()
- {
- $data = $this->getCAPTCHAAsHTML();
- if (PEAR::isError($data)) {
- return PEAR::raiseError($data->getMessage());
- }
-
- $obfus_data = rawurlencode($data);
-
- $javascript = "<script language=\"javascript\">
- document.write(unescape(\"$obfus_data.\" ) );
- </script>";
-
- return $javascript;
- }
-}
+++ /dev/null
-<?php
-/**
- *
- * Require Image_Text class for generating the text.
- *
- */
-require_once 'Text/CAPTCHA.php';
-require_once 'Image/Text.php';
-
-/**
- * Text_CAPTCHA_Driver_Image - Text_CAPTCHA driver graphical CAPTCHAs
- *
- * Class to create a graphical Turing test
- *
- *
- * @license PHP License, version 3.0
- * @author Christian Wenz <wenz@php.net>
- * @todo refine the obfuscation algorithm :-)
- * @todo learn how to use Image_Text better (or remove dependency)
- */
-
-class Text_CAPTCHA_Driver_Image extends Text_CAPTCHA
-{
-
- /**
- * Image object
- *
- * @access private
- * @var resource
- */
- var $_im;
-
- /**
- * Image_Text object
- *
- * @access private
- * @var resource
- */
- var $_imt;
-
- /**
- * Width of CAPTCHA
- *
- * @access private
- * @var int
- */
- var $_width;
-
- /**
- * Height of CAPTCHA
- *
- * @access private
- * @var int
- */
- var $_height;
-
- /**
- * CAPTCHA output format
- *
- * @access private
- * @var string
- */
- var $_output;
-
- /**
- * Further options (here: for Image_Text)
- *
- * @access private
- * @var array
- */
- var $_imageOptions = array(
- 'font_size' => 24,
- 'font_path' => './',
- 'font_file' => 'COUR.TTF',
- 'text_color' => '#000000',
- 'lines_color' => '#CACACA',
- 'background_color' => '#555555');
-
- /**
- * Whether the immage resource has been created
- *
- * @access private
- * @var boolean
- */
- var $_created = false;
-
- /**
- * Last error
- *
- * @access protected
- * @var PEAR_Error
- */
- var $_error = null;
-
- /**
- * init function
- *
- * Initializes the new Text_CAPTCHA_Driver_Image object and creates a GD image
- *
- * @param array $options CAPTCHA options
- * @access public
- * @return mixed true upon success, PEAR error otherwise
- */
- function init($options = array())
- {
- if (!is_array($options)) {
- // Compatibility mode ... in future versions, these two
- // lines of code will be used:
- // $this->_error = PEAR::raiseError('You need to provide a set of CAPTCHA options!');
- // return $this->_error;
- $o = array();
- $args = func_get_args();
- if (isset($args[0])) {
- $o['width'] = $args[0];
- }
- if (isset($args[1])) {
- $o['height'] = $args[1];
- }
- if (isset($args[2]) && $args[2] != null) {
- $o['phrase'] = $args[2];
- }
- if (isset($args[3]) && is_array($args[3])) {
- $o['imageOptions'] = $args[3];
- }
- $options = $o;
- }
- if (is_array($options)) {
- if (isset($options['width']) && is_int($options['width'])) {
- $this->_width = $options['width'];
- } else {
- $this->_width = 200;
- }
- if (isset($options['height']) && is_int($options['height'])) {
- $this->_height = $options['height'];
- } else {
- $this->_height = 80;
- }
- if (!isset($options['phrase']) || empty($options['phrase'])) {
- $this->_createPhrase();
- } else {
- $this->_phrase = $options['phrase'];
- }
- if (!isset($options['output']) || empty($options['output'])) {
- $this->_output = 'resource';
- } else {
- $this->_output = $options['output'];
- }
- if (isset($options['imageOptions']) && is_array($options['imageOptions']) && count($options['imageOptions']) > 0) {
- $this->_imageOptions = array_merge($this->_imageOptions, $options['imageOptions']);
- }
- return true;
- }
- }
-
- /**
- * Create random CAPTCHA phrase, Image edition (with size check)
- *
- * This method creates a random phrase, maximum 8 characters or width / 25, whatever is smaller
- *
- * @access private
- */
- function _createPhrase()
- {
- $len = intval(min(8, $this->_width / 25));
- $this->_phrase = Text_Password::create($len);
- $this->_created = false;
- }
-
- /**
- * Create CAPTCHA image
- *
- * This method creates a CAPTCHA image
- *
- * @access private
- * @return void PEAR_Error on error
- */
- function _createCAPTCHA()
- {
- if ($this->_error) {
- return $this->_error;
- }
- if ($this->_created) {
- return;
- }
- $options['canvas'] = array(
- 'width' => $this->_width,
- 'height' => $this->_height
- );
- $options['width'] = $this->_width - 20;
- $options['height'] = $this->_height - 20;
- $options['cx'] = ceil(($this->_width) / 2 + 10);
- $options['cy'] = ceil(($this->_height) / 2 + 10);
- $options['angle'] = rand(0, 30) - 15;
- $options['font_size'] = $this->_imageOptions['font_size'];
- $options['font_path'] = $this->_imageOptions['font_path'];
- $options['font_file'] = $this->_imageOptions['font_file'];
- $options['color'] = array($this->_imageOptions['text_color']);
- $options['background_color'] = $this->_imageOptions['background_color'];
- $options['max_lines'] = 1;
- $options['mode'] = 'auto';
- $this->_imt = new Image_Text(
- $this->_phrase,
- $options
- );
- if (PEAR::isError($e = $this->_imt->init())) {
- $this->_error = PEAR::raiseError(
- sprintf('Error initializing Image_Text (%s)',
- $e->getMessage()));
- return $this->_error;
- } else {
- $this->_created = true;
- }
- $this->_imt->measurize();
- $this->_imt->render();
- $this->_im =& $this->_imt->getImg();
- $colors = $this->_imt->_convertString2RGB($this->_imageOptions['lines_color']);
- $lines_color = imagecolorallocate($this->_im, $colors['r'], $colors['g'], $colors['b']);
- //some obfuscation
- for ($i = 0; $i < 3; $i++) {
- $x1 = rand(0, $this->_width - 1);
- $y1 = rand(0, round($this->_height / 10, 0));
- $x2 = rand(0, round($this->_width / 10, 0));
- $y2 = rand(0, $this->_height - 1);
- imageline($this->_im, $x1, $y1, $x2, $y2, $lines_color);
- $x1 = rand(0, $this->_width - 1);
- $y1 = $this->_height - rand(1, round($this->_height / 10, 0));
- $x2 = $this->_width - rand(1, round($this->_width / 10, 0));
- $y2 = rand(0, $this->_height - 1);
- imageline($this->_im, $x1, $y1, $x2, $y2, $lines_color);
- $cx = rand(0, $this->_width - 50) + 25;
- $cy = rand(0, $this->_height - 50) + 25;
- $w = rand(1, 24);
- imagearc($this->_im, $cx, $cy, $w, $w, 0, 360, $lines_color);
- }
- }
-
- /**
- * Return CAPTCHA as image resource
- *
- * This method returns the CAPTCHA depending on the output format
- *
- * @access public
- * @return mixed image resource or PEAR error
- */
- function getCAPTCHA()
- {
- $retval = $this->_createCAPTCHA();
- if (PEAR::isError($retval)) {
- return PEAR::raiseError($retval->getMessage());
- }
-
- if ($this->_output == 'gif' && !function_exists('imagegif')) {
- $this->_output = 'png';
- }
-
- switch ($this->_output) {
- case 'png':
- return $this->getCAPTCHAAsPNG();
- break;
- case 'jpg':
- case 'jpeg':
- return $this->getCAPTCHAAsJPEG();
- break;
- case 'gif':
- return $this->getCAPTCHAAsGIF();
- break;
- case 'resource':
- default:
- return $this->_im;
- }
- }
-
- /**
- * Return CAPTCHA as PNG
- *
- * This method returns the CAPTCHA as PNG
- *
- * @access public
- * @return mixed image contents or PEAR error
- */
- function getCAPTCHAAsPNG()
- {
- $retval = $this->_createCAPTCHA();
- if (PEAR::isError($retval)) {
- return PEAR::raiseError($retval->getMessage());
- }
-
- if (is_resource($this->_im)) {
- ob_start();
- imagepng($this->_im);
- $data = ob_get_contents();
- ob_end_clean();
- return $data;
- } else {
- $this->_error = PEAR::raiseError('Error creating CAPTCHA image (font missing?!)');
- return $this->_error;
- }
- }
-
- /**
- * Return CAPTCHA as JPEG
- *
- * This method returns the CAPTCHA as JPEG
- *
- * @access public
- * @return mixed image contents or PEAR error
- */
- function getCAPTCHAAsJPEG()
- {
- $retval = $this->_createCAPTCHA();
- if (PEAR::isError($retval)) {
- return PEAR::raiseError($retval->getMessage());
- }
-
- if (is_resource($this->_im)) {
- ob_start();
- imagejpeg($this->_im);
- $data = ob_get_contents();
- ob_end_clean();
- return $data;
- } else {
- $this->_error = PEAR::raiseError('Error creating CAPTCHA image (font missing?!)');
- return $this->_error;
- }
- }
-
- /**
- * Return CAPTCHA as GIF
- *
- * This method returns the CAPTCHA as GIF
- *
- * @access public
- * @return mixed image contents or PEAR error
- */
- function getCAPTCHAAsGIF()
- {
- $retval = $this->_createCAPTCHA();
- if (PEAR::isError($retval)) {
- return PEAR::raiseError($retval->getMessage());
- }
-
- if (is_resource($this->_im)) {
- ob_start();
- imagegif($this->_im);
- $data = ob_get_contents();
- ob_end_clean();
- return $data;
- } else {
- $this->_error = PEAR::raiseError('Error creating CAPTCHA image (font missing?!)');
- return $this->_error;
- }
- }
-
- /**
- * __wakeup method (PHP 5 only)
- */
- function __wakeup()
- {
- $this->_created = false;
- }
-}
+++ /dev/null
-<?php
-// {{{ Class Text_CAPTCHA_Driver_Numeral
-// +----------------------------------------------------------------------+
-// | PHP version 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2006 David Coallier |
-// | All rights reserved. |
-// +----------------------------------------------------------------------+
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | |
-// | Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution. |
-// | |
-// | Neither the name of David Coallier nor the names of his contributors |
-// | may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
-// | POSSIBILITY OF SUCH DAMAGE. |
-// +----------------------------------------------------------------------+
-// | Author: David Coallier <davidc@agoraproduction.com> |
-// +----------------------------------------------------------------------+
-//
-require_once 'Text/CAPTCHA.php';
-/**
- * Class used for numeral captchas
- *
- * This class is intended to be used to generate
- * numeral captchas as such as:
- * Example:
- * Give me the answer to "54 + 2" to prove that you are human.
- *
- * @author David Coallier <davidc@agoraproduction.com>
- * @author Christian Wenz <wenz@php.net>
- * @package Text_CAPTCHA
- * @category Text
- */
-class Text_CAPTCHA_Driver_Numeral extends Text_CAPTCHA
-{
- // {{{ Variables
- /**
- * Minimum range value
- *
- * This variable holds the minimum range value
- * default set to "1"
- *
- * @access private
- * @var integer $_minValue The minimum range value
- */
- var $_minValue = 1;
-
- /**
- * Maximum range value
- *
- * This variable holds the maximum range value
- * default set to "50"
- *
- * @access private
- * @var integer $_maxValue The maximum value of the number range
- */
- var $_maxValue = 50;
-
- /**
- * Operators
- *
- * The valid operators to use
- * in the numeral captcha. We could
- * use / and * but not yet.
- *
- * @access private
- * @var array $_operators The operations for the captcha
- */
- var $_operators = array('-', '+');
-
- /**
- * Operator to use
- *
- * This variable is basically the operation
- * that we're going to be using in the
- * numeral captcha we are about to generate.
- *
- * @access private
- * @var string $_operator The operation's operator
- */
- var $_operator = '';
-
- /**
- * Mathematical Operation
- *
- * This is the mathematical operation
- * that we are displaying to the user.
- *
- * @access private
- * @var string $_operation The math operation
- */
- var $_operation = '';
-
- /**
- * First number of the operation
- *
- * This variable holds the first number
- * of the numeral operation we are about
- * to generate.
- *
- * @access private
- * @var integer $_firstNumber The first number of the operation
- */
- var $_firstNumber = '';
-
- /**
- * Second Number of the operation
- *
- * This variable holds the value of the
- * second variable of the operation we are
- * about to generate for the captcha.
- *
- * @access private
- * @var integer $_secondNumber The second number of the operation
- */
- var $_secondNumber = '';
- // }}}
- // {{{ Constructor
- function init($options = array())
- {
- if (isset($options['minValue'])) {
- $this->_minValue = (int)$options['minValue'];
- }
- if (isset($options['maxValue'])) {
- $this->_maxValue = (int)$options['maxValue'];
- }
-
- $this->_createCAPTCHA();
- }
- // }}}
- // {{{ private function _createCAPTCHA
- /**
- * Create the CAPTCHA (the numeral expressio)
- *
- * This function determines a random numeral expression
- * and set the associated class properties
- *
- * @access private
- */
- function _createCAPTCHA()
- {
- $this->_generateFirstNumber();
- $this->_generateSecondNumber();
- $this->_generateOperator();
- $this->_generateOperation();
- }
- // }}}
- // {{{ private function _setRangeMinimum
- /**
- * Set Range Minimum value
- *
- * This function give the developer the ability
- * to set the range minimum value so the operations
- * can be bigger, smaller, etc.
- *
- * @access private
- * @param integer $minValue The minimum value
- */
- function _setRangeMinimum($minValue = 1)
- {
- $this->minValue = (int)$minValue;
- }
- // }}}
- // {{{ private function _generateFirstNumber
- /**
- * Sets the first number
- *
- * This function sets the first number
- * of the operation by calling the _generateNumber
- * function that generates a random number.
- *
- * @access private
- * @see $this->_firstNumber, $this->_generateNumber
- */
- function _generateFirstNumber()
- {
- $this->_setFirstNumber($this->_generateNumber());
- }
- // }}}
- // {{{ private function generateSecondNumber
- /**
- * Sets second number
- *
- * This function sets the second number of the
- * operation by calling _generateNumber()
- *
- * @access private
- * @see $this->_secondNumber, $this->_generateNumber()
- */
- function _generateSecondNumber()
- {
- $this->_setSecondNumber($this->_generateNumber());
- }
- // }}}
- // {{{ private function generateOperator
- /**
- * Sets the operation operator
- *
- * This function sets the operation operator by
- * getting the array value of an array_rand() of
- * the $this->_operators() array.
- *
- * @access private
- * @see $this->_operators, $this->_operator
- */
- function _generateOperator()
- {
- $this->_operator = $this->_operators[array_rand($this->_operators)];
- }
- // }}}
- // {{{ private function setAnswer
- /**
- * Sets the answer value
- *
- * This function will accept the parameters which is
- * basically the result of the function we have done
- * and it will set $this->answer with it.
- *
- * @access private
- * @param integer $phraseValue The answer value
- * @see $this->_phrase
- */
- function _setPhrase($phraseValue)
- {
- $this->_phrase = $phraseValue;
- }
- // }}}
- // {{{ private function setFirstNumber
- /**
- * Set First number
- *
- * This function sets the first number
- * to the value passed to the function
- *
- * @access private
- * @param integer $value The first number value.
- */
- function _setFirstNumber($value)
- {
- $this->_firstNumber = (int)$value;
- }
- // }}}
- // {{{ private function setSecondNumber
- /**
- * Sets the second number
- *
- * This function sets the second number
- * with the value passed to it.
- *
- * @access private
- * @param integer $value The second number new value.
- */
- function _setSecondNumber($value)
- {
- $this->_secondNumber = (int)$value;
- }
- // }}}
- // {{{ private function setOperation
- /**
- * Set operation
- *
- * This variable sets the operation variable
- * by taking the firstNumber, secondNumber and operator
- *
- * @access private
- * @see $this->_operation
- */
- function _setOperation()
- {
- $this->_operation = $this->_getFirstNumber() . ' ' .
- $this->_operator . ' ' .
- $this->_getSecondNumber();
- }
- // }}}
- // {{{ private function _generateNumber
- /**
- * Generate a number
- *
- * This function takes the parameters that are in
- * the $this->_maxValue and $this->_minValue and get
- * the random number from them using mt_rand()
- *
- * @access private
- * @return integer Random value between _minValue and _maxValue
- */
- function _generateNumber()
- {
- return mt_rand($this->_minValue, $this->_maxValue);
- }
- // }}}
- // {{{ private function _doAdd
- /**
- * Adds values
- *
- * This function will add the firstNumber and the
- * secondNumber value and then call setAnswer to
- * set the answer value.
- *
- * @access private
- * @see $this->_firstNumber, $this->_secondNumber, $this->_setAnswer()
- */
- function _doAdd()
- {
- $phrase = $this->_getFirstNumber() + $this->_getSecondNumber();
- $this->_setPhrase($phrase);
- }
- // }}}
- // {{{ private function _doSubstract
- /**
- * Does a substract on the values
- *
- * This function executes a substraction on the firstNumber
- * and the secondNumber to then call $this->setAnswer to set
- * the answer value.
- *
- * If the firstnumber value is smaller than the secondnumber value
- * then we regenerate the first number and regenerate the operation.
- *
- * @access private
- * @see $this->_firstNumber, $this->_secondNumber, $this->_setAnswer()
- */
- function _doSubstract()
- {
- $first = $this->_getFirstNumber();
- $second = $this->_getSecondNumber();
-
- /**
- * Check if firstNumber is smaller than secondNumber
- */
- if ($first < $second) {
- $this->_setFirstNumber($second);
- $this->_setSecondNumber($first);
- $this->_setOperation();
- }
-
- $phrase = $this->_getFirstNumber() - $this->_getSecondNumber();
- $this->_setPhrase($phrase);
- }
- // }}}
- // {{{ private function _generateOperation
- /**
- * Generate the operation
- *
- * This function will call the _setOperation() function
- * to set the operation string that will be called
- * to display the operation, and call the function necessary
- * depending on which operation is set by this->operator.
- *
- * @access private
- * @see $this->_setOperation(), $this->_operator
- */
- function _generateOperation()
- {
- $this->_setOperation();
-
- switch ($this->_operator) {
- case '+':
- $this->_doAdd();
- break;
- case '-':
- $this->_doSubstract();
- break;
- default:
- $this->_doAdd();
- break;
- }
- }
- // }}}
- // {{{ public function _getFirstNumber
- /**
- * Get the first number
- *
- * This function will get the first number
- * value from $this->_firstNumber
- *
- * @access public
- * @return integer $this->_firstNumber The firstNumber
- */
- function _getFirstNumber()
- {
- return $this->_firstNumber;
- }
- // }}}
- // {{{ public function _getSecondNumber
- /**
- * Get the second number value
- *
- * This function will return the second number value
- *
- * @access public
- * @return integer $this->_secondNumber The second number
- */
- function _getSecondNumber()
- {
- return $this->_secondNumber;
- }
- // }}}
- // {{{ public function getCAPTCHA
- /**
- * Get operation
- *
- * This function will get the operation
- * string from $this->_operation
- *
- * @access public
- * @return string The operation String
- */
- function getCAPTCHA()
- {
- return $this->_operation;
- }
-}
-// }}}
-?>
+++ /dev/null
-<?php
-/**
- * Text_CAPTCHA_Driver_Word - Text_CAPTCHA driver word CAPTCHAs
- *
- * Class to create a textual Turing test
- *
- *
- * @license PHP License, version 3.0
- * @author Tobias Schlitt <schlitt@php.net>
- * @author Christian Wenz <wenz@php.net>
- */
-
-/**
- *
- * Require Numbers_Words class for generating the text.
- *
- */
-require_once 'Text/CAPTCHA.php';
-require_once 'Numbers/Words.php';
-
-class Text_CAPTCHA_Driver_Word extends Text_CAPTCHA
-{
-
- /**
- * Phrase length
- *
- * This variable holds the length of the Word
- *
- * @access private
- */
- var $_length;
-
- /**
- * Numbers_Words mode
- *
- * This variable holds the mode for Numbers_Words
- *
- * @access private
- */
- var $_mode;
-
- /**
- * Locale
- *
- * This variable holds the locale for Numbers_Words
- *
- * @access private
- */
- var $_locale;
-
- /**
- * init function
- *
- * Initializes the new Text_CAPTCHA_Driver_Word object
- *
- * @param array $options CAPTCHA options with these keys:
- * phrase The "secret word" of the CAPTCHA
- * length The number of characters in the phrase
- * locale The locale for Numbers_Words
- * mode The mode for Numbers_Words
- * @access public
- */
- function init($options = array())
- {
- if (isset($options['length']) && is_int($options['length'])) {
- $this->_length = $options['length'];
- } else {
- $this->_length = 4;
- }
- if (isset($options['phrase']) && !empty($options['phrase'])) {
- $this->_phrase = (string)(int)$options['phrase'];
- } else {
- $this->_createPhrase();
- }
- if (isset($options['mode']) && !empty($options['mode'])) {
- $this->_mode = $options['mode'];
- } else {
- $this->_mode = 'single';
- }
- if (isset($options['locale']) && !empty($options['locale'])) {
- $this->_locale = $options['locale'];
- } else {
- $this->_locale = 'en_US';
- }
- }
-
- /**
- * Create random CAPTCHA phrase, "Word edition" (numbers only)
- *
- * This method creates a random phrase
- *
- * @access private
- */
- function _createPhrase()
- {
- $this->_phrase = (string)Text_Password::create($this->_length, 'unpronounceable', 'numeric');
- }
-
- /**
- * Return CAPTCHA as a string
- *
- * This method returns the CAPTCHA as string
- *
- * @access public
- * @return text string
- */
- function getCAPTCHA()
- {
- $res = '';
- if ($this->_mode == 'single') {
- for ($i = 0; $i < strlen($this->_phrase); $i++) {
- $res .= ' '.Numbers_Words::toWords($this->_phrase{$i}, $this->_locale);
- }
- } else {
- $res = Numbers_Words::toWords($this->_phrase, $this->_locale);
- }
- return $res;
- }
-}
-?>
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2006 Pierre-Alain Joye,Tomas V.V.Cox, Amir Saied |
-// +----------------------------------------------------------------------+
-// | This source file is subject to the New BSD license, That is bundled |
-// | with this package in the file LICENSE, and is available through |
-// | the world-wide-web at |
-// | http://www.opensource.org/licenses/bsd-license.php |
-// | If you did not receive a copy of the new BSDlicense and are unable |
-// | to obtain it through the world-wide-web, please send a note to |
-// | pajoye@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Tomas V.V.Cox <cox@idecnet.com> |
-// | Pierre-Alain Joye <pajoye@php.net> |
-// | Amir Mohammad Saied <amir@php.net> |
-// +----------------------------------------------------------------------+
-//
-/**
- * Validation class
- *
- * Package to validate various datas. It includes :
- * - numbers (min/max, decimal or not)
- * - email (syntax, domain check)
- * - string (predifined type alpha upper and/or lowercase, numeric,...)
- * - date (min, max, rfc822 compliant)
- * - uri (RFC2396)
- * - possibility valid multiple data with a single method call (::multiple)
- *
- * @category Validate
- * @package Validate
- * @author Tomas V.V.Cox <cox@idecnet.com>
- * @author Pierre-Alain Joye <pajoye@php.net>
- * @author Amir Mohammad Saied <amir@php.net>
- * @copyright 1997-2006 Pierre-Alain Joye,Tomas V.V.Cox,Amir Mohammad Saied
- * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: Validate.php,v 1.1.1.1 2008/04/28 15:20:46 jamie Exp $
- * @link http://pear.php.net/package/Validate
- */
-
-/**
- * Methods for common data validations
- */
-define('VALIDATE_NUM', '0-9');
-define('VALIDATE_SPACE', '\s');
-define('VALIDATE_ALPHA_LOWER', 'a-z');
-define('VALIDATE_ALPHA_UPPER', 'A-Z');
-define('VALIDATE_ALPHA', VALIDATE_ALPHA_LOWER . VALIDATE_ALPHA_UPPER);
-define('VALIDATE_EALPHA_LOWER', VALIDATE_ALPHA_LOWER . 'áéíóúýàèìòùäëïöüÿâêîôûãñõ¨åæç½ðøþß');
-define('VALIDATE_EALPHA_UPPER', VALIDATE_ALPHA_UPPER . 'ÁÉÍÓÚÝÀÈÌÒÙÄËÏÖܾÂÊÎÔÛÃÑÕ¦ÅÆÇ¼ÐØÞ');
-define('VALIDATE_EALPHA', VALIDATE_EALPHA_LOWER . VALIDATE_EALPHA_UPPER);
-define('VALIDATE_PUNCTUATION', VALIDATE_SPACE . '\.,;\:&"\'\?\!\(\)');
-define('VALIDATE_NAME', VALIDATE_EALPHA . VALIDATE_SPACE . "'" . "-");
-define('VALIDATE_STREET', VALIDATE_NUM . VALIDATE_NAME . "/\\ºª\.");
-
-define('VALIDATE_ITLD_EMAILS', 1);
-define('VALIDATE_GTLD_EMAILS', 2);
-define('VALIDATE_CCTLD_EMAILS', 4);
-define('VALIDATE_ALL_EMAILS', 8);
-
-/**
- * Validation class
- *
- * Package to validate various datas. It includes :
- * - numbers (min/max, decimal or not)
- * - email (syntax, domain check)
- * - string (predifined type alpha upper and/or lowercase, numeric,...)
- * - date (min, max)
- * - uri (RFC2396)
- * - possibility valid multiple data with a single method call (::multiple)
- *
- * @category Validate
- * @package Validate
- * @author Tomas V.V.Cox <cox@idecnet.com>
- * @author Pierre-Alain Joye <pajoye@php.net>
- * @author Amir Mohammad Saied <amir@php.net>
- * @copyright 1997-2006 Pierre-Alain Joye,Tomas V.V.Cox,Amir Mohammad Saied
- * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
- * @version Release: @package_version@
- * @link http://pear.php.net/package/Validate
- */
-class Validate
-{
- /**
- * International Top-Level Domain
- *
- * This is an array of the known international
- * top-level domain names.
- *
- * @access protected
- * @var array $_iTld (International top-level domains)
- */
- var $_itld = array(
- 'arpa',
- 'root',
- );
-
- /**
- * Generic top-level domain
- *
- * This is an array of the official
- * generic top-level domains.
- *
- * @access protected
- * @var array $_gTld (Generic top-level domains)
- */
- var $_gtld = array(
- 'aero',
- 'biz',
- 'cat',
- 'com',
- 'coop',
- 'edu',
- 'gov',
- 'info',
- 'int',
- 'jobs',
- 'mil',
- 'mobi',
- 'museum',
- 'name',
- 'net',
- 'org',
- 'pro',
- 'travel',
- 'asia',
- 'post',
- 'tel',
- 'geo',
- );
-
- /**
- * Country code top-level domains
- *
- * This is an array of the official country
- * codes top-level domains
- *
- * @access protected
- * @var array $_ccTld (Country Code Top-Level Domain)
- */
- var $_cctld = array(
- 'ac',
- 'ad','ae','af','ag',
- 'ai','al','am','an',
- 'ao','aq','ar','as',
- 'at','au','aw','ax',
- 'az','ba','bb','bd',
- 'be','bf','bg','bh',
- 'bi','bj','bm','bn',
- 'bo','br','bs','bt',
- 'bu','bv','bw','by',
- 'bz','ca','cc','cd',
- 'cf','cg','ch','ci',
- 'ck','cl','cm','cn',
- 'co','cr','cs','cu',
- 'cv','cx','cy','cz',
- 'de','dj','dk','dm',
- 'do','dz','ec','ee',
- 'eg','eh','er','es',
- 'et','eu','fi','fj',
- 'fk','fm','fo','fr',
- 'ga','gb','gd','ge',
- 'gf','gg','gh','gi',
- 'gl','gm','gn','gp',
- 'gq','gr','gs','gt',
- 'gu','gw','gy','hk',
- 'hm','hn','hr','ht',
- 'hu','id','ie','il',
- 'im','in','io','iq',
- 'ir','is','it','je',
- 'jm','jo','jp','ke',
- 'kg','kh','ki','km',
- 'kn','kp','kr','kw',
- 'ky','kz','la','lb',
- 'lc','li','lk','lr',
- 'ls','lt','lu','lv',
- 'ly','ma','mc','md',
- 'me','mg','mh','mk',
- 'ml','mm','mn','mo',
- 'mp','mq','mr','ms',
- 'mt','mu','mv','mw',
- 'mx','my','mz','na',
- 'nc','ne','nf','ng',
- 'ni','nl','no','np',
- 'nr','nu','nz','om',
- 'pa','pe','pf','pg',
- 'ph','pk','pl','pm',
- 'pn','pr','ps','pt',
- 'pw','py','qa','re',
- 'ro','rs','ru','rw',
- 'sa','sb','sc','sd',
- 'se','sg','sh','si',
- 'sj','sk','sl','sm',
- 'sn','so','sr','st',
- 'su','sv','sy','sz',
- 'tc','td','tf','tg',
- 'th','tj','tk','tl',
- 'tm','tn','to','tp',
- 'tr','tt','tv','tw',
- 'tz','ua','ug','uk',
- 'us','uy','uz','va',
- 'vc','ve','vg','vi',
- 'vn','vu','wf','ws',
- 'ye','yt','yu','za',
- 'zm','zw',
- );
-
-
- /**
- * Validate a number
- *
- * @param string $number Number to validate
- * @param array $options array where:
- * 'decimal' is the decimal char or false when decimal not allowed
- * i.e. ',.' to allow both ',' and '.'
- * 'dec_prec' Number of allowed decimals
- * 'min' minimum value
- * 'max' maximum value
- *
- * @return boolean true if valid number, false if not
- *
- * @access public
- */
- function number($number, $options = array())
- {
- $decimal = $dec_prec = $min = $max = null;
- if (is_array($options)) {
- extract($options);
- }
-
- $dec_prec = $dec_prec ? "{1,$dec_prec}" : '+';
- $dec_regex = $decimal ? "[$decimal][0-9]$dec_prec" : '';
-
- if (!preg_match("|^[-+]?\s*[0-9]+($dec_regex)?\$|", $number)) {
- return false;
- }
-
- if ($decimal != '.') {
- $number = strtr($number, $decimal, '.');
- }
-
- $number = (float)str_replace(' ', '', $number);
- if ($min !== null && $min > $number) {
- return false;
- }
-
- if ($max !== null && $max < $number) {
- return false;
- }
- return true;
- }
-
- /**
- * Converting a string to UTF-7 (RFC 2152)
- *
- * @param $string string to be converted
- *
- * @return string converted string
- *
- * @access private
- */
- function __stringToUtf7($string) {
- $return = '';
- $utf7 = array(
- 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
- 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
- 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
- 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
- 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2',
- '3', '4', '5', '6', '7', '8', '9', '+', ','
- );
-
- $state = 0;
- if (!empty($string)) {
- $i = 0;
- while ($i <= strlen($string)) {
- $char = substr($string, $i, 1);
- if ($state == 0) {
- if ((ord($char) >= 0x7F) || (ord($char) <= 0x1F)) {
- if ($char) {
- $return .= '&';
- }
- $state = 1;
- } elseif ($char == '&') {
- $return .= '&-';
- } else {
- $return .= $char;
- }
- } elseif (($i == strlen($string) ||
- !((ord($char) >= 0x7F)) || (ord($char) <= 0x1F))) {
- if ($state != 1) {
- if (ord($char) > 64) {
- $return .= '';
- } else {
- $return .= $utf7[ord($char)];
- }
- }
- $return .= '-';
- $state = 0;
- } else {
- switch($state) {
- case 1:
- $return .= $utf7[ord($char) >> 2];
- $residue = (ord($char) & 0x03) << 4;
- $state = 2;
- break;
- case 2:
- $return .= $utf7[$residue | (ord($char) >> 4)];
- $residue = (ord($char) & 0x0F) << 2;
- $state = 3;
- break;
- case 3:
- $return .= $utf7[$residue | (ord($char) >> 6)];
- $return .= $utf7[ord($char) & 0x3F];
- $state = 1;
- break;
- }
- }
- $i++;
- }
- return $return;
- }
- return '';
- }
-
- /**
- * Validate an email according to full RFC822 (inclusive human readable part)
- *
- * @param string $email email to validate,
- * will return the address for optional dns validation
- * @param array $options email() options
- *
- * @return boolean true if valid email, false if not
- *
- * @access private
- */
- function __emailRFC822(&$email, &$options)
- {
- if (Validate::__stringToUtf7($email) != $email) {
- return false;
- }
- static $address = null;
- static $uncomment = null;
- if (!$address) {
- // atom = 1*<any CHAR except specials, SPACE and CTLs>
- $atom = '[^][()<>@,;:\\".\s\000-\037\177-\377]+\s*';
- // qtext = <any CHAR excepting <">, ; => may be folded
- // "\" & CR, and including linear-white-space>
- $qtext = '[^"\\\\\r]';
- // quoted-pair = "\" CHAR ; may quote any char
- $quoted_pair = '\\\\.';
- // quoted-string = <"> *(qtext/quoted-pair) <">; Regular qtext or
- // ; quoted chars.
- $quoted_string = '"(?:' . $qtext . '|' . $quoted_pair . ')*"\s*';
- // word = atom / quoted-string
- $word = '(?:' . $atom . '|' . $quoted_string . ')';
- // local-part = word *("." word) ; uninterpreted
- // ; case-preserved
- $local_part = $word . '(?:\.\s*' . $word . ')*';
- // dtext = <any CHAR excluding "[", ; => may be folded
- // "]", "\" & CR, & including linear-white-space>
- $dtext = '[^][\\\\\r]';
- // domain-literal = "[" *(dtext / quoted-pair) "]"
- $domain_literal = '\[(?:' . $dtext . '|' . $quoted_pair . ')*\]\s*';
- // sub-domain = domain-ref / domain-literal
- // domain-ref = atom ; symbolic reference
- $sub_domain = '(?:' . $atom . '|' . $domain_literal . ')';
- // domain = sub-domain *("." sub-domain)
- $domain = $sub_domain . '(?:\.\s*' . $sub_domain . ')*';
- // addr-spec = local-part "@" domain ; global address
- $addr_spec = $local_part . '@\s*' . $domain;
- // route = 1#("@" domain) ":" ; path-relative
- $route = '@' . $domain . '(?:,@\s*' . $domain . ')*:\s*';
- // route-addr = "<" [route] addr-spec ">"
- $route_addr = '<\s*(?:' . $route . ')?' . $addr_spec . '>\s*';
- // phrase = 1*word ; Sequence of words
- $phrase = $word . '+';
- // mailbox = addr-spec ; simple address
- // / phrase route-addr ; name & addr-spec
- $mailbox = '(?:' . $addr_spec . '|' . $phrase . $route_addr . ')';
- // group = phrase ":" [#mailbox] ";"
- $group = $phrase . ':\s*(?:' . $mailbox . '(?:,\s*' . $mailbox . ')*)?;\s*';
- // address = mailbox ; one addressee
- // / group ; named list
- $address = '/^\s*(?:' . $mailbox . '|' . $group . ')$/';
- $uncomment =
- '/((?:(?:\\\\"|[^("])*(?:' . $quoted_string .
- ')?)*)((?<!\\\\)\((?:(?2)|.)*?(?<!\\\\)\))/';
- }
- // strip comments
- $email = preg_replace($uncomment, '$1 ', $email);
- return preg_match($address, $email);
- }
-
- /**
- * Full TLD Validation function
- *
- * This function is used to make a much more proficient validation
- * against all types of official domain names.
- *
- * @access protected
- * @param string $email The email address to check.
- * @param array $options The options for validation
- * @return bool True if validating succeeds
- */
- function _fullTLDValidation($email, $options)
- {
- $validate = array();
-
- switch ($options) {
- /** 1 */
- case VALIDATE_ITLD_EMAILS:
- array_push($validate, 'itld');
- break;
-
- /** 2 */
- case VALIDATE_GTLD_EMAILS:
- array_push($validate, 'gtld');
- break;
-
- /** 3 */
- case VALIDATE_ITLD_EMAILS | VALIDATE_GTLD_EMAILS:
- array_push($validate, 'itld');
- array_push($validate, 'gtld');
- break;
-
- /** 4 */
- case VALIDATE_CCTLD_EMAILS:
- array_push($validate, 'cctld');
- break;
-
- /** 5 */
- case VALIDATE_CCTLD_EMAILS | VALIDATE_ITLD_EMAILS:
- array_push($validate, 'cctld');
- array_push($validate, 'itld');
- break;
-
- /** 6 */
- case VALIDATE_CCTLD_EMAILS ^ VALIDATE_ITLD_EMAILS:
- array_push($validate, 'cctld');
- array_push($validate, 'itld');
- break;
-
- /** 7 - 8 */
- case VALIDATE_CCTLD_EMAILS | VALIDATE_ITLD_EMAILS | VALIDATE_GTLD_EMAILS:
- case VALIDATE_ALL_EMAILS:
- array_push($validate, 'cctld');
- array_push($validate, 'itld');
- array_push($validate, 'gtld');
- break;
- }
-
- /**
- * Debugging still, not implemented but code is somewhat here.
- */
-
- $self = new Validate;
-
- $toValidate = array();
-
- foreach ($validate as $valid) {
- $tmpVar = '_' . (string)$valid;
- $toValidate[$valid] = $self->{$tmpVar};
- }
-
- $e = $self->executeFullEmailValidation($email, $toValidate);
-
- return $e;
- }
- // {{{ protected function executeFullEmailValidation
- /**
- * Execute the validation
- *
- * This function will execute the full email vs tld
- * validation using an array of tlds passed to it.
- *
- * @access public
- * @param string $email The email to validate.
- * @param array $arrayOfTLDs The array of the TLDs to validate
- * @return true or false (Depending on if it validates or if it does not)
- */
- function executeFullEmailValidation($email, $arrayOfTLDs)
- {
- $emailEnding = explode('.', $email);
- $emailEnding = $emailEnding[count($emailEnding)-1];
-
- foreach ($arrayOfTLDs as $validator => $keys) {
- if (in_array($emailEnding, $keys)) {
- return true;
- }
- }
- return false;
- }
- // }}}
-
- /**
- * Validate an email
- *
- * @param string $email email to validate
- * @param mixed boolean (BC) $check_domain Check or not if the domain exists
- * array $options associative array of options
- * 'check_domain' boolean Check or not if the domain exists
- * 'use_rfc822' boolean Apply the full RFC822 grammar
- *
- * @return boolean true if valid email, false if not
- *
- * @access public
- */
- function email($email, $options = null)
- {
- $check_domain = false;
- $use_rfc822 = false;
- if (is_bool($options)) {
- $check_domain = $options;
- } elseif (is_array($options)) {
- extract($options);
- }
-
- /**
- * @todo Fix bug here.. even if it passes this, it won't be passing
- * The regular expression below
- */
- if (isset($fullTLDValidation)) {
- $valid = Validate::_fullTLDValidation($email, $fullTLDValidation);
-
- if (!$valid) {
- return false;
- }
- }
-
- // the base regexp for address
- $regex = '&^(?: # recipient:
- ("\s*(?:[^"\f\n\r\t\v\b\s]+\s*)+")| #1 quoted name
- ([-\w!\#\$%\&\'*+~/^`|{}]+(?:\.[-\w!\#\$%\&\'*+~/^`|{}]+)*)) #2 OR dot-atom
- @(((\[)? #3 domain, 4 as IPv4, 5 optionally bracketed
- (?:(?:(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:[0-1]?[0-9]?[0-9]))\.){3}
- (?:(?:25[0-5])|(?:2[0-4][0-9])|(?:[0-1]?[0-9]?[0-9]))))(?(5)\])|
- ((?:[a-z0-9](?:[-a-z0-9]*[a-z0-9])?\.)*[a-z0-9](?:[-a-z0-9]*[a-z0-9])?) #6 domain as hostname
- \.((?:([^- ])[-a-z]*[-a-z]))) #7 TLD
- $&xi';
-
- if ($use_rfc822? Validate::__emailRFC822($email, $options) :
- preg_match($regex, $email)) {
- if ($check_domain && function_exists('checkdnsrr')) {
- list (, $domain) = explode('@', $email);
- if (checkdnsrr($domain, 'MX') || checkdnsrr($domain, 'A')) {
- return true;
- }
- return false;
- }
- return true;
- }
- return false;
- }
-
- /**
- * Validate a string using the given format 'format'
- *
- * @param string $string String to validate
- * @param array $options Options array where:
- * 'format' is the format of the string
- * Ex: VALIDATE_NUM . VALIDATE_ALPHA (see constants)
- * 'min_length' minimum length
- * 'max_length' maximum length
- *
- * @return boolean true if valid string, false if not
- *
- * @access public
- */
- function string($string, $options)
- {
- $format = null;
- $min_length = $max_length = 0;
- if (is_array($options)) {
- extract($options);
- }
- if ($format && !preg_match("|^[$format]*\$|s", $string)) {
- return false;
- }
- if ($min_length && strlen($string) < $min_length) {
- return false;
- }
- if ($max_length && strlen($string) > $max_length) {
- return false;
- }
- return true;
- }
-
- /**
- * Validate an URI (RFC2396)
- * This function will validate 'foobarstring' by default, to get it to validate
- * only http, https, ftp and such you have to pass it in the allowed_schemes
- * option, like this:
- * <code>
- * $options = array('allowed_schemes' => array('http', 'https', 'ftp'))
- * var_dump(Validate::uri('http://www.example.org', $options));
- * </code>
- *
- * NOTE 1: The rfc2396 normally allows middle '-' in the top domain
- * e.g. http://example.co-m should be valid
- * However, as '-' is not used in any known TLD, it is invalid
- * NOTE 2: As double shlashes // are allowed in the path part, only full URIs
- * including an authority can be valid, no relative URIs
- * the // are mandatory (optionally preceeded by the 'sheme:' )
- * NOTE 3: the full complience to rfc2396 is not achieved by default
- * the characters ';/?:@$,' will not be accepted in the query part
- * if not urlencoded, refer to the option "strict'"
- *
- * @param string $url URI to validate
- * @param array $options Options used by the validation method.
- * key => type
- * 'domain_check' => boolean
- * Whether to check the DNS entry or not
- * 'allowed_schemes' => array, list of protocols
- * List of allowed schemes ('http',
- * 'ssh+svn', 'mms')
- * 'strict' => string the refused chars
- * in query and fragment parts
- * default: ';/?:@$,'
- * empty: accept all rfc2396 foreseen chars
- *
- * @return boolean true if valid uri, false if not
- *
- * @access public
- */
- function uri($url, $options = null)
- {
- $strict = ';/?:@$,';
- $domain_check = false;
- $allowed_schemes = null;
- if (is_array($options)) {
- extract($options);
- }
- if (preg_match(
- '&^(?:([a-z][-+.a-z0-9]*):)? # 1. scheme
- (?:// # authority start
- (?:((?:%[0-9a-f]{2}|[-a-z0-9_.!~*\'();:\&=+$,])*)@)? # 2. authority-userinfo
- (?:((?:[a-z0-9](?:[-a-z0-9]*[a-z0-9])?\.)*[a-z](?:[a-z0-9]+)?\.?) # 3. authority-hostname OR
- |([0-9]{1,3}(?:\.[0-9]{1,3}){3})) # 4. authority-ipv4
- (?::([0-9]*))?) # 5. authority-port
- ((?:/(?:%[0-9a-f]{2}|[-a-z0-9_.!~*\'():@\&=+$,;])*)*/?)? # 6. path
- (?:\?([^#]*))? # 7. query
- (?:\#((?:%[0-9a-f]{2}|[-a-z0-9_.!~*\'();/?:@\&=+$,])*))? # 8. fragment
- $&xi', $url, $matches)) {
- $scheme = isset($matches[1]) ? $matches[1] : '';
- $authority = isset($matches[3]) ? $matches[3] : '' ;
- if (is_array($allowed_schemes) &&
- !in_array($scheme,$allowed_schemes)
- ) {
- return false;
- }
- if (!empty($matches[4])) {
- $parts = explode('.', $matches[4]);
- foreach ($parts as $part) {
- if ($part > 255) {
- return false;
- }
- }
- } elseif ($domain_check && function_exists('checkdnsrr')) {
- if (!checkdnsrr($authority, 'A')) {
- return false;
- }
- }
- if ($strict) {
- $strict = '#[' . preg_quote($strict, '#') . ']#';
- if ((!empty($matches[7]) && preg_match($strict, $matches[7]))
- || (!empty($matches[8]) && preg_match($strict, $matches[8]))) {
- return false;
- }
- }
- return true;
- }
- return false;
- }
-
- /**
- * Validate date and times. Note that this method need the Date_Calc class
- *
- * @param string $date Date to validate
- * @param array $options array options where :
- * 'format' The format of the date (%d-%m-%Y)
- * or rfc822_compliant
- * 'min' The date has to be greater
- * than this array($day, $month, $year)
- * or PEAR::Date object
- * 'max' The date has to be smaller than
- * this array($day, $month, $year)
- * or PEAR::Date object
- *
- * @return boolean true if valid date/time, false if not
- *
- * @access public
- */
- function date($date, $options)
- {
- $max = $min = false;
- $format = '';
- if (is_array($options)) {
- extract($options);
- }
-
- if (strtolower($format) == 'rfc822_compliant') {
- $preg = '&^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),) \s+
- (?:(\d{2})?) \s+
- (?:(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)?) \s+
- (?:(\d{2}(\d{2})?)?) \s+
- (?:(\d{2}?)):(?:(\d{2}?))(:(?:(\d{2}?)))? \s+
- (?:[+-]\d{4}|UT|GMT|EST|EDT|CST|CDT|MST|MDT|PST|PDT|[A-IK-Za-ik-z])$&xi';
-
- if (!preg_match($preg, $date, $matches)) {
- return false;
- }
-
- $year = (int)$matches[4];
- $months = array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
- 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
- $month = array_keys($months, $matches[3]);
- $month = (int)$month[0]+1;
- $day = (int)$matches[2];
- $weekday= $matches[1];
- $hour = (int)$matches[6];
- $minute = (int)$matches[7];
- isset($matches[9]) ? $second = (int)$matches[9] : $second = 0;
-
- if ((strlen($year) != 4) ||
- ($day > 31 || $day < 1)||
- ($hour > 23) ||
- ($minute > 59) ||
- ($second > 59)) {
- return false;
- }
- } else {
- $date_len = strlen($format);
- for ($i = 0; $i < $date_len; $i++) {
- $c = $format{$i};
- if ($c == '%') {
- $next = $format{$i + 1};
- switch ($next) {
- case 'j':
- case 'd':
- if ($next == 'j') {
- $day = (int)Validate::_substr($date, 1, 2);
- } else {
- $day = (int)Validate::_substr($date, 0, 2);
- }
- if ($day < 1 || $day > 31) {
- return false;
- }
- break;
- case 'm':
- case 'n':
- if ($next == 'm') {
- $month = (int)Validate::_substr($date, 0, 2);
- } else {
- $month = (int)Validate::_substr($date, 1, 2);
- }
- if ($month < 1 || $month > 12) {
- return false;
- }
- break;
- case 'Y':
- case 'y':
- if ($next == 'Y') {
- $year = Validate::_substr($date, 4);
- $year = (int)$year?$year:'';
- } else {
- $year = (int)(substr(date('Y'), 0, 2) .
- Validate::_substr($date, 2));
- }
- if (strlen($year) != 4 || $year < 0 || $year > 9999) {
- return false;
- }
- break;
- case 'g':
- case 'h':
- if ($next == 'g') {
- $hour = Validate::_substr($date, 1, 2);
- } else {
- $hour = Validate::_substr($date, 2);
- }
- if (!preg_match('/^\d+$/', $hour) || $hour < 0 || $hour > 12) {
- return false;
- }
- break;
- case 'G':
- case 'H':
- if ($next == 'G') {
- $hour = Validate::_substr($date, 1, 2);
- } else {
- $hour = Validate::_substr($date, 2);
- }
- if (!preg_match('/^\d+$/', $hour) || $hour < 0 || $hour > 24) {
- return false;
- }
- break;
- case 's':
- case 'i':
- $t = Validate::_substr($date, 2);
- if (!preg_match('/^\d+$/', $t) || $t < 0 || $t > 59) {
- return false;
- }
- break;
- default:
- trigger_error("Not supported char `$next' after % in offset " . ($i+2), E_USER_WARNING);
- }
- $i++;
- } else {
- //literal
- if (Validate::_substr($date, 1) != $c) {
- return false;
- }
- }
- }
- }
- // there is remaing data, we don't want it
- if (strlen($date) && (strtolower($format) != 'rfc822_compliant')) {
- return false;
- }
-
- if (isset($day) && isset($month) && isset($year)) {
- if (!checkdate($month, $day, $year)) {
- return false;
- }
-
- if (strtolower($format) == 'rfc822_compliant') {
- if ($weekday != date("D", mktime(0, 0, 0, $month, $day, $year))) {
- return false;
- }
- }
-
- if ($min) {
- include_once 'Date/Calc.php';
- if (is_a($min, 'Date') &&
- (Date_Calc::compareDates($day, $month, $year,
- $min->getDay(), $min->getMonth(), $min->getYear()) < 0))
- {
- return false;
- } elseif (is_array($min) &&
- (Date_Calc::compareDates($day, $month, $year,
- $min[0], $min[1], $min[2]) < 0))
- {
- return false;
- }
- }
-
- if ($max) {
- include_once 'Date/Calc.php';
- if (is_a($max, 'Date') &&
- (Date_Calc::compareDates($day, $month, $year,
- $max->getDay(), $max->getMonth(), $max->getYear()) > 0))
- {
- return false;
- } elseif (is_array($max) &&
- (Date_Calc::compareDates($day, $month, $year,
- $max[0], $max[1], $max[2]) > 0))
- {
- return false;
- }
- }
- }
-
- return true;
- }
-
- function _substr(&$date, $num, $opt = false)
- {
- if ($opt && strlen($date) >= $opt && preg_match('/^[0-9]{'.$opt.'}/', $date, $m)) {
- $ret = $m[0];
- } else {
- $ret = substr($date, 0, $num);
- }
- $date = substr($date, strlen($ret));
- return $ret;
- }
-
- function _modf($val, $div) {
- if (function_exists('bcmod')) {
- return bcmod($val, $div);
- } elseif (function_exists('fmod')) {
- return fmod($val, $div);
- }
- $r = $val / $div;
- $i = intval($r);
- return intval($val - $i * $div + .1);
- }
-
- /**
- * Calculates sum of product of number digits with weights
- *
- * @param string $number number string
- * @param array $weights reference to array of weights
- *
- * @returns int returns product of number digits with weights
- *
- * @access protected
- */
- function _multWeights($number, &$weights) {
- if (!is_array($weights)) {
- return -1;
- }
- $sum = 0;
-
- $count = min(count($weights), strlen($number));
- if ($count == 0) { // empty string or weights array
- return -1;
- }
- for ($i = 0; $i < $count; ++$i) {
- $sum += intval(substr($number, $i, 1)) * $weights[$i];
- }
-
- return $sum;
- }
-
- /**
- * Calculates control digit for a given number
- *
- * @param string $number number string
- * @param array $weights reference to array of weights
- * @param int $modulo (optionsl) number
- * @param int $subtract (optional) number
- * @param bool $allow_high (optional) true if function can return number higher than 10
- *
- * @returns int -1 calculated control number is returned
- *
- * @access protected
- */
- function _getControlNumber($number, &$weights, $modulo = 10, $subtract = 0, $allow_high = false) {
- // calc sum
- $sum = Validate::_multWeights($number, $weights);
- if ($sum == -1) {
- return -1;
- }
- $mod = Validate::_modf($sum, $modulo); // calculate control digit
-
- if ($subtract > $mod && $mod > 0) {
- $mod = $subtract - $mod;
- }
- if ($allow_high === false) {
- $mod %= 10; // change 10 to zero
- }
- return $mod;
- }
-
- /**
- * Validates a number
- *
- * @param string $number number to validate
- * @param array $weights reference to array of weights
- * @param int $modulo (optionsl) number
- * @param int $subtract (optional) numbier
- *
- * @returns bool true if valid, false if not
- *
- * @access protected
- */
- function _checkControlNumber($number, &$weights, $modulo = 10, $subtract = 0) {
- if (strlen($number) < count($weights)) {
- return false;
- }
- $target_digit = substr($number, count($weights), 1);
- $control_digit = Validate::_getControlNumber($number, $weights, $modulo, $subtract, $modulo > 10);
-
- if ($control_digit == -1) {
- return false;
- }
- if ($target_digit === 'X' && $control_digit == 10) {
- return true;
- }
- if ($control_digit != $target_digit) {
- return false;
- }
- return true;
- }
-
- /**
- * Bulk data validation for data introduced in the form of an
- * assoc array in the form $var_name => $value.
- * Can be used on any of Validate subpackages
- *
- * @param array $data Ex: array('name' => 'toto', 'email' => 'toto@thing.info');
- * @param array $val_type Contains the validation type and all parameters used in.
- * 'val_type' is not optional
- * others validations properties must have the same name as the function
- * parameters.
- * Ex: array('toto'=>array('type'=>'string','format'='toto@thing.info','min_length'=>5));
- * @param boolean $remove if set, the elements not listed in data will be removed
- *
- * @return array value name => true|false the value name comes from the data key
- *
- * @access public
- */
- function multiple(&$data, &$val_type, $remove = false)
- {
- $keys = array_keys($data);
- $valid = array();
- foreach ($keys as $var_name) {
- if (!isset($val_type[$var_name])) {
- if ($remove) {
- unset($data[$var_name]);
- }
- continue;
- }
- $opt = $val_type[$var_name];
- $methods = get_class_methods('Validate');
- $val2check = $data[$var_name];
- // core validation method
- if (in_array(strtolower($opt['type']), $methods)) {
- //$opt[$opt['type']] = $data[$var_name];
- $method = $opt['type'];
- unset($opt['type']);
-
- if (sizeof($opt) == 1 && is_array(reset($opt))) {
- $opt = array_pop($opt);
- }
- $valid[$var_name] = call_user_func(array('Validate', $method), $val2check, $opt);
-
- /**
- * external validation method in the form:
- * "<class name><underscore><method name>"
- * Ex: us_ssn will include class Validate/US.php and call method ssn()
- */
- } elseif (strpos($opt['type'], '_') !== false) {
- $validateType = explode('_', $opt['type']);
- $method = array_pop($validateType);
- $class = implode('_', $validateType);
- $classPath = str_replace('_', DIRECTORY_SEPARATOR, $class);
- $class = 'Validate_' . $class;
- if (!@include_once "Validate/$classPath.php") {
- trigger_error("$class isn't installed or you may have some permissoin issues", E_USER_ERROR);
- }
-
- $ce = substr(phpversion(), 0, 1) > 4 ? class_exists($class, false) : class_exists($class);
- if (!$ce ||
- !in_array($method, get_class_methods($class)))
- {
- trigger_error("Invalid validation type $class::$method", E_USER_WARNING);
- continue;
- }
- unset($opt['type']);
- if (sizeof($opt) == 1) {
- $opt = array_pop($opt);
- }
- $valid[$var_name] = call_user_func(array($class, $method), $data[$var_name], $opt);
- } else {
- trigger_error("Invalid validation type {$opt['type']}", E_USER_WARNING);
- }
- }
- return $valid;
- }
-}
-
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-/**
- * Specific validation methods for data used in the United States
- *
- * PHP Versions 4 and 5
- *
- * This source file is subject to the New BSD license, That is bundled
- * with this package in the file LICENSE, and is available through
- * the world-wide-web at
- * http://www.opensource.org/licenses/bsd-license.php
- * If you did not receive a copy of the new BSDlicense and are unable
- * to obtain it through the world-wide-web, please send a note to
- * pajoye@php.net so we can mail you a copy immediately.
- *
- * @category Validate
- * @package Validate_US
- * @author Brent Cook <busterbcook@yahoo.com>
- * @author Tim Gallagher <timg@sunflowerroad.com>
- * @copyright 1997-2005 Brent Cook
- * @license http://www.opensource.org/licenses/bsd-license.php new BSD
- * @version CVS: $Id: US.php,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
- * @link http://pear.php.net/package/Validate_US
- */
-
-/**
- * Data validation class for the United States
- *
- * This class provides methods to validate:
- * - Social insurance number (aka SSN)
- * - Region (state code)
- * - Postal code
- * - Telephone number
- *
- * @category Validate
- * @package Validate_US
- * @author Brent Cook <busterbcook@yahoo.com>
- * @author Tim Gallagher <timg@sunflowerroad.com>
- * @copyright 1997-2005 Brent Cook
- * @license http://www.opensource.org/licenses/bsd-license.php new BSD
- * @version Release: @package_version@
- * @link http://pear.php.net/package/Validate_US
- */
-class Validate_US
-{
- /**
- * Validates a social security number
- *
- * @param string $ssn number to validate
- * @param array $high_groups array of highest issued SSN group numbers
- *
- * @return bool
- */
- function ssn($ssn, $high_groups = null)
- {
- // remove any dashes, spaces, returns, tabs or slashes
- $ssn = str_replace(array('-','/',' ',"\t","\n"), '', $ssn);
-
- // check if this is a 9-digit number
- if (!is_numeric($ssn) || strlen($ssn) != 9) {
- return false;
- }
- $area = substr($ssn, 0, 3);
- $group = intval(substr($ssn, 3, 2));
- $serial = intval(substr($ssn, 5, 4));
-
- if (!$high_groups) {
- $high_groups = Validate_US::ssnGetHighGroups();
- }
- return Validate_US::ssnCheck($area, $group, $serial, $high_groups);
- }
-
- /**
- * Returns a range for a supplied group number, which
- * is the middle, two-digit field of a SSN.
- * Group numbers are defined as follows:
- * 1 - Odd numbers, 01 to 09
- * 2 - Even numbers, 10 to 98
- * 3 - Even numbers, 02 to 08
- * 4 - Odd numbers, 11 to 99
- *
- * @param int $groupNumber a group number to check, 00-99
- *
- * @return int
- */
- function ssnGroupRange($groupNumber)
- {
- if (is_array($groupNumber)) {
- extract($groupNumber);
- }
- if ($groupNumber < 10) {
- // is the number odd?
- if ($groupNumber % 2) {
- return 1;
- } else {
- return 3;
- }
- } else {
- // is the number odd?
- if ($groupNumber % 2) {
- return 4;
- } else {
- return 2;
- }
- }
- }
-
- /**
- * checks if a Social Security Number is valid
- * needs the first three digits and first two digits and the
- * final four digits as separate integer parameters
- *
- * @param int $area 3-digit group in a SSN
- * @param int $group 2-digit group in a SSN
- * @param int $serial 4-digit group in a SSN
- * @param array $high_groups array of highest issued group numbers
- * area number=>group number
- *
- * @return bool true if valid
- */
- function ssnCheck($area, $group, $serial, $high_groups)
- {
- if (is_array($area)) {
- extract($area);
- }
- // perform trivial checks
- // no field should contain all zeros
- if (!($area && $group && $serial)) {
- return false;
- }
-
- // check if this area has been assigned yet
- if (!isset($high_groups[$area])) {
- return false;
- }
-
- $high_group = $high_groups[$area];
-
- $high_group_range = Validate_US::ssnGroupRange($high_group);
- $group_range = Validate_US::ssnGroupRange($group);
-
- // if the assigned range is higher than this group number, we're OK
- if ($high_group_range > $group_range) {
- return true;
- } elseif ($high_group_range < $group_range) {
- // if the assigned range is lower than the group number, that's bad
- return false;
- } elseif ($high_group >= $group) {
- // we must be in the same range, check the actual numbers
- return true;
- }
-
- return false;
- }
-
- /**
- * Gets the most current list the highest SSN group numbers issued
- * from the Social Security Administration website. This info can be
- * cached for performance (and to lessen the load on the SSA website)
- *
- * @param string $uri Path to the SSA highgroup.txt file
- * @param bool $is_text Take the $uri param as directly the contents
- *
- * @return array
- */
- function ssnGetHighGroups($uri = 'http://www.ssa.gov/employer/highgroup.txt',
- $is_text = false)
- {
- /**
- * Stores high groups that have been fetched from any given web page to
- * keep the load down if having to validate more then one ssn in a row
- */
- static $high_groups = array();
- static $lastUri = '';
-
- if ($lastUri == $uri && !empty($high_groups)) {
- return $high_groups;
- }
- $lastUri = $uri;
-
- if ($is_text) {
- $source = $uri;
- } else {
- if (!$fd = @fopen($uri, 'r')) {
- $lastUri = '';
- trigger_error('Could not access the SSA High Groups file',
- E_USER_WARNING);
- return array();
- }
- $source = '';
- while ($data = fread($fd, 2048)) {
- $source .= $data;
- }
- fclose($fd);
- }
-
- $lines = explode("\n", ereg_replace("[^\n0-9]*", '', $source));
- $high_groups = array();
- foreach ($lines as $line) {
- $reg = '^([0-9]{3})([0-9]{2})([0-9]{3})([0-9]{2})([0-9]{3})'
- . '([0-9]{2})([0-9]{3})([0-9]{2})([0-9]{3})([0-9]{2})'
- . '([0-9]{3})([0-9]{2})$';
- if (ereg($reg, $line, $grouping)) {
- $high_groups[$grouping[1]] = $grouping[2];
- $high_groups[$grouping[3]] = $grouping[4];
- $high_groups[$grouping[5]] = $grouping[6];
- $high_groups[$grouping[7]] = $grouping[8];
- $high_groups[$grouping[9]] = $grouping[10];
- $high_groups[$grouping[11]] = $grouping[12];
- }
- }
- return $high_groups;
- }
-
- /**
- * Validates a US Postal Code format (ZIP code)
- *
- * @param string $postalCode the ZIP code to validate
- * @param bool $strong optional; strong checks (e.g. against a list
- * of postcodes) (not implanted)
- *
- * @return boolean TRUE if code is valid, FALSE otherwise
- * @access public
- * @static
- * @todo Integrate with USPS web API
- */
- function postalCode($postalCode, $strong = false)
- {
- return (bool)preg_match('/^[0-9]{5}((-| )[0-9]{4})?$/', $postalCode);
- }
-
- /**
- * Validates a "region" (i.e. state) code
- *
- * @param string $region 2-letter state code
- *
- * @return bool Whether the code is a valid state
- * @static
- */
- function region($region)
- {
- switch (strtoupper($region)) {
- case 'AL':
- case 'AK':
- case 'AZ':
- case 'AR':
- case 'CA':
- case 'CO':
- case 'CT':
- case 'DE':
- case 'DC':
- case 'FL':
- case 'GA':
- case 'HI':
- case 'ID':
- case 'IL':
- case 'IN':
- case 'IA':
- case 'KS':
- case 'KY':
- case 'LA':
- case 'ME':
- case 'MD':
- case 'MA':
- case 'MI':
- case 'MN':
- case 'MS':
- case 'MO':
- case 'MT':
- case 'NE':
- case 'NV':
- case 'NH':
- case 'NJ':
- case 'NM':
- case 'NY':
- case 'NC':
- case 'ND':
- case 'OH':
- case 'OK':
- case 'OR':
- case 'PA':
- case 'RI':
- case 'SC':
- case 'SD':
- case 'TN':
- case 'TX':
- case 'UT':
- case 'VT':
- case 'VA':
- case 'WA':
- case 'WV':
- case 'WI':
- case 'WY':
- return true;
- }
- return false;
- }
-
- /**
- * Validate a US phone number.
- *
- * Allowed formats
- * <ul>
- * <li>xxxxxxx <-> 7 digits format</li>
- * <li>(xxx) xxx-xxxx <-> area code with brackets around it (or not) +
- * phone number with dash or not </li>
- * <li>xxx xxx-xxxx <-> area code + number +- dash/space + 4 digits</li>
- * <li>(1|0) xxx xxx-xxxx <-> 1 or 0 + area code + 3 digits +- dash/space
- * + 4 digits</li>
- * <li>xxxxxxxxxx <-> 10 digits</li>
- * </ul>
- *
- * or various combination without spaces or dashes.
- * THIS SHOULD EVENTUALLY take a FORMAT in the options, instead
- *
- * @param string $number phone to validate
- * @param bool $requireAreaCode require the area code? (default: true)
- *
- * @return bool The valid or invalid phone number
- * @access public
- */
- function phoneNumber($number, $requireAreaCode = true)
- {
- if (strlen(trim($number)) <= 6) {
- return false;
- }
-
- if (!$requireAreaCode) {
- // just seven digits, maybe a space or dash
- if (preg_match('/^[2-9]\d{2}[- ]?\d{4}$/', $number)) {
- return true;
- }
- } else {
- // ten digits, maybe spaces and/or dashes and/or parentheses
- // maybe a 1 or a 0...
- $reg = '/^[0-1]?[- ]?(\()?[2-9]\d{2}(?(1)\))[- ]?[2-9]\d{2}[- ]?\d{4}$/';
- if (preg_match($reg,
- $number)) {
- return true;
- }
- }
- return false;
- }
-
-
-
-}
-?>
+++ /dev/null
-<?PHP
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2002 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Stephan Schmidt <schst@php-tools.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Util.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
-
-/**
- * error code for invalid chars in XML name
- */
-define("XML_UTIL_ERROR_INVALID_CHARS", 51);
-
-/**
- * error code for invalid chars in XML name
- */
-define("XML_UTIL_ERROR_INVALID_START", 52);
-
-/**
- * error code for non-scalar tag content
- */
-define("XML_UTIL_ERROR_NON_SCALAR_CONTENT", 60);
-
-/**
- * error code for missing tag name
- */
-define("XML_UTIL_ERROR_NO_TAG_NAME", 61);
-
-/**
- * replace XML entities
- */
-define("XML_UTIL_REPLACE_ENTITIES", 1);
-
-/**
- * embedd content in a CData Section
- */
-define("XML_UTIL_CDATA_SECTION", 5);
-
-/**
- * do not replace entitites
- */
-define("XML_UTIL_ENTITIES_NONE", 0);
-
-/**
- * replace all XML entitites
- * This setting will replace <, >, ", ' and &
- */
-define("XML_UTIL_ENTITIES_XML", 1);
-
-/**
- * replace only required XML entitites
- * This setting will replace <, " and &
- */
-define("XML_UTIL_ENTITIES_XML_REQUIRED", 2);
-
-/**
- * replace HTML entitites
- * @link http://www.php.net/htmlentities
- */
-define("XML_UTIL_ENTITIES_HTML", 3);
-
-/**
- * Collapse all empty tags.
- */
-define("XML_UTIL_COLLAPSE_ALL", 1);
-
-/**
- * Collapse only empty XHTML tags that have no end tag.
- */
-define("XML_UTIL_COLLAPSE_XHTML_ONLY", 2);
-
-/**
- * utility class for working with XML documents
- *
- * @category XML
- * @package XML_Util
- * @version 1.1.0
- * @author Stephan Schmidt <schst@php.net>
- */
-class XML_Util {
-
- /**
- * return API version
- *
- * @access public
- * @static
- * @return string $version API version
- */
- function apiVersion()
- {
- return '1.1';
- }
-
- /**
- * replace XML entities
- *
- * With the optional second parameter, you may select, which
- * entities should be replaced.
- *
- * <code>
- * require_once 'XML/Util.php';
- *
- * // replace XML entites:
- * $string = XML_Util::replaceEntities("This string contains < & >.");
- * </code>
- *
- * @access public
- * @static
- * @param string string where XML special chars should be replaced
- * @param integer setting for entities in attribute values (one of XML_UTIL_ENTITIES_XML, XML_UTIL_ENTITIES_XML_REQUIRED, XML_UTIL_ENTITIES_HTML)
- * @return string string with replaced chars
- * @see reverseEntities()
- */
- function replaceEntities($string, $replaceEntities = XML_UTIL_ENTITIES_XML)
- {
- switch ($replaceEntities) {
- case XML_UTIL_ENTITIES_XML:
- return strtr($string,array(
- '&' => '&',
- '>' => '>',
- '<' => '<',
- '"' => '"',
- '\'' => ''' ));
- break;
- case XML_UTIL_ENTITIES_XML_REQUIRED:
- return strtr($string,array(
- '&' => '&',
- '<' => '<',
- '"' => '"' ));
- break;
- case XML_UTIL_ENTITIES_HTML:
- return htmlentities($string);
- break;
- }
- return $string;
- }
-
- /**
- * reverse XML entities
- *
- * With the optional second parameter, you may select, which
- * entities should be reversed.
- *
- * <code>
- * require_once 'XML/Util.php';
- *
- * // reverse XML entites:
- * $string = XML_Util::reverseEntities("This string contains < & >.");
- * </code>
- *
- * @access public
- * @static
- * @param string string where XML special chars should be replaced
- * @param integer setting for entities in attribute values (one of XML_UTIL_ENTITIES_XML, XML_UTIL_ENTITIES_XML_REQUIRED, XML_UTIL_ENTITIES_HTML)
- * @return string string with replaced chars
- * @see replaceEntities()
- */
- function reverseEntities($string, $replaceEntities = XML_UTIL_ENTITIES_XML)
- {
- switch ($replaceEntities) {
- case XML_UTIL_ENTITIES_XML:
- return strtr($string,array(
- '&' => '&',
- '>' => '>',
- '<' => '<',
- '"' => '"',
- ''' => '\'' ));
- break;
- case XML_UTIL_ENTITIES_XML_REQUIRED:
- return strtr($string,array(
- '&' => '&',
- '<' => '<',
- '"' => '"' ));
- break;
- case XML_UTIL_ENTITIES_HTML:
- $arr = array_flip(get_html_translation_table(HTML_ENTITIES));
- return strtr($string, $arr);
- break;
- }
- return $string;
- }
-
- /**
- * build an xml declaration
- *
- * <code>
- * require_once 'XML/Util.php';
- *
- * // get an XML declaration:
- * $xmlDecl = XML_Util::getXMLDeclaration("1.0", "UTF-8", true);
- * </code>
- *
- * @access public
- * @static
- * @param string $version xml version
- * @param string $encoding character encoding
- * @param boolean $standAlone document is standalone (or not)
- * @return string $decl xml declaration
- * @uses XML_Util::attributesToString() to serialize the attributes of the XML declaration
- */
- function getXMLDeclaration($version = "1.0", $encoding = null, $standalone = null)
- {
- $attributes = array(
- "version" => $version,
- );
- // add encoding
- if ($encoding !== null) {
- $attributes["encoding"] = $encoding;
- }
- // add standalone, if specified
- if ($standalone !== null) {
- $attributes["standalone"] = $standalone ? "yes" : "no";
- }
-
- return sprintf("<?xml%s?>", XML_Util::attributesToString($attributes, false));
- }
-
- /**
- * build a document type declaration
- *
- * <code>
- * require_once 'XML/Util.php';
- *
- * // get a doctype declaration:
- * $xmlDecl = XML_Util::getDocTypeDeclaration("rootTag","myDocType.dtd");
- * </code>
- *
- * @access public
- * @static
- * @param string $root name of the root tag
- * @param string $uri uri of the doctype definition (or array with uri and public id)
- * @param string $internalDtd internal dtd entries
- * @return string $decl doctype declaration
- * @since 0.2
- */
- function getDocTypeDeclaration($root, $uri = null, $internalDtd = null)
- {
- if (is_array($uri)) {
- $ref = sprintf( ' PUBLIC "%s" "%s"', $uri["id"], $uri["uri"] );
- } elseif (!empty($uri)) {
- $ref = sprintf( ' SYSTEM "%s"', $uri );
- } else {
- $ref = "";
- }
-
- if (empty($internalDtd)) {
- return sprintf("<!DOCTYPE %s%s>", $root, $ref);
- } else {
- return sprintf("<!DOCTYPE %s%s [\n%s\n]>", $root, $ref, $internalDtd);
- }
- }
-
- /**
- * create string representation of an attribute list
- *
- * <code>
- * require_once 'XML/Util.php';
- *
- * // build an attribute string
- * $att = array(
- * "foo" => "bar",
- * "argh" => "tomato"
- * );
- *
- * $attList = XML_Util::attributesToString($att);
- * </code>
- *
- * @access public
- * @static
- * @param array $attributes attribute array
- * @param boolean|array $sort sort attribute list alphabetically, may also be an assoc array containing the keys 'sort', 'multiline', 'indent', 'linebreak' and 'entities'
- * @param boolean $multiline use linebreaks, if more than one attribute is given
- * @param string $indent string used for indentation of multiline attributes
- * @param string $linebreak string used for linebreaks of multiline attributes
- * @param integer $entities setting for entities in attribute values (one of XML_UTIL_ENTITIES_NONE, XML_UTIL_ENTITIES_XML, XML_UTIL_ENTITIES_XML_REQUIRED, XML_UTIL_ENTITIES_HTML)
- * @return string string representation of the attributes
- * @uses XML_Util::replaceEntities() to replace XML entities in attribute values
- * @todo allow sort also to be an options array
- */
- function attributesToString($attributes, $sort = true, $multiline = false, $indent = ' ', $linebreak = "\n", $entities = XML_UTIL_ENTITIES_XML)
- {
- /**
- * second parameter may be an array
- */
- if (is_array($sort)) {
- if (isset($sort['multiline'])) {
- $multiline = $sort['multiline'];
- }
- if (isset($sort['indent'])) {
- $indent = $sort['indent'];
- }
- if (isset($sort['linebreak'])) {
- $multiline = $sort['linebreak'];
- }
- if (isset($sort['entities'])) {
- $entities = $sort['entities'];
- }
- if (isset($sort['sort'])) {
- $sort = $sort['sort'];
- } else {
- $sort = true;
- }
- }
- $string = '';
- if (is_array($attributes) && !empty($attributes)) {
- if ($sort) {
- ksort($attributes);
- }
- if( !$multiline || count($attributes) == 1) {
- foreach ($attributes as $key => $value) {
- if ($entities != XML_UTIL_ENTITIES_NONE) {
- if ($entities === XML_UTIL_CDATA_SECTION) {
- $entities = XML_UTIL_ENTITIES_XML;
- }
- $value = XML_Util::replaceEntities($value, $entities);
- }
- $string .= ' '.$key.'="'.$value.'"';
- }
- } else {
- $first = true;
- foreach ($attributes as $key => $value) {
- if ($entities != XML_UTIL_ENTITIES_NONE) {
- $value = XML_Util::replaceEntities($value, $entities);
- }
- if ($first) {
- $string .= " ".$key.'="'.$value.'"';
- $first = false;
- } else {
- $string .= $linebreak.$indent.$key.'="'.$value.'"';
- }
- }
- }
- }
- return $string;
- }
-
- /**
- * Collapses empty tags.
- *
- * @access public
- * @static
- * @param string $xml XML
- * @param integer $mode Whether to collapse all empty tags (XML_UTIL_COLLAPSE_ALL) or only XHTML (XML_UTIL_COLLAPSE_XHTML_ONLY) ones.
- * @return string $xml XML
- */
- function collapseEmptyTags($xml, $mode = XML_UTIL_COLLAPSE_ALL) {
- if ($mode == XML_UTIL_COLLAPSE_XHTML_ONLY) {
- return preg_replace(
- '/<(area|base|br|col|hr|img|input|link|meta|param)([^>]*)><\/\\1>/s',
- '<\\1\\2 />',
- $xml
- );
- } else {
- return preg_replace(
- '/<(\w+)([^>]*)><\/\\1>/s',
- '<\\1\\2 />',
- $xml
- );
- }
- }
-
- /**
- * create a tag
- *
- * This method will call XML_Util::createTagFromArray(), which
- * is more flexible.
- *
- * <code>
- * require_once 'XML/Util.php';
- *
- * // create an XML tag:
- * $tag = XML_Util::createTag("myNs:myTag", array("foo" => "bar"), "This is inside the tag", "http://www.w3c.org/myNs#");
- * </code>
- *
- * @access public
- * @static
- * @param string $qname qualified tagname (including namespace)
- * @param array $attributes array containg attributes
- * @param mixed $content
- * @param string $namespaceUri URI of the namespace
- * @param integer $replaceEntities whether to replace XML special chars in content, embedd it in a CData section or none of both
- * @param boolean $multiline whether to create a multiline tag where each attribute gets written to a single line
- * @param string $indent string used to indent attributes (_auto indents attributes so they start at the same column)
- * @param string $linebreak string used for linebreaks
- * @param boolean $sortAttributes Whether to sort the attributes or not
- * @return string $string XML tag
- * @see XML_Util::createTagFromArray()
- * @uses XML_Util::createTagFromArray() to create the tag
- */
- function createTag($qname, $attributes = array(), $content = null, $namespaceUri = null, $replaceEntities = XML_UTIL_REPLACE_ENTITIES, $multiline = false, $indent = "_auto", $linebreak = "\n", $sortAttributes = true)
- {
- $tag = array(
- "qname" => $qname,
- "attributes" => $attributes
- );
-
- // add tag content
- if ($content !== null) {
- $tag["content"] = $content;
- }
-
- // add namespace Uri
- if ($namespaceUri !== null) {
- $tag["namespaceUri"] = $namespaceUri;
- }
-
- return XML_Util::createTagFromArray($tag, $replaceEntities, $multiline, $indent, $linebreak, $sortAttributes);
- }
-
- /**
- * create a tag from an array
- * this method awaits an array in the following format
- * <pre>
- * array(
- * "qname" => $qname // qualified name of the tag
- * "namespace" => $namespace // namespace prefix (optional, if qname is specified or no namespace)
- * "localpart" => $localpart, // local part of the tagname (optional, if qname is specified)
- * "attributes" => array(), // array containing all attributes (optional)
- * "content" => $content, // tag content (optional)
- * "namespaceUri" => $namespaceUri // namespaceUri for the given namespace (optional)
- * )
- * </pre>
- *
- * <code>
- * require_once 'XML/Util.php';
- *
- * $tag = array(
- * "qname" => "foo:bar",
- * "namespaceUri" => "http://foo.com",
- * "attributes" => array( "key" => "value", "argh" => "fruit&vegetable" ),
- * "content" => "I'm inside the tag",
- * );
- * // creating a tag with qualified name and namespaceUri
- * $string = XML_Util::createTagFromArray($tag);
- * </code>
- *
- * @access public
- * @static
- * @param array $tag tag definition
- * @param integer $replaceEntities whether to replace XML special chars in content, embedd it in a CData section or none of both
- * @param boolean $multiline whether to create a multiline tag where each attribute gets written to a single line
- * @param string $indent string used to indent attributes (_auto indents attributes so they start at the same column)
- * @param string $linebreak string used for linebreaks
- * @param boolean $sortAttributes Whether to sort the attributes or not
- * @return string $string XML tag
- * @see XML_Util::createTag()
- * @uses XML_Util::attributesToString() to serialize the attributes of the tag
- * @uses XML_Util::splitQualifiedName() to get local part and namespace of a qualified name
- */
- function createTagFromArray($tag, $replaceEntities = XML_UTIL_REPLACE_ENTITIES, $multiline = false, $indent = "_auto", $linebreak = "\n", $sortAttributes = true)
- {
- if (isset($tag['content']) && !is_scalar($tag['content'])) {
- return XML_Util::raiseError( 'Supplied non-scalar value as tag content', XML_UTIL_ERROR_NON_SCALAR_CONTENT );
- }
-
- if (!isset($tag['qname']) && !isset($tag['localPart'])) {
- return XML_Util::raiseError( 'You must either supply a qualified name (qname) or local tag name (localPart).', XML_UTIL_ERROR_NO_TAG_NAME );
- }
-
- // if no attributes hav been set, use empty attributes
- if (!isset($tag["attributes"]) || !is_array($tag["attributes"])) {
- $tag["attributes"] = array();
- }
-
- if (isset($tag['namespaces'])) {
- foreach ($tag['namespaces'] as $ns => $uri) {
- $tag['attributes']['xmlns:'.$ns] = $uri;
- }
- }
-
- // qualified name is not given
- if (!isset($tag["qname"])) {
- // check for namespace
- if (isset($tag["namespace"]) && !empty($tag["namespace"])) {
- $tag["qname"] = $tag["namespace"].":".$tag["localPart"];
- } else {
- $tag["qname"] = $tag["localPart"];
- }
- // namespace URI is set, but no namespace
- } elseif (isset($tag["namespaceUri"]) && !isset($tag["namespace"])) {
- $parts = XML_Util::splitQualifiedName($tag["qname"]);
- $tag["localPart"] = $parts["localPart"];
- if (isset($parts["namespace"])) {
- $tag["namespace"] = $parts["namespace"];
- }
- }
-
- if (isset($tag["namespaceUri"]) && !empty($tag["namespaceUri"])) {
- // is a namespace given
- if (isset($tag["namespace"]) && !empty($tag["namespace"])) {
- $tag["attributes"]["xmlns:".$tag["namespace"]] = $tag["namespaceUri"];
- } else {
- // define this Uri as the default namespace
- $tag["attributes"]["xmlns"] = $tag["namespaceUri"];
- }
- }
-
- // check for multiline attributes
- if ($multiline === true) {
- if ($indent === "_auto") {
- $indent = str_repeat(" ", (strlen($tag["qname"])+2));
- }
- }
-
- // create attribute list
- $attList = XML_Util::attributesToString($tag['attributes'], $sortAttributes, $multiline, $indent, $linebreak, $replaceEntities );
- if (!isset($tag['content']) || (string)$tag['content'] == '') {
- $tag = sprintf('<%s%s />', $tag['qname'], $attList);
- } else {
- switch ($replaceEntities) {
- case XML_UTIL_ENTITIES_NONE:
- break;
- case XML_UTIL_CDATA_SECTION:
- $tag['content'] = XML_Util::createCDataSection($tag['content']);
- break;
- default:
- $tag['content'] = XML_Util::replaceEntities($tag['content'], $replaceEntities);
- break;
- }
- $tag = sprintf('<%s%s>%s</%s>', $tag['qname'], $attList, $tag['content'], $tag['qname'] );
- }
- return $tag;
- }
-
- /**
- * create a start element
- *
- * <code>
- * require_once 'XML/Util.php';
- *
- * // create an XML start element:
- * $tag = XML_Util::createStartElement("myNs:myTag", array("foo" => "bar") ,"http://www.w3c.org/myNs#");
- * </code>
- *
- * @access public
- * @static
- * @param string $qname qualified tagname (including namespace)
- * @param array $attributes array containg attributes
- * @param string $namespaceUri URI of the namespace
- * @param boolean $multiline whether to create a multiline tag where each attribute gets written to a single line
- * @param string $indent string used to indent attributes (_auto indents attributes so they start at the same column)
- * @param string $linebreak string used for linebreaks
- * @param boolean $sortAttributes Whether to sort the attributes or not
- * @return string $string XML start element
- * @see XML_Util::createEndElement(), XML_Util::createTag()
- */
- function createStartElement($qname, $attributes = array(), $namespaceUri = null, $multiline = false, $indent = '_auto', $linebreak = "\n", $sortAttributes = true)
- {
- // if no attributes hav been set, use empty attributes
- if (!isset($attributes) || !is_array($attributes)) {
- $attributes = array();
- }
-
- if ($namespaceUri != null) {
- $parts = XML_Util::splitQualifiedName($qname);
- }
-
- // check for multiline attributes
- if ($multiline === true) {
- if ($indent === "_auto") {
- $indent = str_repeat(" ", (strlen($qname)+2));
- }
- }
-
- if ($namespaceUri != null) {
- // is a namespace given
- if (isset($parts["namespace"]) && !empty($parts["namespace"])) {
- $attributes["xmlns:".$parts["namespace"]] = $namespaceUri;
- } else {
- // define this Uri as the default namespace
- $attributes["xmlns"] = $namespaceUri;
- }
- }
-
- // create attribute list
- $attList = XML_Util::attributesToString($attributes, $sortAttributes, $multiline, $indent, $linebreak);
- $element = sprintf("<%s%s>", $qname, $attList);
- return $element;
- }
-
- /**
- * create an end element
- *
- * <code>
- * require_once 'XML/Util.php';
- *
- * // create an XML start element:
- * $tag = XML_Util::createEndElement("myNs:myTag");
- * </code>
- *
- * @access public
- * @static
- * @param string $qname qualified tagname (including namespace)
- * @return string $string XML end element
- * @see XML_Util::createStartElement(), XML_Util::createTag()
- */
- function createEndElement($qname)
- {
- $element = sprintf("</%s>", $qname);
- return $element;
- }
-
- /**
- * create an XML comment
- *
- * <code>
- * require_once 'XML/Util.php';
- *
- * // create an XML start element:
- * $tag = XML_Util::createComment("I am a comment");
- * </code>
- *
- * @access public
- * @static
- * @param string $content content of the comment
- * @return string $comment XML comment
- */
- function createComment($content)
- {
- $comment = sprintf("<!-- %s -->", $content);
- return $comment;
- }
-
- /**
- * create a CData section
- *
- * <code>
- * require_once 'XML/Util.php';
- *
- * // create a CData section
- * $tag = XML_Util::createCDataSection("I am content.");
- * </code>
- *
- * @access public
- * @static
- * @param string $data data of the CData section
- * @return string $string CData section with content
- */
- function createCDataSection($data)
- {
- return sprintf("<![CDATA[%s]]>", $data);
- }
-
- /**
- * split qualified name and return namespace and local part
- *
- * <code>
- * require_once 'XML/Util.php';
- *
- * // split qualified tag
- * $parts = XML_Util::splitQualifiedName("xslt:stylesheet");
- * </code>
- * the returned array will contain two elements:
- * <pre>
- * array(
- * "namespace" => "xslt",
- * "localPart" => "stylesheet"
- * );
- * </pre>
- *
- * @access public
- * @static
- * @param string $qname qualified tag name
- * @param string $defaultNs default namespace (optional)
- * @return array $parts array containing namespace and local part
- */
- function splitQualifiedName($qname, $defaultNs = null)
- {
- if (strstr($qname, ':')) {
- $tmp = explode(":", $qname);
- return array(
- "namespace" => $tmp[0],
- "localPart" => $tmp[1]
- );
- }
- return array(
- "namespace" => $defaultNs,
- "localPart" => $qname
- );
- }
-
- /**
- * check, whether string is valid XML name
- *
- * <p>XML names are used for tagname, attribute names and various
- * other, lesser known entities.</p>
- * <p>An XML name may only consist of alphanumeric characters,
- * dashes, undescores and periods, and has to start with a letter
- * or an underscore.
- * </p>
- *
- * <code>
- * require_once 'XML/Util.php';
- *
- * // verify tag name
- * $result = XML_Util::isValidName("invalidTag?");
- * if (XML_Util::isError($result)) {
- * print "Invalid XML name: " . $result->getMessage();
- * }
- * </code>
- *
- * @access public
- * @static
- * @param string $string string that should be checked
- * @return mixed $valid true, if string is a valid XML name, PEAR error otherwise
- * @todo support for other charsets
- */
- function isValidName($string)
- {
- // check for invalid chars
- if (!preg_match('/^[[:alpha:]_]$/', $string{0})) {
- return XML_Util::raiseError('XML names may only start with letter or underscore', XML_UTIL_ERROR_INVALID_START);
- }
-
- // check for invalid chars
- if (!preg_match('/^([[:alpha:]_]([[:alnum:]\-\.]*)?:)?[[:alpha:]_]([[:alnum:]\_\-\.]+)?$/', $string)) {
- return XML_Util::raiseError('XML names may only contain alphanumeric chars, period, hyphen, colon and underscores', XML_UTIL_ERROR_INVALID_CHARS);
- }
- // XML name is valid
- return true;
- }
-
- /**
- * replacement for XML_Util::raiseError
- *
- * Avoids the necessity to always require
- * PEAR.php
- *
- * @access public
- * @param string error message
- * @param integer error code
- * @return object PEAR_Error
- */
- function raiseError($msg, $code)
- {
- require_once 'PEAR.php';
- return PEAR::raiseError($msg, $code);
- }
-}
-?>
\ No newline at end of file
+++ /dev/null
-#sfWebDebug
-{
- padding: 0;
- margin: 0;
- font-family: Arial, sans-serif;
- font-size: 12px;
- color: #333;
- text-align: left;
- line-height: 12px;
-}
-
-#sfWebDebug a, #sfWebDebug a:hover
-{
- color: #000;
- text-decoration: none;
- color: #1E90FF;
-}
-
-#sfWebDebugBar a, #sfWebDebugBar a:hover
-{
- text-decoration: none;
- color: #000;
-}
-
-#sfWebDebug img
-{
- border: 0;
-}
-
-#sfWebDebugBar
-{
- position: absolute;
- margin: 0;
- padding: 1px 0;
- right: 0px;
- top: 0px;
- opacity: 0.80;
- filter: alpha(opacity:80);
- z-index: 10000;
-}
-
-#sfWebDebugBar[id]
-{
- position: fixed;
-}
-
-#sfWebDebugBar img
-{
- vertical-align: middle;
-}
-
-#sfWebDebugBar .menu
-{
- padding: 5px;
- display: inline;
-}
-
-#sfWebDebugBar .menu li
-{
- display: inline;
- list-style: none;
- margin: 0;
- padding: 0 5px;
- border-right: 1px solid #aaa;
-}
-
-#title
-{
- border-right: 1px solid #aaa;
-}
-
-#sfWebDebugBar .menu li.last
-{
- margin: 0;
- padding: 0;
- border: 0;
-}
-
-#sfWebDebugDatabaseDetails li
-{
- margin: 0;
- margin-left: 30px;
- padding: 5px 0;
-}
-
-#sfWebDebugShortMessages li
-{
- margin-bottom: 10px;
- padding: 5px;
- background-color: #ddd;
-}
-
-#sfWebDebugShortMessages li
-{
- list-style: none;
-}
-
-#sfWebDebugDetails
-{
- margin-right: 7px;
-}
-
-#sfWebDebug pre
-{
- line-height: 1.3;
- margin-bottom: 10px;
-}
-
-#sfWebDebug h1
-{
- font-size: 16px;
- font-weight: bold;
- margin-bottom: 20px;
- padding: 0;
- border: 0px;
- background-color: #eee;
-}
-
-#sfWebDebug h2
-{
- font-size: 14px;
- font-weight: bold;
- margin: 10px 0;
- padding: 0;
- border: 0px;
- background: none;
-}
-
-#sfWebDebug .top
-{
- position: absolute;
- left: 0px;
- top: 0px;
- width: 100%;
- padding: 10px;
- z-index: 9999;
- background-color: #efefef;
- border-bottom: 1px solid #aaa;
-}
-
-#sfWebDebugLog
-{
- margin: 0;
- padding: 3px;
- font-size: 11px;
-}
-
-#sfWebDebugLogMenu li
-{
- display: inline;
- list-style: none;
- margin: 0;
- padding: 0 5px;
- border-right: 1px solid #aaa;
-}
-
-#sfWebDebugConfigSummary
-{
- display: inline;
- padding: 5px;
- background-color: #ddd;
- border: 1px solid #aaa;
- margin: 20px 0;
-}
-
-#sfWebDebugConfigSummary li
-{
- list-style: none;
- display: inline;
- margin: 0;
- padding: 0 5px;
- border-right: 1px solid #aaa;
-}
-
-#sfWebDebugConfigSummary li.last
-{
- margin: 0;
- padding: 0;
- border: 0;
-}
-
-.sfWebDebugInfo, .sfWebDebugInfo td
-{
- background-color: #ddd;
-}
-
-.sfWebDebugInfo #title
-{
- float:left;
- background-color: #ddd;
- width:90px;
- text-align:center;
-}
-
-.sfWebDebugWarning, .sfWebDebugWarning td
-{
- background-color: orange;
-}
-
-.sfWebDebugError, .sfWebDebugError td
-{
- background-color: #f99;
-}
-
-.sfWebDebugLogNumber
-{
- width: 25px;
-}
-
-.sfWebDebugLogType
-{
- width: 1%;
- white-space: nowrap;
- color: darkgreen;
-}
-
-.sfWebDebugLogTypePerf
-{
- width: 100%;
- white-space: nowrap;
- color: darkgreen;
-}
-
-.sfWebDebugLogMessagePerf
-{
- width: 100%;
- white-space: nowrap;
-}
-
-.sfWebDebugLogFile
-{
- width: 1%;
-}
-
-.sfWebDebugLogLine
-{
- width: 1%;
-}
-
-.sfWebDebugLogInfo
-{
- color: blue;
-}
-
-.sfWebDebugLogFromSource
-{
- padding: 5px 5px 5px 5px;
- background-color: #DDD;
-}
-
-.ison
-{
- color: #3f3;
- margin-right: 5px;
-}
-
-.isoff
-{
- color: #f33;
- margin-right: 5px;
- text-decoration: line-through;
-}
-
-.sfWebDebugLogs
-{
- padding: 0;
- margin: 0;
- border: 1px solid #999;
- font-family: Arial;
- font-size: 11px;
-}
-
-.sfWebDebugLogs tr
-{
- padding: 0;
- margin: 0;
- border: 0;
-}
-
-.sfWebDebugLogs td
-{
- margin: 0;
- border: 0;
- padding: 1px 3px;
- vertical-align: top;
-}
-
-.sfWebDebugLogs th
-{
- margin: 0;
- border: 0;
- padding: 3px 5px;
- vertical-align: top;
- background-color: #999;
- color: #eee;
- white-space: nowrap;
-}
-
-.sfWebDebugDebugInfo
-{
- margin-left: 10px;
- padding-left: 5px;
- border-left: 1px solid #aaa;
-}
-
-.sfWebDebugCache
-{
- padding: 0;
- margin: 0;
- font-family: Arial;
- position: absolute;
- overflow: hidden;
- z-index: 995;
- font-size: 9px;
- padding: 2px;
- filter:alpha(opacity=85);
- -moz-opacity:0.85;
- opacity: 0.85;
-}
-
-#sfWebDebug .main-file
-{
- font-weight: bold;
-}
-
-#sfWebDebugFiles .source {
- margin: 0px 5px 0px 5px;
-}
-
-#sfWebDebug .watch
-{
- font-weight:bold;
-}
\ No newline at end of file
+++ /dev/null
-/* Main table */
-.pd-table {
- border: solid 1px Navy;
- border-bottom: 0px;
- border-right: 0px;
-}
-/* Table header */
-.pd-table-header {
- font-family: tahoma, arial, sans-serif;
- font-size: 0.8em;
- font-weight: bold;
- color: white;
- background-color: Navy;
- border-bottom: solid 1px Navy;
-}
-/* 1- Generic TD cell */
-.pd-td {
- font-family: tahoma, arial, sans-serif;
- font-size: 0.8em;
- color: black;
- background-color: white;
- padding: 2px;
- border-bottom: solid 1px Navy;
- border-right: solid 1px Navy;
-}
-/* 2, 3 - Query cell */
-.pd-query {
- font-weight: bold;
- color: orange;
-}
-/* 5 - Application error */
-.pd-app-error {
- background-color: orange;
- color: white;
- font-weight: bold;
-}
-/* 6 - Credits */
-.pd-credits {
- font-family: tahoma, arial, sans-serif;
- font-size: 0.9em;
- color: navy;
- font-weight: bold;
-}
-/* 7 - Search cell */
-.pd-search {
- font-family: tahoma, arial, sans-serif;
- font-size: 0.8em;
- font-weight: bold;
-}
-/* Highligthed search keyword */
-.pd-search-hl {
- background-color: yellow;
- color: blue;
-}
-/* 8 - Dump */
-.pd-dump-title {
- color: blue;
-}
-.pd-dump-val {
- color: black;
- border: solid 1px blue;
-}
-/* 9 - Perf summary */
-.pd-perf {
- font-size: 0.8em;
- color: white;
- font-weight: bold;
- background-color: blue;
-}
-.pd-perf-table {
- border: solid 1px blue;
-}
-.pd-time {
- color: navy;
- font-weight: bold;
-}
-/* 10 - Templates */
-.pd-files {
- color: blue;
-}
-.pd-main-file {
- background-color: LightSteelBlue;
- color: white;
- font-weight: bold;
-}
-/* 11 - Page action */
-.pd-pageaction {
- background-color: LightSteelBlue;
- color: white;
- font-weight: bold;
-}
-/* 13 - Watch cell */
-.pd-watch {
- font-style: oblique;
- font-weight: bold;
-}
-.pd-watch-val {
- font-weight: bold;
- border: solid 1px Navy;
-}
-/* 14 - Php errors */
-.pd-php-warning {
- background-color: red;
- color: white;
- font-weight: bold;
-}
-.pd-php-notice {
- background-color: yellow;
- color: navy;
- font-weight: bold;
-}
-.pd-php-user-error {
- background-color: orange;
- color: white;
- font-weight: bold;
-}
\ No newline at end of file
+++ /dev/null
-.hl-default {
- color: Black;
-}
-.hl-code {
- color: Gray;
-}
-.hl-brackets {
- color: Olive;
-}
-.hl-comment {
- color: Orange;
-}
-.hl-quotes {
- color: Darkred;
-}
-.hl-string {
- color: Red;
-}
-.hl-identifier {
- color: Blue;
-}
-.hl-builtin {
- color: Teal;
-}
-.hl-reserved {
- color: Green;
-}
-.hl-inlinedoc {
- color: Blue;
-}
-.hl-var {
- color: Darkblue;
-}
-.hl-url {
- color: Blue;
-}
-.hl-special {
- color: Navy;
-}
-.hl-number {
- color: Maroon;
-}
-.hl-inlinetags {
- color: Blue;
-}
-.hl-main {
- background-color: #F5F5F5;
-}
-.hl-gutter {
- background-color: #999999;
- color: White
-}
-.hl-table {
- font-family: courier;
- font-size: 14px;
- border: solid 1px Lightgrey;
-}
-.hl-title {
- font-family: Tahoma;
- font-size: 22px;
- border: solid 1px Lightgrey;
- background-color: #F0F0F0;
- margin-left: 15px;
- padding-left: 5px;
- padding-right: 5px;
-}
\ No newline at end of file
+++ /dev/null
-function sfWebDebugGetElementsByClassName(strClass, strTag, objContElm)
-{
- // http://muffinresearch.co.uk/archives/2006/04/29/getelementsbyclassname-deluxe-edition/
- strTag = strTag || "*";
- objContElm = objContElm || document;
- var objColl = (strTag == '*' && document.all) ? document.all : objContElm.getElementsByTagName(strTag);
- var arr = new Array();
- var delim = strClass.indexOf('|') != -1 ? '|' : ' ';
- var arrClass = strClass.split(delim);
- var j = objColl.length;
- for (var i = 0; i < j; i++) {
- if(objColl[i].className == undefined) continue;
- var arrObjClass = objColl[i].className.split(' ');
- if (delim == ' ' && arrClass.length > arrObjClass.length) continue;
- var c = 0;
- comparisonLoop:
- {
- var l = arrObjClass.length;
- for (var k = 0; k < l; k++) {
- var n = arrClass.length;
- for (var m = 0; m < n; m++) {
- if (arrClass[m] == arrObjClass[k]) c++;
- if (( delim == '|' && c == 1) || (delim == ' ' && c == arrClass.length)) {
- arr.push(objColl[i]);
- break comparisonLoop;
- }
- }
- }
- }
- }
- return arr;
-}
-
-function sfWebDebugToggleMenu()
-{
- var element = document.getElementById('sfWebDebugDetails');
-
- var cacheElements = sfWebDebugGetElementsByClassName('sfWebDebugCache');
- var mainCacheElements = sfWebDebugGetElementsByClassName('sfWebDebugActionCache');
-
- if (element.style.display != 'none')
- {
- document.getElementById('sfWebDebugLog').style.display = 'none';
- document.getElementById('sfWebDebugConfig').style.display = 'none';
- document.getElementById('sfWebDebugDatabaseDetails').style.display = 'none';
- document.getElementById('sfWebDebugW3CDetails').style.display = 'none';
- document.getElementById('sfWebDebugTimeDetails').style.display = 'none';
-
- // hide all cache information
- for (var i = 0; i < cacheElements.length; ++i)
- {
- cacheElements[i].style.display = 'none';
- }
- for (var i = 0; i < mainCacheElements.length; ++i)
- {
- mainCacheElements[i].style.border = 'none';
- }
- }
- else
- {
- for (var i = 0; i < cacheElements.length; ++i)
- {
- cacheElements[i].style.display = '';
- }
- for (var i = 0; i < mainCacheElements.length; ++i)
- {
- mainCacheElements[i].style.border = '1px solid #f00';
- }
- }
-
- sfWebDebugToggle('sfWebDebugDetails');
- sfWebDebugToggle('sfWebDebugShowMenu');
- sfWebDebugToggle('sfWebDebugHideMenu');
-}
-
-function sfWebDebugShowDetailsFor(element)
-{
- if (element != 'sfWebDebugLog') document.getElementById('sfWebDebugLog').style.display='none';
- if (element != 'sfWebDebugConfig') document.getElementById('sfWebDebugConfig').style.display='none';
- if (element != 'sfWebDebugDatabaseDetails') document.getElementById('sfWebDebugDatabaseDetails').style.display='none';
- if (element != 'sfWebDebugW3CDetails') document.getElementById('sfWebDebugW3CDetails').style.display='none';
- if (element != 'sfWebDebugTimeDetails') document.getElementById('sfWebDebugTimeDetails').style.display='none';
-
- sfWebDebugToggle(element);
-}
-
-function sfWebDebugToggle(element)
-{
- if (typeof element == 'string')
- element = document.getElementById(element);
-
- if (element)
- element.style.display = element.style.display == 'none' ? '' : 'none';
-}
-
-function sfWebDebugToggleMessages(klass)
-{
- var elements = sfWebDebugGetElementsByClassName(klass);
-
- var x = elements.length;
- for (var i = 0; i < x; ++i)
- {
- sfWebDebugToggle(elements[i]);
- }
-}
-
-function sfWebDebugToggleAllLogLines(show, klass)
-{
- var elements = sfWebDebugGetElementsByClassName(klass);
- var x = elements.length;
- for (var i = 0; i < x; ++i)
- {
- elements[i].style.display = show ? '' : 'none';
- }
-}
-
-function sfWebDebugShowOnlyLogLines(type)
-{
- var types = new Array();
- types[0] = 'info';
- types[1] = 'warning';
- types[2] = 'error';
- for (klass in types)
- {
- var elements = sfWebDebugGetElementsByClassName('sfWebDebug' + types[klass].substring(0, 1).toUpperCase() + types[klass].substring(1, types[klass].length));
- var x = elements.length;
- for (var i = 0; i < x; ++i)
- {
- elements[i].style.display = (type == types[klass]) ? '' : 'none';
- }
- }
-}
+++ /dev/null
-<?xml version="1.0"?>
-<!-- $Id: Auth_XML.xml,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $ -->
-<liveuserAuthXML>
- <user>
- <userId>c4ca4238a0b923820dcc509a6f75849b</userId>
- <handle>father</handle>
- <password>0de959beaa82daa7df6ef2286d071a6d</password>
- <lastLogin>1047564897</lastLogin>
- <isActive>Y</isActive>
- </user>
- <user>
- <userId>c81e728d9d4c2f636f067f89cc14862c</userId>
- <handle>mother</handle>
- <password>6ee6a213cb02554a63b1867143572e70</password>
- <lastLogin>1047564685</lastLogin>
- <isActive>Y</isActive>
- </user>
- <user>
- <userId>eccbc87e4b5ce2fe28308fd9f2a7baf3</userId>
- <handle>child</handle>
- <password>1b7d5726533ab525a8760351e9b5e415</password>
- <lastLogin>1047565686</lastLogin>
- <isActive>Y</isActive>
- </user>
-</liveuserAuthXML>
\ No newline at end of file
+++ /dev/null
-<!-- $Id: Perm_XML.xml,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $ -->
-<?xml version="1.0"?>
-<liveuserPermXMLSimple>
- <users>
- <user userId="1" authUserId="c4ca4238a0b923820dcc509a6f75849b" authContainerName="0" type="1">
- <rights>3,4,5,6</rights>
- </user>
- <user userId="2" authUserId="c81e728d9d4c2f636f067f89cc14862c" authContainerName="0" type="1">
- <rights>1,3,4,5</rights>
- </user>
- <user userId="3" authUserId="eccbc87e4b5ce2fe28308fd9f2a7baf3" authContainerName="0" type="1">
- <rights>2,3,5</rights>
- </user>
- </users>
- <areas>
- <area id="1" defineName="kitchen">
- <right defineName="cooking">1</right>
- <right defineName="washTheDishes">2</right>
- </area>
- <area id="2" defineName="livingroom">
- <right defineName="watchTV">3</right>
- <right defineName="watchLateNightTV">4</right>
- </area>
- <area id="3" defineName="office">
- <right defineName="useTheComputer">5</right>
- <right defineName="connectingTheInternet">6</right>
- </area>
- </areas>
-</liveuserPermXMLSimple>
\ No newline at end of file
+++ /dev/null
-We no longer support SQL based schema files and instead only provide xml based
-schema files that are supported by Metabase, MDB and MDB2. To ease installation
-we provide an install.php script which contains a class and some commented code
-inside this directory.
-
-This is only a basic readme which could be extended into something a lot bigger,
-for example describing why you'd need the medium container and etc. this has
-often be done on the mailinglist at http://news.gmane.org/gmane.comp.php.pear.liveuser
-
-if anyone cares to write this thing up, please do so and email us to the
-mailinglist or post it to http://oss.backendmedia.com/LiveUser/ (a link or the whole thing.)
+++ /dev/null
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * A framework for authentication and authorization in PHP applications
- *
- * LiveUser is an authentication/permission framework designed
- * to be flexible and easily extendable.
- *
- * Since it is impossible to have a
- * "one size fits all" it takes a container
- * approach which should enable it to
- * be versatile enough to meet most needs.
- *
- * PHP version 4 and 5
- *
- * LICENSE: This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library 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
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
- * MA 02111-1307 USA
- *
- *
- * @category authentication
- * @package LiveUser
- * @author Lukas Smith <smith@pooteeweet.org>
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version CVS: $Id: install.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- * @link http://pear.php.net/LiveUser
- */
-
-require_once 'LiveUser.php';
-require_once 'MDB2/Schema.php';
-
-/* ATTENTION: uncomment the following lines as needed
-
-// error handler
-function handleError($err)
-{
- var_dump($err);
- return PEAR_ERRORSTACK_PUSH;
-}
-
-PEAR_ErrorStack::setDefaultCallback('handleError');
-
-echo '<pre>';
-
-// customize DSN as needed
-$dsn = 'mysql://root:@localhost/liveuser_test_installer';
-
-// customize config array as needed
-$conf = array(
- 'authContainers' => array(
- array(
- 'type' => 'MDB2',
- 'expireTime' => 3600,
- 'idleTime' => 1800,
- 'storage' => array(
- 'dsn' => $dsn,
-# 'force_seq' => false,
- 'alias' => array(
- 'auth_user_id' => 'authUserId',
- 'lastlogin' => 'lastLogin',
- 'is_active' => 'isActive',
- 'owner_user_id' => 'owner_user_id',
- 'owner_group_id' => 'owner_group_id',
- ),
- 'fields' => array(
-# 'auth_user_id' => 'integer',
- 'lastlogin' => 'timestamp',
- 'is_active' => 'boolean',
- 'owner_user_id' => 'integer',
- 'owner_group_id' => 'integer',
- ),
- 'tables' => array(
- 'users' => array(
- 'fields' => array(
- 'lastlogin' => null,
- 'is_active' => null,
- 'owner_user_id' => null,
- 'owner_group_id' => null,
- ),
- ),
- ),
- ),
- ),
- ),
- 'permContainer' => array(
- 'type' => 'Complex',
- 'storage' => array(
- 'MDB2' => array(
- 'dsn' => $dsn,
- 'prefix' => 'liveuser_',
-# 'force_seq' => false,
- 'fields' => array(
-# 'auth_user_id' => 'integer',
- ),
- )
- )
- )
-);
-
-@unlink('dump.sql');
-function dump_to_file(&$db, $scope, $message, $is_manip)
-{
- if ($is_manip) {
- $fp = fopen('dump.sql', 'a');
- fwrite($fp, $message."\n");
- fclose($fp);
- }
-}
-
-// customize MDB2_SCHEMA configuration options as needed
-$options = array(
- 'debug' => true,
- 'log_line_break' => '<br>',
-// to dump the SQL to a file uncommented the following line
-// and set the disable_query parameter in the installSchema calls
-# 'debug_handler' => 'dump_to_file',
-);
-
-// field name - value pairs of lengths to use in the schema
-$lengths = array('description' => 255);
-
-// field name - value pairs of defaults to use in the schema
-$defaults = array('right_level' => LIVEUSER_MAX_LEVEL);
-
-// create instance of the auth container
-$auth =& LiveUser::authFactory($conf['authContainers'][0], 'foo');
-// generate xml schema file for auth container
-$result = LiveUser_Misc_Schema_Install::generateSchema(
- $auth,
- 'auth_schema.xml',
- $lengths,
- $defaults
-);
-var_dump($result);
-
-// install the auth xml schema .. notice the 4th parameter controls if the
-// database needs to be created or not
-$variables = array();
-$result = LiveUser_Misc_Schema_Install::installSchema(
- $auth,
- 'auth_schema.xml',
- $variables,
- true,
- $options,
- false,
- false
-);
-var_dump($result);
-
-// create instance of the perm container
-$perm =& LiveUser::storageFactory($conf['permContainer']['storage']);
-// generate xml schema file for perm container
-$result = LiveUser_Misc_Schema_Install::generateSchema(
- $perm,
- 'perm_schema.xml',
- $lengths,
- $defaults
-);
-var_dump($result);
-
-// install the perm xml schema .. notice the 4th parameter controls if the
-// database needs to be created or not
-$variables = array();
-$result = LiveUser_Misc_Schema_Install::installSchema(
- $perm,
- 'perm_schema.xml',
- $variables,
- false,
- $options,
- false,
- false
-);
-var_dump($result);
-
-/* */
-
-/**
- * database schema installer class
- *
- * This class generates XML based schema files and uses PEAR:MDB2_Schema to
- * install them inside the users database
- *
- * Requirements:
- * - PEAR::LiveUser
- * - PEAR::MDB2_Schema
- * - PEAR::MDB2
- * - PEAR::MDB2_Driver_* (where * is the name of the backend database)
- * - a valid LiveUser configuration
- *
- * @category authentication
- * @package LiveUser
- * @author Lukas Smith <smith@pooteeweet.org>
- * @version $Id: install.php,v 1.1.1.1 2008/04/28 15:20:48 jamie Exp $
- * @copyright 2002-2006 Markus Wolff
- * @license http://www.gnu.org/licenses/lgpl.txt
- * @version Release: @package_version@
- * @link http://pear.php.net/LiveUser
- */
-class LiveUser_Misc_Schema_Install
-{
-
- /**
- * Accepts a PDO DSN and returns a PEAR DSN
- *
- * The PEAR DSN format is specified here:
- * http://pear.php.net/manual/en/package.database.db.intro-dsn.php
- *
- * @param string PDO DSN
- * @return array PEAR DSN
- *
- * @access public
- */
- function parsePDODSN($pdo_dsn)
- {
- die('Hardcode the parsed DSN to the PEAR array dsn format.');
- return array(
- 'phptype' => false,
- 'dbsyntax' => false,
- // not needed as its fetched from the options array
- # 'username' => false,
- # 'password' => false,
- 'protocol' => false,
- 'hostspec' => false,
- 'port' => false,
- 'socket' => false,
- 'database' => false,
- 'mode' => false,
- );
- }
-
- /**
- * Generates a schema file from the instance
- *
- * @param object LiveUser storage instance
- * @param string name of the file into which the xml schema should be written
- * @param array key-value pairs with keys being field names and values being the default length
- * @param array key-value pairs with keys being field names and values being the default values
- * @return bool|PEAR_Error true on success or a PEAR_Error on error
- *
- * @access public
- */
- function generateSchema($obj, $file, $lengths = array(), $defaults = array())
- {
- if (!is_object($obj)) {
- return false;
- }
-
- $use_auto_increment = false;
- if (isset($obj->force_seq) && !$obj->force_seq) {
- if (MDB2::isConnection($obj->dbc)) {
- $use_auto_increment = ($obj->dbc->supports('auto_increment') === true);
- } elseif (is_a($obj->dbc, 'PDO')) {
- // todo: need to figure out what to do here
- $use_auto_increment = true;
- }
- }
-
- // generate xml schema
- $tables = array();
- $sequences = array();
- foreach ($obj->tables as $table_name => $table) {
- $fields = array();
- $table_indexes = array();
- foreach($table['fields'] as $field_name => $required) {
- $type = $obj->fields[$field_name];
- $field_name = $obj->alias[$field_name];
- $fields[$field_name]['name'] = $field_name;
- $fields[$field_name]['type'] = $type;
- if ($fields[$field_name]['type'] == 'text') {
- $length = array_key_exists($field_name, $lengths) ? $lengths[$field_name] : 32;
- $fields[$field_name]['length'] = $length;
- }
-
- $default = array_key_exists($field_name, $defaults) ? $defaults[$field_name] : '';
- if ($required || array_key_exists($field_name, $defaults)) {
- $fields[$field_name]['default'] = $default;
- }
-
- // check if not null
- if ($required) {
- $fields[$field_name]['notnull'] = true;
- // Sequences
- if ($required === 'seq') {
- if ($fields[$field_name]['type'] == 'integer' && $use_auto_increment) {
- $fields[$field_name]['autoincrement'] = true;
- $fields[$field_name]['default'] = 0;
- } else {
- $sequences[$obj->prefix . $obj->alias[$table_name]] = array(
- 'on' => array(
- 'table' => $obj->prefix . $obj->alias[$table_name],
- 'field' => $field_name,
- )
- );
-
- $table_indexes[$table_name.'_'.$field_name] = array(
- 'fields' => array(
- $field_name => true,
- ),
- 'primary' => true
- );
- }
- // Generate indexes
- } elseif (is_string($required)) {
- $index_name = $table_name.'_'.$required . '_i';
- $table_indexes[$index_name]['fields'][$field_name] = true;
- $table_indexes[$index_name]['unique'] = true;
- }
- } else {
- $fields[$field_name]['notnull'] = ($required === false);
- }
- }
- $tables[$obj->prefix . $obj->alias[$table_name]]['fields'] = $fields;
- $tables[$obj->prefix . $obj->alias[$table_name]]['indexes'] = $table_indexes;
- }
-
- $definition = array(
- 'name' => '<variable>database</variable>',
- 'create' => '<variable>create</variable>',
- 'overwrite' => '<variable>overwrite</variable>',
- 'tables' => $tables,
- 'sequences' => $sequences,
- );
-
- return LiveUser_Misc_Schema_Install::writeSchema($definition, $file);
- }
-
- /**
- * Takes a given definition array and writes it as xml to a file
- *
- * @param array schema definition
- * @return bool|PEAR_Error true on success or a PEAR_Error on error
- *
- * @access public
- */
- function writeSchema($definition, $file)
- {
- require_once 'MDB2/Schema/Writer.php';
- $writer =& new MDB2_Schema_Writer();
- $arguments = array(
- 'output_mode' => 'file',
- 'output' => $file,
- );
- return $writer->dumpDatabase($definition, $arguments);
- }
-
- /**
- * Install a schema file into the database
- *
- * @param object LiveUser storage instance
- * @param string name of the file into which the xml schema should be written
- * @param array key-value pairs with keys being variable names and values being the variable values
- * @param bool determines if the database should be created or not
- * @param array MDB2_Schema::connect() options
- * @param bool determines if the database should be created or not
- * @param bool determines if the old schema file should be unlinked first
- * @param bool determines if the disable_query option should be set in MDB2
- * @return bool|PEAR_Error true on success or a PEAR_Error on error
- *
- * @access public
- */
- function installSchema($obj, $file, $variables = array(), $create = true,
- $options = array(), $overwrite = false, $disable_query = false)
- {
- $dsn = array();
- if (is_a($obj->dbc, 'DB_Common')) {
- $dsn = $obj->dbc->dsn;
- $options['seqcol_name'] = 'id';
- } elseif (is_a($obj->dbc, 'PDO')) {
- $dsn = LiveUser_Misc_Schema_Install::parsePDODSN($obj->dbc->dsn);
- $dsn['username'] = array_key_exists('username', $obj->dbc->options)
- ? $obj->dbc->options['username'] : '';
- $dsn['password'] = array_key_exists('password', $obj->dbc->options)
- ? $obj->dbc->options['password'] : '';
- $options['seqname_format'] = '%s';
- } elseif (MDB2::isConnection($obj->dbc)) {
- $dsn = $obj->dbc->getDSN('array');
- }
-
- $file_old = $file.'.'.$dsn['hostspec'].'.'.$dsn['database'].'.old';
- $variables['create'] = (int)$create;
- $variables['overwrite'] = (int)$overwrite;
- $variables['database'] = $dsn['database'];
- unset($dsn['database']);
-
- $manager =& MDB2_Schema::factory($dsn, $options);
- if (PEAR::isError($manager)) {
- return $manager;
- }
-
- if ($overwrite && file_exists($file_old)) {
- unlink($file_old);
- }
- $result = $manager->updateDatabase($file, $file_old, $variables, $disable_query);
-
- $debug = $manager->db->getOption('debug');
- if ($debug && !PEAR::isError($debug)) {
- echo('Debug messages<br>');
- echo($manager->db->getDebugOutput().'<br>');
- }
- $manager->disconnect();
- return $result;
- }
-}
-
-?>
+++ /dev/null
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available through the world-wide-web at the following url: |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Stig Bakken <ssb@php.net> |
-// | Tomas V.V.Cox <cox@idecnet.com> |
-// | |
-// +----------------------------------------------------------------------+
-//
-// $Id: pearcmd.php,v 1.1.1.1 2008/04/28 15:20:46 jamie Exp $
-
-ob_end_clean();
-/**
- * @nodep Gtk
- */
-if ('/usr/share/pear' != '@'.'include_path'.'@') {
- ini_set('include_path', '/usr/share/pear');
-}
-ini_set('allow_url_fopen', true);
-if (!ini_get('safe_mode')) {
- set_time_limit(0);
-}
-ob_implicit_flush(true);
-ini_set('track_errors', true);
-ini_set('html_errors', false);
-ini_set('magic_quotes_runtime', false);
-set_error_handler('error_handler');
-
-$pear_package_version = "1.3.2";
-
-require_once 'PEAR.php';
-require_once 'PEAR/Config.php';
-require_once 'PEAR/Command.php';
-require_once 'Console/Getopt.php';
-
-PEAR_Command::setFrontendType('CLI');
-$all_commands = PEAR_Command::getCommands();
-
-$argv = Console_Getopt::readPHPArgv();
-/* $progname = basename($argv[0]); */
-$progname = 'pear';
-if (in_array('getopt2', get_class_methods('Console_Getopt'))) {
- array_shift($argv);
- $options = Console_Getopt::getopt2($argv, "c:C:d:D:Gh?sSqu:vV");
-} else {
- $options = Console_Getopt::getopt($argv, "c:C:d:D:Gh?sSqu:vV");
-}
-if (PEAR::isError($options)) {
- usage($options);
-}
-
-$opts = $options[0];
-
-$fetype = 'CLI';
-if ($progname == 'gpear' || $progname == 'pear-gtk') {
- $fetype = 'Gtk';
-} else {
- foreach ($opts as $opt) {
- if ($opt[0] == 'G') {
- $fetype = 'Gtk';
- }
- }
-}
-PEAR_Command::setFrontendType($fetype);
-$ui = &PEAR_Command::getFrontendObject();
-PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($ui, "displayFatalError"));
-
-$pear_user_config = '';
-$pear_system_config = '';
-$store_user_config = false;
-$store_system_config = false;
-$verbose = 1;
-
-foreach ($opts as $opt) {
- switch ($opt[0]) {
- case 'c':
- $pear_user_config = $opt[1];
- break;
- case 'C':
- $pear_system_config = $opt[1];
- break;
- }
-}
-
-$config = &PEAR_Config::singleton($pear_user_config, $pear_system_config);
-$verbose = $config->get("verbose");
-$cmdopts = array();
-
-foreach ($opts as $opt) {
- $param = !empty($opt[1]) ? $opt[1] : true;
- switch ($opt[0]) {
- case 'd':
- list($key, $value) = explode('=', $param);
- $config->set($key, $value, 'user');
- break;
- case 'D':
- list($key, $value) = explode('=', $param);
- $config->set($key, $value, 'system');
- break;
- case 's':
- $store_user_config = true;
- break;
- case 'S':
- $store_system_config = true;
- break;
- case 'u':
- $config->remove($param, 'user');
- break;
- case 'v':
- $config->set('verbose', $config->get('verbose') + 1);
- break;
- case 'q':
- $config->set('verbose', $config->get('verbose') - 1);
- break;
- case 'V':
- usage(null, 'version');
- default:
- // all non pear params goes to the command
- $cmdopts[$opt[0]] = $param;
- break;
- }
-}
-
-if ($store_system_config) {
- $config->store('system');
-}
-
-if ($store_user_config) {
- $config->store('user');
-}
-
-$command = (isset($options[1][0])) ? $options[1][0] : null;
-
-if (empty($command) && ($store_user_config || $store_system_config)) {
- exit;
-}
-
-if ($fetype == 'Gtk') {
- Gtk::main();
-} else do {
- if ($command == 'help') {
- usage(null, @$options[1][1]);
- }
-
- PEAR::pushErrorHandling(PEAR_ERROR_RETURN);
- $cmd = PEAR_Command::factory($command, $config);
- PEAR::popErrorHandling();
- if (PEAR::isError($cmd)) {
- usage(null, @$options[1][1]);
- }
-
- $short_args = $long_args = null;
- PEAR_Command::getGetoptArgs($command, $short_args, $long_args);
- if (in_array('getopt2', get_class_methods('Console_Getopt'))) {
- array_shift($options[1]);
- $tmp = Console_Getopt::getopt2($options[1], $short_args, $long_args);
- } else {
- $tmp = Console_Getopt::getopt($options[1], $short_args, $long_args);
- }
- if (PEAR::isError($tmp)) {
- break;
- }
- list($tmpopt, $params) = $tmp;
- $opts = array();
- foreach ($tmpopt as $foo => $tmp2) {
- list($opt, $value) = $tmp2;
- if ($value === null) {
- $value = true; // options without args
- }
- if (strlen($opt) == 1) {
- $cmdoptions = $cmd->getOptions($command);
- foreach ($cmdoptions as $o => $d) {
- if (@$d['shortopt'] == $opt) {
- $opts[$o] = $value;
- }
- }
- } else {
- if (substr($opt, 0, 2) == '--') {
- $opts[substr($opt, 2)] = $value;
- }
- }
- }
- $ok = $cmd->run($command, $opts, $params);
- if ($ok === false) {
- PEAR::raiseError("unknown command `$command'");
- }
-} while (false);
-
-// {{{ usage()
-
-function usage($error = null, $helpsubject = null)
-{
- global $progname, $all_commands;
- $stderr = fopen('php://stderr', 'w');
- if (PEAR::isError($error)) {
- fputs($stderr, $error->getMessage() . "\n");
- } elseif ($error !== null) {
- fputs($stderr, "$error\n");
- }
- if ($helpsubject != null) {
- $put = cmdHelp($helpsubject);
- } else {
- $put =
- "Usage: $progname [options] command [command-options] <parameters>\n".
- "Type \"$progname help options\" to list all options.\n".
- "Type \"$progname help <command>\" to get the help for the specified command.\n".
- "Commands:\n";
- $maxlen = max(array_map("strlen", $all_commands));
- $formatstr = "%-{$maxlen}s %s\n";
- ksort($all_commands);
- foreach ($all_commands as $cmd => $class) {
- $put .= sprintf($formatstr, $cmd, PEAR_Command::getDescription($cmd));
- }
- }
- fputs($stderr, "$put\n");
- fclose($stderr);
- exit;
-}
-
-function cmdHelp($command)
-{
- global $progname, $all_commands, $config;
- if ($command == "options") {
- return
- "Options:\n".
- " -v increase verbosity level (default 1)\n".
- " -q be quiet, decrease verbosity level\n".
- " -c file find user configuration in `file'\n".
- " -C file find system configuration in `file'\n".
- " -d foo=bar set user config variable `foo' to `bar'\n".
- " -D foo=bar set system config variable `foo' to `bar'\n".
- " -G start in graphical (Gtk) mode\n".
- " -s store user configuration\n".
- " -S store system configuration\n".
- " -u foo unset `foo' in the user configuration\n".
- " -h, -? display help/usage (this message)\n".
- " -V version information\n";
- } elseif ($command == "shortcuts") {
- $sc = PEAR_Command::getShortcuts();
- $ret = "Shortcuts:\n";
- foreach ($sc as $s => $c) {
- $ret .= sprintf(" %-8s %s\n", $s, $c);
- }
- return $ret;
-
- } elseif ($command == "version") {
- return "PEAR Version: ".$GLOBALS['pear_package_version'].
- "\nPHP Version: ".phpversion().
- "\nZend Engine Version: ".zend_version().
- "\nRunning on: ".php_uname();
-
- } elseif ($help = PEAR_Command::getHelp($command)) {
- if (is_string($help)) {
- return "$progname $command [options] $help\n";
- }
- if ($help[1] === null) {
- return "$progname $command $help[0]";
- } else {
- return "$progname $command [options] $help[0]\n$help[1]";
- }
- }
- return "Command '$command' is not valid, try 'pear help'";
-}
-
-// }}}
-
-function error_handler($errno, $errmsg, $file, $line, $vars) {
- if ((defined('E_STRICT') && $errno & E_STRICT) || !error_reporting()) {
- return; // @silenced error
- }
- $errortype = array (
- E_ERROR => "Error",
- E_WARNING => "Warning",
- E_PARSE => "Parsing Error",
- E_NOTICE => "Notice",
- E_CORE_ERROR => "Core Error",
- E_CORE_WARNING => "Core Warning",
- E_COMPILE_ERROR => "Compile Error",
- E_COMPILE_WARNING => "Compile Warning",
- E_USER_ERROR => "User Error",
- E_USER_WARNING => "User Warning",
- E_USER_NOTICE => "User Notice"
- );
- $prefix = $errortype[$errno];
- $file = basename($file);
- print "\n$prefix: $errmsg in $file on line $line\n";
-}
-
-
-/*
- * Local variables:
- * tab-width: 4
- * c-basic-offset: 4
- * indent-tabs-mode: nil
- * mode: php
- * End:
- */
-// vim600:syn=php
-
-?>
+++ /dev/null
-#!@php_bin@
-<?php
-/**
- * PHP_CodeSniffer tokenises PHP code and detects violations of a
- * defined set of coding standards.
- *
- * PHP version 5
- *
- * @category PHP
- * @package PHP_CodeSniffer
- * @author Greg Sherwood <gsherwood@squiz.net>
- * @author Marc McIntyre <mmcintyre@squiz.net>
- * @copyright 2006 Squiz Pty Ltd (ABN 77 084 670 600)
- * @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
- * @version CVS: $Id: phpcs,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
- * @link http://pear.php.net/package/PHP_CodeSniffer
- */
-
-error_reporting(E_ALL | E_STRICT);
-
-if (is_file(dirname(__FILE__).'/../CodeSniffer/CLI.php') === true) {
- include_once dirname(__FILE__).'/../CodeSniffer/CLI.php';
-} else {
- include_once 'PHP/CodeSniffer/CLI.php';
-}
-
-$phpcs = new PHP_CodeSniffer_CLI();
-$phpcs->checkRequirements();
-
-$numErrors = $phpcs->process();
-if ($numErrors === 0) {
- exit(0);
-} else {
- exit(1);
-}
-
-?>
+++ /dev/null
-#!@php_bin@
-<?php
-/**
- * A commit hook for SVN.
- *
- * PHP version 5
- *
- * @category PHP
- * @package PHP_CodeSniffer
- * @author Jack Bates <ms419@freezone.co.uk>
- * @author Greg Sherwood <gsherwood@squiz.net>
- * @copyright 2006 Squiz Pty Ltd (ABN 77 084 670 600)
- * @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
- * @version CVS: $Id: phpcs-svn-pre-commit,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
- * @link http://pear.php.net/package/PHP_CodeSniffer
- */
-
-if (is_file(dirname(__FILE__).'/../CodeSniffer/CLI.php') === true) {
- include_once dirname(__FILE__).'/../CodeSniffer/CLI.php';
-} else {
- include_once 'PHP/CodeSniffer/CLI.php';
-}
-
-define('PHP_CODESNIFFER_SVNLOOK', '/usr/bin/svnlook');
-
-
-/**
- * A class to process command line options.
- *
- * @category PHP
- * @package PHP_CodeSniffer
- * @author Jack Bates <ms419@freezone.co.uk>
- * @author Greg Sherwood <gsherwood@squiz.net>
- * @copyright 2006 Squiz Pty Ltd (ABN 77 084 670 600)
- * @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
- * @version Release: @package_version@
- * @link http://pear.php.net/package/PHP_CodeSniffer
- */
-class PHP_CodeSniffer_SVN_Hook extends PHP_CodeSniffer_CLI
-{
-
-
- /**
- * Get a list of default values for all possible command line arguments.
- *
- * @return array
- */
- public function getDefaults()
- {
- $defaults = parent::getDefaults();
-
- $defaults['svnArgs'] = array();
- return $defaults;
-
- }//end getDefaults()
-
-
- /**
- * Processes an unknown command line argument.
- *
- * All unkown args are sent to SVN commands.
- *
- * @param string $arg The command line argument.
- * @param int $pos The position of the argument on the command line.
- * @param array $values An array of values determined from CLI args.
- *
- * @return array The updated CLI values.
- * @see getCommandLineValues()
- */
- public function processUnknownArgument($arg, $pos, $values)
- {
- $values['svnArgs'][] = $arg;
- return $values;
-
- }//end processUnknownArgument()
-
-
- /**
- * Runs PHP_CodeSniffer over files are directories.
- *
- * @param array $values An array of values determined from CLI args.
- *
- * @return int The number of error and warning messages shown.
- * @see getCommandLineValues()
- */
- public function process($values=array())
- {
- if (empty($values) === true) {
- $values = parent::getCommandLineValues();
- }
-
- // Get list of files in this transaction.
- $command = PHP_CODESNIFFER_SVNLOOK.' changed '.implode(' ', $values['svnArgs']);
- $handle = popen($command, 'r');
- if ($handle === false) {
- echo 'ERROR: Could not execute "'.$command.'"'.PHP_EOL.PHP_EOL;
- exit(2);
- }
-
- $contents = stream_get_contents($handle);
- fclose($handle);
-
- // Do not check deleted paths.
- $contents = preg_replace('/^D.*/m', null, $contents);
-
- // Drop the four characters representing the action which precede the path on
- // each line.
- $contents = preg_replace('/^.{4}/m', null, $contents);
-
- $values['standard'] = $this->validateStandard($values['standard']);
- if (PHP_CodeSniffer::isInstalledStandard($values['standard']) === false) {
- // They didn't select a valid coding standard, so help them
- // out by letting them know which standards are installed.
- echo 'ERROR: the "'.$values['standard'].'" coding standard is not installed. ';
- $this->printInstalledStandards();
- exit(2);
- }
-
- $phpcs = new PHP_CodeSniffer($values['verbosity'], $values['tabWidth']);
-
- // Set file extensions if they were specified. Otherwise,
- // let PHP_CodeSniffer decide on the defaults.
- if (empty($values['extensions']) === false) {
- $phpcs->setAllowedFileExtensions($values['extensions']);
- }
-
- // Set ignore patterns if they were specified.
- if (empty($values['ignored']) === false) {
- $phpcs->setIgnorePatterns($values['ignored']);
- }
-
- $phpcs->setTokenListeners($values['standard']);
-
- foreach (preg_split('/\v/', $contents, -1, PREG_SPLIT_NO_EMPTY) as $path) {
- // Get the contents of each file, as it would be after this transaction.
- $command = PHP_CODESNIFFER_SVNLOOK.' cat '.implode(' ', $values['svnArgs']).' '.$path;
- $handle = popen($command, 'r');
- if ($handle === false) {
- echo 'ERROR: Could not execute "'.$command.'"'.PHP_EOL.PHP_EOL;
- exit(2);
- }
-
- $contents = stream_get_contents($handle);
- fclose($handle);
-
- $phpcs->processFile($path, $contents);
- }//end foreach
-
- return parent::printErrorReport($phpcs, $values['report'], $values['showWarnings']);
-
- }//end process()
-
-
- /**
- * Prints out the usage information for this script.
- *
- * @return void
- */
- public function printUsage()
- {
- parent::printUsage();
-
- echo PHP_EOL;
- echo ' Each additional argument is passed to the `svnlook changed ...`'.PHP_EOL;
- echo ' and `svnlook cat ...` commands. The report is printed on standard output,'.PHP_EOL;
- echo ' however Subversion displays only standard error to the user, so in a'.PHP_EOL;
- echo ' pre-commit hook, this script should be invoked as follows:'.PHP_EOL;
- echo PHP_EOL;
- echo ' '.basename($_SERVER['argv'][0]).' ... "$REPOS" -t "$TXN" >&2 || exit 1'.PHP_EOL;
-
- }//end printUsage()
-
-
-}//end class
-
-$phpcs = new PHP_CodeSniffer_SVN_Hook();
-$phpcs->checkRequirements();
-
-$numErrors = $phpcs->process();
-if ($numErrors !== 0) {
- exit(1);
-}
-
-?>
+++ /dev/null
-@echo off
-REM PHP_CodeSniffer tokenises PHP code and detects violations of a
-REM defined set of coding standards.
-REM
-REM PHP version 5
-REM
-REM @category PHP
-REM @package PHP_CodeSniffer
-REM @author Greg Sherwood <gsherwood@squiz.net>
-REM @author Marc McIntyre <mmcintyre@squiz.net>
-REM @copyright 2006 Squiz Pty Ltd (ABN 77 084 670 600)
-REM @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
-REM @version CVS: $Id: phpcs.bat,v 1.1.1.1 2008/04/28 15:20:47 jamie Exp $
-REM @link http://pear.php.net/package/PHP_CodeSniffer
-
-"@php_bin@" -d auto_append_file="" -d auto_prepend_file="" -d include_path="@php_dir@" "@bin_dir@\phpcs" %*
+++ /dev/null
-<?php
-
-include_once 'TestAuthContainer.php';
-include_once 'Auth/Container/DB.php';
-
-
-class DBContainer extends TestAuthContainer {
-
- function DBContainer($name){
- $this->TestAuthContainer($name);
- }
-
- function &getContainer() {
- static $container;
- #print "In DBContainer::getContainer {$this->skip_tests}\n";
- if(!isset($container)){
- include './auth_container_db_options.php';
- $container = new Auth_Container_DB($options);
- // Catch if DB connection cannot be made
- $res = $container->_prepare();
- }
-
- if(!DB::isConnection($container->db)){
- #print "In DBContainer::getContainer container->db is error \n";
- $this->skip_tests = true;
- $this->skip_tests_message = "SKIP TEST:DB is not a connection object, check dsn !!!";
- }
- return($container);
- }
-
- function &getExtraOptions() {
- include './auth_container_db_options.php';
- return($extra_options);
- }
-}
-
-
-
-
-?>
+++ /dev/null
-<?php
-
-include_once 'TestAuthContainer.php';
-include_once 'Auth/Container/File.php';
-
-class FileContaner extends TestAuthContainer {
-
- function FileContaner($name){
- $this->TestAuthContainer($name);
- }
-
- function &getContainer() {
- static $container;
- if(!isset($container)){
- include './auth_container_file_options.php';
- $container = new Auth_Container_File($options);
- }
- return($container);
- }
-
- function &getExtraOptions() {
- include './auth_container_file_options.php';
- return($extra_options);
- }
-}
-
-
-
-
-?>
+++ /dev/null
-<?php
-
-include_once 'TestAuthContainer.php';
-include_once 'Auth/Container/MDB2.php';
-
-
-class MDB2Container extends TestAuthContainer {
-
- function MDB2Container($name){
- $this->TestAuthContainer($name);
- }
-
- function &getContainer() {
- static $container;
- #print "In MDB2Container::getContainer {$this->skip_tests}\n";
- if(!isset($container)){
- include './auth_container_mdb2_options.php';
- $container = new Auth_Container_MDB2($options);
- // Catch if DB connection cannot be made
- $res = $container->_prepare();
- }
-
- if(!MDB2::isConnection($container->db)){
- #print "In MDB2Container::getContainer container->db is error \n";
- $this->skip_tests = true;
- $this->skip_tests_message = "SKIP TEST:MDB2 is not a connection object, check dsn !!!";
- }
- return $container;
- }
-
- function &getExtraOptions() {
- include './auth_container_mdb2_options.php';
- return $extra_options;
- }
-}
-?>
+++ /dev/null
-<?php
-
-include_once 'TestAuthContainer.php';
-include_once 'Auth/Container/MDB.php';
-
-
-class MDBContainer extends TestAuthContainer {
-
- function MDBContainer($name){
- $this->TestAuthContainer($name);
- }
-
- function &getContainer() {
- static $container;
- #print "In MDBContainer::getContainer {$this->skip_tests}\n";
- if(!isset($container)){
- include './auth_container_mdb_options.php';
- $container = new Auth_Container_MDB($options);
- // Catch if DB connection cannot be made
- $res = $container->_prepare();
- }
-
- if(!MDB::isConnection($container->db)){
- #print "In MDBContainer::getContainer container->db is error \n";
- $this->skip_tests = true;
- $this->skip_tests_message = "SKIP TEST:MDB is not a connection object, check dsn !!!";
- }
- return $container;
- }
-
- function &getExtraOptions() {
- include './auth_container_mdb_options.php';
- return $extra_options;
- }
-}
-
-
-
-
-?>
+++ /dev/null
-<?php
-
-include_once 'TestAuthContainer.php';
-include_once 'Auth/Container/POP3.php';
-
-
-class POP3Container extends TestAuthContainer {
-
- function POP3Container($name){
- $this->TestAuthContainer($name);
- }
-
- function &getContainer() {
- static $container;
- if(!isset($container)){
- include './auth_container_pop3_options.php';
- $container = new Auth_Container_POP3($options);
- }
- return($container);
- }
-
- function &getExtraOptions() {
- include './auth_container_pop3_options.php';
- return($extra_options);
- }
-}
-
-
-
-
-?>
+++ /dev/null
-<?php
-
-include_once 'TestAuthContainer.php';
-include_once 'Auth/Container/POP3.php';
-
-
-class POP3aContainer extends TestAuthContainer {
-
- function POP3aContainer($name){
- $this->TestAuthContainer($name);
- }
-
- function &getContainer() {
- static $container;
- if(!isset($container)){
- include './auth_container_pop3a_options.php';
- $container = new Auth_Container_POP3($options);
- }
- return($container);
- }
-
- function &getExtraOptions() {
- include './auth_container_pop3a_options.php';
- return($extra_options);
- }
-}
-
-
-
-
-?>
+++ /dev/null
-<?php
-
-include_once 'PHPUnit.php';
-
-
-class TestAuthContainer extends PHPUnit_TestCase
-{
-
- var $skip_tests = false;
- var $skip_tests_message = "SKIP TEST";
-
- function TestAuthContainer($name)
- {
- $this->PHPUnit_TestCase($name);
- $this->container =& $this->getContainer();
- $this->user = 'joe';
- $this->pass = 'doe';
- $this->opt = 'VeryCoolUser';
- // Nedded since lazy loading of container was introduced
- $this->container->_auth_obj =& new Auth(&$this);
- }
-
- // Abstract
- function getContainer() {}
- function getExtraOptions() {}
-
- function setUp()
- {
- $opt = $this->getExtraOptions();
- // Add the default user to be used for some testing
- $this->container->addUser($opt['username'], $opt['passwd']);
- }
-
- function tearDown()
- {
- $opt = $this->getExtraOptions();
- // Remove default user
- $this->container->removeUser($opt['username']);
- }
-
- function testListUsers()
- {
- if ($this->skip_tests) {
- $this->fail($this->skip_tests_message.'');
- return(false);
- }
-
- $users = $this->container->listUsers();
- if (AUTH_METHOD_NOT_SUPPORTED === $users) {
- $this->fail('This operation is not supported by '.get_class($this->container));
- return(false);
- }
-
- $opt = $this->getExtraOptions();
- $this->assertTrue(is_array($users[0]), 'First array element from result was not an array');
- $this->assertTrue($users[0]['username'] == $opt['username'], sprintf('First username was not equal to default username "%s" ', $opt['username']));
- }
-
- function testAddUser()
- {
- if ($this->skip_tests) {
- $this->fail($this->skip_tests_message.'');
- return(false);
- }
-
- $cb = count($this->container->listUsers());
- $res = $this->container->addUser($this->user, $this->pass, $this->opt);
- if (AUTH_METHOD_NOT_SUPPORTED === $res) {
- $this->fail("This operation is not supported by ".get_class($this->container));
- return(false);
- }
-
- if (PEAR::isError($res)) {
- $error = $res->getMessage().' ['.$res->getUserInfo().']';
- } else {
- $error = '';
- }
- $this->assertTrue(!PEAR::isError($res), 'error:'.$error);
- $ca = count($this->container->listUsers());
- $users = $this->container->listUsers();
- $last_username = $users[$ca-1]['username'];
- $this->assertTrue( ($cb === $ca-1) , sprintf('Count of users before (%s) and after (%s) does not differ by one', $cb, $ca));
- $this->assertTrue( $this->container->fetchData($this->user, $this->pass) , sprintf('Could not verify with the newly created user %s',$this->user));
-
- // Remove the user we just added, assumes removeUser works
- $this->container->removeUser($this->user);
- }
-
- function testFetchData()
- {
- if ($this->skip_tests) {
- $this->fail($this->skip_tests_message.'');
- return(false);
- }
-
- $opt = $this->getExtraOptions();
- $fetch_res = $this->container->fetchData($opt['username'], $opt['passwd']);
- if (AUTH_METHOD_NOT_SUPPORTED === $fetch_res) {
- $this->fail("This operation is not supported by ".get_class($this->container));
- return(false);
- }
-
- $this->assertTrue($fetch_res,sprintf('Could not verify with the default username (%s) and passwd (%s)', $opt['username'], $opt['passwd']));
-
- // Test for fail fetchData
- $opt = $this->getExtraOptions();
- $this->assertFalse(
- $this->container->fetchData(md5($opt['username']), $opt['passwd']),
- "fetchData returned true with invalid username and pass"
- );
-
- }
-
-
- /**
- * Tjis test depends on add user & remove user to work
- */
- function testFetchDataSpaceInPassword()
- {
-
- if ($this->skip_tests) {
- $this->fail($this->skip_tests_message.'');
- return(false);
- }
-
- $user = uniqid('user');
- $pass = 'Some Pass ';
-
- $res = $this->container->addUser($user, $pass, array());
- if (AUTH_METHOD_NOT_SUPPORTED === $res) {
- $this->fail("This operation is not supported by ".get_class($this->container));
- return(false);
- } else {
- $fetch_res = $this->container->fetchData($user, $pass);
- if (AUTH_METHOD_NOT_SUPPORTED === $fetch_res) {
- $this->fail("This operation is not supported by ".get_class($this->container));
- return(false);
- } else {
- $this->assertTrue($fetch_res, 'Could not verify user with space password');
- }
- }
-
- $remove_res = $this->container->removeUser($user);
- }
-
-
-
-
- function testRemoveUser()
- {
- if ($this->skip_tests) {
- $this->fail($this->skip_tests_message.'');
- return(false);
- }
-
- // Add a user to be removed when testing removeUuser method
- // Assume add user works
- $this->container->addUser('for_remove', 'for_remove');
- $cb = count($this->container->listUsers());
- $remove_res = $this->container->removeUser('for_remove');
- if (AUTH_METHOD_NOT_SUPPORTED === $remove_res) {
- $this->fail("This operation is not supported by ".get_class($this->container));
- return(false);
- }
-
- $this->assertTrue(AUTH_METHOD_NOT_SUPPORTED == $remove_res, "This operation is not supported by ".get_class($this));
- $ca = count($this->container->listUsers());
- $this->assertTrue($cb === $ca+1, sprintf('Could not remove user "%s", count before:%s count after:%s ', 'for_remove', $cb, $ca));
- }
-
-}
-
-?>
+++ /dev/null
-<?php
-
-/*
- $this->options['table'] = "auth";
- $this->options['usernamecol'] = "username";
- $this->options['passwordcol'] = "password";
- $this->options['dsn'] = "";
- $this->options['db_fields'] = "";
- $this->options['cryptType'] = "md5";
-*/
-$options = array(
- 'dsn'=>'mysql://root:@localhost/authtest',
- 'table'=>'temp',
- 'usernamecol'=>'username',
- 'passwordcol'=>'password',
- 'cryptType'=>'md5',
- 'db_fields'=>'*'
-);
-
-$extra_options['username'] = 'test_user';
-$extra_options['passwd'] = 'test_user';
-
-?>
+++ /dev/null
-<?php
-
-$options = 'users';
-
-$extra_options['username'] = 'test_user';
-$extra_options['passwd'] = 'test_user';
-
-?>
+++ /dev/null
-<?php
-/*
-//TEST DATABASE:
------------------------------------------------
-DROP TABLE IF EXISTS temp;
-CREATE TABLE temp (
- username varchar(150) NOT NULL,
- password varchar(200) NOT NULL
-);
------------------------------------------------
-*/
-
-$options = array(
- 'dsn' => 'mysql://root:@localhost/authtest',
- 'table' => 'temp',
- 'usernamecol' => 'username',
- 'passwordcol' => 'password',
- 'db_fields' => '*',
- 'cryptType' => 'md5'
-);
-
-$extra_options['username'] = 'test_user';
-$extra_options['passwd'] = 'test_user';
-
-?>
+++ /dev/null
-<?php
-/*
-//TEST DATABASE:
------------------------------------------------
-DROP TABLE IF EXISTS temp;
-CREATE TABLE temp (
- username varchar(150) NOT NULL,
- password varchar(200) NOT NULL
-);
------------------------------------------------
-*/
-
-$options = array(
- 'dsn' => 'mysql://root:@localhost/authtest',
- 'table' => 'temp',
- 'usernamecol' => 'username',
- 'passwordcol' => 'password',
- 'db_fields' => '*',
- 'cryptType' => 'md5'
-);
-
-$extra_options['username'] = 'test_user';
-$extra_options['passwd'] = 'test_user';
-
-?>
+++ /dev/null
-<?php
-
-$options = array(
- 'host'=>'mail.example.com',
- 'port'=>'110'
-);
-
-$extra_options['username'] = 'test_user';
-$extra_options['passwd'] = 'test_user';
-
-?>
+++ /dev/null
-<?php
-
-$options = 'mail.example.com:110';
-
-$extra_options['username'] = 'test_user';
-$extra_options['passwd'] = 'test_user';
-
-?>
+++ /dev/null
-test:fcfKBtvEwG4g.
+++ /dev/null
---TEST--
-Regression test for bug #8735
---FILE--
-<?php
-set_include_path(dirname(dirname(__FILE__)) . ':' . get_include_path());
-$datasrc = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'bug8735.passwd';
-
-require_once 'PEAR.php';
-require_once 'Auth.php';
-
-$a = new Auth('File',
- array('file' => $datasrc,
- 'type' => 'AuthBasic'),
- 'displayLogin');
-if (PEAR::isError($a)) {
- print $a->getMessage();
- exit;
-}
-
-$error = $a->removeUser('username');
-if (PEAR::isError($error)) {
- print $error->getMessage();
- exit;
-}
-
-readfile($datasrc);
-print "-- cut --\n";
-
-$error = $a->addUser('username', 'password');
-if (PEAR::isError($error) || $error === false) {
- print "Error happened when adding.\n";
- print $error->getMessage();
- exit;
-}
-
-readfile($datasrc);
-
-$a->removeUser('username');
-?>
---EXPECT--
-test:fcfKBtvEwG4g.
--- cut --
-test:fcfKBtvEwG4g.
-username:{SHA}W6ph5Mm5Pz8GgiULbPgzG37mj9g=
+++ /dev/null
-CREATE TABLE `temp` (
- `username` varchar(150) NOT NULL default '',
- `password` varchar(200) NOT NULL default ''
- ) ENGINE=MyISAM DEFAULT CHARSET=latin1;
+++ /dev/null
-<?php
-
-include_once 'Auth.php';
-include_once 'TestAuthContainer.php';
-include_once 'FileContainer.php';
-include_once 'DBContainer.php';
-include_once 'DBLiteContainer.php';
-include_once 'MDBContainer.php';
-include_once 'MDB2Container.php';
-include_once 'POP3Container.php';
-include_once 'POP3aContainer.php';
-include_once 'IMAPContainer.php';
-include_once 'PHPUnit.php';
-
-
-function error($err){
- print "Error\n";
- print "Code:".trim($err->getCode())."\n";
- print "Message:".trim($err->getMessage())."\n";
- #print "UserInfo:".trim($err->getUserInfo())."\n";
- #print "DebugInfo:".trim($err->getDebugInfo())."\n";
-
-}
-
-#error_reporting(0);
-PEAR::setErrorHandling(PEAR_ERROR_PRINT, "\nPear Error:%s \n");
-#PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, "error");
-
-set_time_limit(0);
-
-$suite = new PHPUnit_TestSuite();
-
-// File Container
-#$suite->addTest(new PHPUnit_TestSuite('IMAPContainer'));
-$suite->addTest(new PHPUnit_TestSuite('FileContainer'));
-$suite->addTest(new PHPUnit_TestSuite('DBContainer'));
-//$suite->addTest(new PHPUnit_TestSuite('DBLiteContainer'));
-// MDB Container
-$suite->addTest(new PHPUnit_TestSuite('MDBContainer'));
-// MDB2 Container
-$suite->addTest(new PHPUnit_TestSuite('MDB2Container'));
-// POP3 Container
-$suite->addTest(new PHPUnit_TestSuite('POP3Container'));
-
-$result = PHPUnit::run($suite);
-echo $result->toString();
-
-?>
HTTP_Session2::start();
if ($catid == ORDER_FORM_PAGE) {
- //include 'priceQuoteForm.inc';
+ include 'priceQuoteForm.inc';
}
require_once 'setup_functions.phtml';
);
$glmPage->fetchPage();
ob_start();
- //echo $wizard->run();
+ echo $wizard->run();
$glmPage->toolboxContent = ob_get_contents();
ob_end_clean();
<?php
require_once 'HTML/QuickForm/Controller.php';
+require_once 'HTML/QuickForm/Page2.php';
require_once 'HTML/QuickForm/ElementGrid.php';
// Load some default action handlers
function checkCountryState($data)
{
- if (!empty($data[0]) && !empty($data[1])) {
- if ($data[1] == 'USA') {
- // Make sure the state is actually a state.
- return array_key_exists($data[0], $GLOBALS['states_US']);
- } else {
- // Make sure the province is NOT a state.
- return !array_key_exists($data[0], $GLOBALS['states_US']);
- }
- }
- return true;
+ if (!empty($data[0]) && !empty($data[1])) {
+ if ($data[1] == 'USA') {
+ // Make sure the state is actually a state.
+ return array_key_exists($data[0], $GLOBALS['states_US']);
+ } else {
+ // Make sure the province is NOT a state.
+ return !array_key_exists($data[0], $GLOBALS['states_US']);
+ }
+ }
+ return true;
}
function date_difference($m0, $d0, $y0, $m1, $d1, $y1)
{
- $arrival = gregoriantojd($m0, $d0, $y0);
- $departure = gregoriantojd($m1, $d1, $y1);
+ $arrival = gregoriantojd($m0, $d0, $y0);
+ $departure = gregoriantojd($m1, $d1, $y1);
- $diff = $departure - $arrival;
+ $diff = $departure - $arrival;
- return $diff;
+ return $diff;
}
-class PageBase extends HTML_QuickForm_Page
+class PageBase extends HTML_QuickForm_Page2
{
- // If you change the target to use the a variable from the $_SERVER
- // array, the page will not process past the 2nd form.
- function __construct($formName, $method = 'post', $target = 'index.php?catid=9', $attributes = null)
- {
- //$target = ($_POST['_qf_default'] == 'page2:next') ? $target . '&_qf_page2_display=true' : $target;
- parent::__construct($formName, $method, MEDIA_BASE_URL . $target, $attributes);
- $this->_validationType = 'server';
- $this->_partySize = array('' => '-- Select Size --') + range(0, 10);
- }
-
- protected function _setupElements($elements)
- {
- $this->formElements = $elements;
- foreach ($elements as $e) {
- switch ($e['type']) {
- case 'group' :
- if (is_array($e['group'])) {
- unset($field);
- foreach ($e['group'] as $g) {
- $field[] =& HTML_QuickForm::createElement($g['type'], $g['name'], $g['display'], $g['opts'], $g['att'], $g['val']);
- }
- $source =& $this->addGroup($field, $e['name'], $e['label'], $e['separator'], $e['appendName']);
- }
- break;
-
- case 'html' :
- if (isset($e['name'], $e['display'])) {
- $source =& $this->addElement($e['type'], $e['name'], $e['display']);
- } else {
- $this->addElement($e['type'], $e['display']);
- }
- break;
-
- default :
- $source =& $this->addElement($e['type'], $e['name'], $e['display'], $e['opts'], $e['att'], $e['val']);
- if ($e['type'] == 'advmultiselect') {
- $source->setLabel($e['labels']);
- }
- break;
- }
- }
- }
-
- protected function _setupRules(array $rules = null)
- {
- if (is_array($rules)) {
- foreach ($rules as $r) {
- $this->addRule($r['element'], $r['message'], $r['type'], $r['format'], $r['validation'], $r['reset'], $r['force']);
- }
- }
-
- foreach ($this->formElements as $e) {
- if ($e['req']) {
- $this->addRule($e['name'],
- 'ERROR: You must complete this field!',
- 'required', null, $this->_validationType
- );
- }
- }
- }
-
- protected function _setupFilters($filters)
- {
- foreach ($filters as $f) {
- $this->applyFilter($f['element'], $f['filter']);
- }
- }
+ // If you change the target to use the a variable from the $_SERVER
+ // array, the page will not process past the 2nd form.
+ function __construct($formName, $method = 'post', $target = 'index.php?catid=9', $attributes = null)
+ {
+ //$target = ($_POST['_qf_default'] == 'page2:next') ? $target . '&_qf_page2_display=true' : $target;
+ parent::__construct($formName, $method, MEDIA_BASE_URL . $target, $attributes);
+ $this->_validationType = 'server';
+ $this->_partySize = array('' => '-- Select Size --') + range(0, 10);
+ }
+
+ protected function _setupElements($elements)
+ {
+ $this->formElements = $elements;
+ foreach ($elements as $e) {
+ switch ($e['type']) {
+ case 'group' :
+ if (is_array($e['group'])) {
+ unset($field);
+ foreach ($e['group'] as $g) {
+ $field[] =& HTML_QuickForm::createElement($g['type'], $g['name'], $g['display'], $g['opts'], $g['att'], $g['val']);
+ }
+ $source =& $this->addGroup($field, $e['name'], $e['label'], $e['separator'], $e['appendName']);
+ }
+ break;
+
+ case 'html' :
+ if (isset($e['name'], $e['display'])) {
+ $source =& $this->addElement($e['type'], $e['name'], $e['display']);
+ } else {
+ $this->addElement($e['type'], $e['display']);
+ }
+ break;
+
+ default :
+ $source =& $this->addElement($e['type'], $e['name'], $e['display'], $e['opts'], $e['att'], $e['val']);
+ if ($e['type'] == 'advmultiselect') {
+ $source->setLabel($e['labels']);
+ }
+ break;
+ }
+ }
+ }
+
+ protected function _setupRules(array $rules = null)
+ {
+ if (is_array($rules)) {
+ foreach ($rules as $r) {
+ $this->addRule($r['element'], $r['message'], $r['type'], $r['format'], $r['validation'], $r['reset'], $r['force']);
+ }
+ }
+
+ foreach ($this->formElements as $e) {
+ if ($e['req']) {
+ $this->addRule($e['name'],
+ 'ERROR: You must complete this field!',
+ 'required', null, $this->_validationType
+ );
+ }
+ }
+ }
+
+ protected function _setupFilters($filters)
+ {
+ foreach ($filters as $f) {
+ $this->applyFilter($f['element'], $f['filter']);
+ }
+ }
}
class PageFirst extends PageBase
{
$this->_formBuilt = true;
- $nextWeek = mktime(0, 0, 0, date('m'), date('d') + 7, date('Y'));
- $defaults = array(
- 'arrival' => array('m' => date('m'), 'd' => date('d'), 'Y' => date('Y')),
- 'departure' => array('m' => date('m', $nextWeek), 'd' => date('d', $nextWeek), 'Y' => date('Y', $nextWeek)),
- );
- $golfers = array('' => '-- Select --') + range(0, 20);
-
- $elements[] = array('type' => 'header', 'req' => false, 'name' => 'header_rmv', 'display' => 'Package Price Quote Request page 1 of 4');
- $elements[] = array('type' => 'date', 'req' => true, 'name' => 'arrival', 'display' => 'Arrival:', 'opts' => array('format' => 'm / d / Y', 'minYear' => date('Y'), 'maxYear' => date('Y')+1));
- $elements[] = array('type' => 'date', 'req' => true, 'name' => 'departure', 'display' => 'Departure:', 'opts' => array('format' => 'm / d / Y', 'minYear' => date('Y'), 'maxYear' => date('Y')+1));
- $elements[] = array('type' => 'select', 'req' => true, 'name' => 'golfers', 'display' => 'Number of golfers:', 'opts' => $golfers);
- $elements[] = array('type' => 'select', 'req' => true, 'name' => 'nongolfers', 'display' => 'Number of non-golfers:', 'opts' => $golfers);
- $elements[] = array('type' => 'submit', 'req' => false, 'name' => $this->getButtonName('next'), 'display' => 'Next step >>');
-
- $rules[] = array('element' => array('arrival', 'departure'), 'message' => 'ERROR: Arrival date must preceed your Departure!', 'type' => 'callback', 'format' => 'check_dates', 'validation' => $this->_validationType, 'reset' => true, 'force' => false);
- $rules[] = array('element' => 'arrival', 'message' => 'ERROR: Invalid Date!', 'type' => 'callback', 'format' => 'check_date', 'validation' => $this->_validationType, 'reset' => true, 'force' => false);
- $rules[] = array('element' => 'departure', 'message' => 'ERROR: Invalid Date!', 'type' => 'callback', 'format' => 'check_date', 'validation' => $this->_validationType, 'reset' => true, 'force' => false);
-
- $filters[] = array('element' => '__ALL__', 'filter' => 'trim');
-
- $this->_setupElements($elements);
- $this->_setupRules($rules);
- $this->_setupFilters($filters);
- $this->setDefaults($defaults);
+ $nextWeek = mktime(0, 0, 0, date('m'), date('d') + 7, date('Y'));
+ $defaults = array(
+ 'arrival' => array('m' => date('m'), 'd' => date('d'), 'Y' => date('Y')),
+ 'departure' => array('m' => date('m', $nextWeek), 'd' => date('d', $nextWeek), 'Y' => date('Y', $nextWeek)),
+ );
+ $golfers = array('' => '-- Select --') + range(0, 20);
+
+ $elements[] = array('type' => 'header', 'req' => false, 'name' => 'header_rmv', 'display' => 'Package Price Quote Request page 1 of 4');
+ $elements[] = array('type' => 'date', 'req' => true, 'name' => 'arrival', 'display' => 'Arrival:', 'opts' => array('format' => 'm / d / Y', 'minYear' => date('Y'), 'maxYear' => date('Y')+1));
+ $elements[] = array('type' => 'date', 'req' => true, 'name' => 'departure', 'display' => 'Departure:', 'opts' => array('format' => 'm / d / Y', 'minYear' => date('Y'), 'maxYear' => date('Y')+1));
+ $elements[] = array('type' => 'select', 'req' => true, 'name' => 'golfers', 'display' => 'Number of golfers:', 'opts' => $golfers);
+ $elements[] = array('type' => 'select', 'req' => true, 'name' => 'nongolfers', 'display' => 'Number of non-golfers:', 'opts' => $golfers);
+ $elements[] = array('type' => 'submit', 'req' => false, 'name' => $this->getButtonName('next'), 'display' => 'Next step >>');
+
+ $rules[] = array('element' => array('arrival', 'departure'), 'message' => 'ERROR: Arrival date must preceed your Departure!', 'type' => 'callback', 'format' => 'check_dates', 'validation' => $this->_validationType, 'reset' => true, 'force' => false);
+ $rules[] = array('element' => 'arrival', 'message' => 'ERROR: Invalid Date!', 'type' => 'callback', 'format' => 'check_date', 'validation' => $this->_validationType, 'reset' => true, 'force' => false);
+ $rules[] = array('element' => 'departure', 'message' => 'ERROR: Invalid Date!', 'type' => 'callback', 'format' => 'check_date', 'validation' => $this->_validationType, 'reset' => true, 'force' => false);
+
+ $filters[] = array('element' => '__ALL__', 'filter' => 'trim');
+
+ $this->_setupElements($elements);
+ $this->_setupRules($rules);
+ $this->_setupFilters($filters);
+ $this->setDefaults($defaults);
$this->setDefaultAction('next');
}
}
{
$this->_formBuilt = true;
- $golfers= $this->controller->exportValue('page1', 'golfers');
- $nongolfers = $this->controller->exportValue('page1', 'nongolfers');
-
- $attendees = $golfers + $nongolfers;
-
- $couples = ($attendees % 2) ? (($attendees - 1) / 2) : ($attendees / 2);
- $couples = array('' => '-- Select --') + range(0, $couples);
- $singles = array('' => '-- Select --') + range(0, $attendees);
- $accomodations = array('' => '-- Select --') + range(0, $attendees);
- $bathrooms = range(1, $attendees);
- foreach ($bathrooms as $k => $v)
- {
- $temp[++$k] = $v;
- }
- unset($bathrooms);
- $bathrooms = $temp;
- unset($temp);
-
- $lodging[] = array('type' => 'radio', 'req' => true, 'name' => 'lodging', 'display' => null, 'opts' => 'Hamlet Village', 'att' => 'Hamlet Village Condominiums');
- $lodging[] = array('type' => 'radio', 'req' => true, 'name' => 'lodging', 'display' => null, 'opts' => 'Trout Creek', 'att' => 'Trout Creek Condominiums');
-
- $bedOptions[] = array('type' => 'checkbox', 'req' => false, 'name' => 'twin', 'display' => null, 'opts' => 'Twin Bed is OK');
- $bedOptions[] = array('type' => 'checkbox', 'req' => false, 'name' => 'sleeper', 'display' => null, 'opts' => 'Sleeper Sofa is OK');
-
- $elements[] = array('type' => 'header', 'req' => false, 'name' => 'header_rmv', 'display' => 'Package Price Quote Request page 2 of 4');
- $elements[] = array('type' => 'group', 'req' => true, 'name' => 'accommodation', 'group' => $lodging, 'label' => 'Lodging:', 'appendName' => false);
- $elements[] = array('type' => 'select', 'req' => true, 'name' => 'couples', 'display' => 'Number of Couples:', 'opts' => $couples);
- $elements[] = array('type' => 'select', 'req' => true, 'name' => 'singles', 'display' => 'Number of Singles:', 'opts' => $singles);
- $elements[] = array('type' => 'select', 'req' => false, 'name' => 'bathrooms', 'display' => 'Number of Bathrooms:','opts' => $bathrooms);
- $elements[] = array('type' => 'header', 'req' => false, 'name' => 'accomodation_rmv', 'display' => 'Accommodation Type Preference');
- $elements[] = array('type' => 'select', 'req' => true, 'name' => 'rooms', 'display' => 'Number of Rooms:', 'opts' => $accomodations);
- $elements[] = array('type' => 'select', 'req' => true, 'name' => 'beds', 'display' => 'Number of Beds:', 'opts' => $accomodations);
- $elements[] = array('type' => 'group', 'req' => false, 'name' => 'bedOptions', 'group' => $bedOptions, 'label' => 'Bed Options:', 'separator' => '<br>', 'appendName' => false);
+ $golfers= $this->controller->exportValue('page1', 'golfers');
+ $nongolfers = $this->controller->exportValue('page1', 'nongolfers');
+
+ $attendees = $golfers + $nongolfers;
+
+ $couples = ($attendees % 2) ? (($attendees - 1) / 2) : ($attendees / 2);
+ $couples = array('' => '-- Select --') + range(0, $couples);
+ $singles = array('' => '-- Select --') + range(0, $attendees);
+ $accomodations = array('' => '-- Select --') + range(0, $attendees);
+ $bathrooms = range(1, $attendees);
+ foreach ($bathrooms as $k => $v)
+ {
+ $temp[++$k] = $v;
+ }
+ unset($bathrooms);
+ $bathrooms = $temp;
+ unset($temp);
+
+ $lodging[] = array('type' => 'radio', 'req' => true, 'name' => 'lodging', 'display' => null, 'opts' => 'Hamlet Village', 'att' => 'Hamlet Village Condominiums');
+ $lodging[] = array('type' => 'radio', 'req' => true, 'name' => 'lodging', 'display' => null, 'opts' => 'Trout Creek', 'att' => 'Trout Creek Condominiums');
+
+ $bedOptions[] = array('type' => 'checkbox', 'req' => false, 'name' => 'twin', 'display' => null, 'opts' => 'Twin Bed is OK');
+ $bedOptions[] = array('type' => 'checkbox', 'req' => false, 'name' => 'sleeper', 'display' => null, 'opts' => 'Sleeper Sofa is OK');
+
+ $elements[] = array('type' => 'header', 'req' => false, 'name' => 'header_rmv', 'display' => 'Package Price Quote Request page 2 of 4');
+ $elements[] = array('type' => 'group', 'req' => true, 'name' => 'accommodation', 'group' => $lodging, 'label' => 'Lodging:', 'appendName' => false);
+ $elements[] = array('type' => 'select', 'req' => true, 'name' => 'couples', 'display' => 'Number of Couples:', 'opts' => $couples);
+ $elements[] = array('type' => 'select', 'req' => true, 'name' => 'singles', 'display' => 'Number of Singles:', 'opts' => $singles);
+ $elements[] = array('type' => 'select', 'req' => false, 'name' => 'bathrooms', 'display' => 'Number of Bathrooms:','opts' => $bathrooms);
+ $elements[] = array('type' => 'header', 'req' => false, 'name' => 'accomodation_rmv', 'display' => 'Accommodation Type Preference');
+ $elements[] = array('type' => 'select', 'req' => true, 'name' => 'rooms', 'display' => 'Number of Rooms:', 'opts' => $accomodations);
+ $elements[] = array('type' => 'select', 'req' => true, 'name' => 'beds', 'display' => 'Number of Beds:', 'opts' => $accomodations);
+ $elements[] = array('type' => 'group', 'req' => false, 'name' => 'bedOptions', 'group' => $bedOptions, 'label' => 'Bed Options:', 'separator' => '<br>', 'appendName' => false);
$prevnext[] =& $this->createElement('submit', $this->getButtonName('next'), 'Next step >>');
- $filters[] = array('element' => '__ALL__', 'filter' => 'trim');
+ $filters[] = array('element' => '__ALL__', 'filter' => 'trim');
- $this->_setupElements($elements);
- $this->_setupRules();
+ $this->_setupElements($elements);
+ $this->_setupRules();
$this->addGroup($prevnext, 'control_buttons', '', ' ', false);
- $this->_setupFilters($filters);
+ $this->_setupFilters($filters);
$this->setDefaultAction('next');
- $defaults = array(
- 'couples' => '',
- 'singles' => '',
- 'rooms' => '',
- 'beds' =>'',
- );
- $this->setDefaults($defaults);
+ $defaults = array(
+ 'couples' => '',
+ 'singles' => '',
+ 'rooms' => '',
+ 'beds' =>'',
+ );
+ $this->setDefaults($defaults);
}
}
{
$this->_formBuilt = true;
- $arrival = $this->controller->exportValue('page1', 'arrival');
- $departure = $this->controller->exportValue('page1', 'departure');
- list($arrivalMonth, $arrivalDay, $arrivalYear) = array_values($arrival);
- list($departureMonth, $departureDay, $departureYear) = array_values($departure);
-
- $vacationLength = date_difference(
- $arrivalMonth,
- $arrivalDay,
- $arrivalYear,
- $departureMonth,
- $departureDay,
- $departureYear
- );
-
- $morning = array(
- 'Any Time' => '-- Anytime --',
- '07:00 am' => '07:00 am',
- '07:30 am' => '07:30 am',
- '08:00 am' => '08:00 am',
- '08:30 am' => '08:30 am',
- '09:00 am' => '09:00 am',
- '09:30 am' => '09:30 am',
- '10:00 am' => '10:00 am',
- '10:30 am' => '10:30 am',
- '11:00 am' => '11:00 am',
- '11:30 am' => '11:30 am',
- );
-
- $evening = array(
- 'Any Time' => '-- Anytime --',
- '12:00 noon' => '12:00 noon',
- '12:30 pm' => '12:30 pm',
- '01:00 pm' => '01:00 pm',
- '01:30 pm' => '01:30 pm',
- '02:00 pm' => '02:00 pm',
- '02:30 pm' => '02:30 pm',
- '03:00 pm' => '03:00 pm',
- '03:30 pm' => '03:30 pm',
- '04:00 pm' => '04:00 pm',
- );
-
- $golfers = array('0' => '-- None --') + range(0, $this->controller->exportValue('page1', 'golfers'));
-
- $courses = array(
- '' => '-- Select --',
+ $arrival = $this->controller->exportValue('page1', 'arrival');
+ $departure = $this->controller->exportValue('page1', 'departure');
+ list($arrivalMonth, $arrivalDay, $arrivalYear) = array_values($arrival);
+ list($departureMonth, $departureDay, $departureYear) = array_values($departure);
+
+ $vacationLength = date_difference(
+ $arrivalMonth,
+ $arrivalDay,
+ $arrivalYear,
+ $departureMonth,
+ $departureDay,
+ $departureYear
+ );
+
+ $morning = array(
+ 'Any Time' => '-- Anytime --',
+ '07:00 am' => '07:00 am',
+ '07:30 am' => '07:30 am',
+ '08:00 am' => '08:00 am',
+ '08:30 am' => '08:30 am',
+ '09:00 am' => '09:00 am',
+ '09:30 am' => '09:30 am',
+ '10:00 am' => '10:00 am',
+ '10:30 am' => '10:30 am',
+ '11:00 am' => '11:00 am',
+ '11:30 am' => '11:30 am',
+ );
+
+ $evening = array(
+ 'Any Time' => '-- Anytime --',
+ '12:00 noon' => '12:00 noon',
+ '12:30 pm' => '12:30 pm',
+ '01:00 pm' => '01:00 pm',
+ '01:30 pm' => '01:30 pm',
+ '02:00 pm' => '02:00 pm',
+ '02:30 pm' => '02:30 pm',
+ '03:00 pm' => '03:00 pm',
+ '03:30 pm' => '03:30 pm',
+ '04:00 pm' => '04:00 pm',
+ );
+
+ $golfers = array('0' => '-- None --') + range(0, $this->controller->exportValue('page1', 'golfers'));
+
+ $courses = array(
+ '' => '-- Select --',
'Belvedere Golf Club' => 'Belvedere Golf Club',
- 'Dunmaglas' => 'Dunmaglas',
- 'Little Traverse Bay' => 'Little Traverse Bay',
- 'Black Lake' => 'Black Lake'
- );
+ 'Dunmaglas' => 'Dunmaglas',
+ 'Little Traverse Bay' => 'Little Traverse Bay',
+ 'Black Lake' => 'Black Lake'
+ );
- $tos = 'Tee Times are requests only and subject to change based on course availability and travel time between courses.';
+ $tos = 'Tee Times are requests only and subject to change based on course availability and travel time between courses.';
- $elements[] = array('type' => 'header', 'req' => false, 'name' => 'header_rmv', 'display' => 'Package Price Quote Request page 3 of 4');
- $elements[] = array('type' => 'static', 'req' => false, 'name' => 'tos_rmv', 'display' => 'Terms of Service:', 'opts' => $tos);
- $elements[] = array('type' => 'static', 'req' => false, 'name' => 'view_courses_rmv', 'display' => 'Click here to view course<br>desriptions and locations:', 'opts' => '<a id="viewCourses" target="_blank" href="'.BASE_URL.'courses-11/">View Courses</a>');
- $elements[] = array('type' => 'elementGrid', 'req' => false, 'name' => 'golfing', 'display' => 'Golfing Preference:', 'opts' => array('actAsGroup' => false));
+ $elements[] = array('type' => 'header', 'req' => false, 'name' => 'header_rmv', 'display' => 'Package Price Quote Request page 3 of 4');
+ $elements[] = array('type' => 'static', 'req' => false, 'name' => 'tos_rmv', 'display' => 'Terms of Service:', 'opts' => $tos);
+ $elements[] = array('type' => 'static', 'req' => false, 'name' => 'view_courses_rmv', 'display' => 'Click here to view course<br>desriptions and locations:', 'opts' => '<a id="viewCourses" target="_blank" href="'.BASE_URL.'courses-11/">View Courses</a>');
+ $elements[] = array('type' => 'elementGrid', 'req' => false, 'name' => 'golfing', 'display' => 'Golfing Preference:', 'opts' => array('actAsGroup' => false));
$prevnext[] =& $this->createElement('submit', $this->getButtonName('next'), 'Next step >>');
- $filters[] = array('element' => '__ALL__', 'filter' => 'trim');
+ $filters[] = array('element' => '__ALL__', 'filter' => 'trim');
- foreach ($elements as $e) {
- $source =& $this->addElement($e['type'], $e['name'], $e['display'], $e['opts'], $e['att'], $e['val']);
+ foreach ($elements as $e) {
+ $source =& $this->addElement($e['type'], $e['name'], $e['display'], $e['opts'], $e['att'], $e['val']);
- if ($e['name'] == 'golfing') {
- $columnNames = array(
- 'No. Golfers',
- 'Tee Time',
- 'Golf Course',
- );
- $source->setColumnNames($columnNames);
+ if ($e['name'] == 'golfing') {
+ $columnNames = array(
+ 'No. Golfers',
+ 'Tee Time',
+ 'Golf Course',
+ );
+ $source->setColumnNames($columnNames);
- $date = gregoriantojd($arrivalMonth, $arrivalDay, $arrivalYear);
- for ($i = 0; $i <= $vacationLength; ++$i) {
- unset($amgolf);
- unset($pmgolf);
+ $date = gregoriantojd($arrivalMonth, $arrivalDay, $arrivalYear);
+ for ($i = 0; $i <= $vacationLength; ++$i) {
+ unset($amgolf);
+ unset($pmgolf);
- $calDate = cal_from_jd($date++, CAL_GREGORIAN);
+ $calDate = cal_from_jd($date++, CAL_GREGORIAN);
- $amgolf[] =& $this->createElement('select', "amGolfers$i", null, $golfers);
- $amgolf[] =& $this->createElement('select', "amTeeTime$i", null, $morning);
- $amgolf[] =& $this->createElement('select', "amCourse$i", null, $courses);
+ $amgolf[] =& $this->createElement('select', "amGolfers$i", null, $golfers);
+ $amgolf[] =& $this->createElement('select', "amTeeTime$i", null, $morning);
+ $amgolf[] =& $this->createElement('select', "amCourse$i", null, $courses);
- $pmgolf[] =& $this->createElement('select', "pmGolfers$i", null, $golfers);
- $pmgolf[] =& $this->createElement('select', "pmTeeTime$i", null, $evening);
- $pmgolf[] =& $this->createElement('select', "pmCourse$i", null, $courses);
+ $pmgolf[] =& $this->createElement('select', "pmGolfers$i", null, $golfers);
+ $pmgolf[] =& $this->createElement('select', "pmTeeTime$i", null, $evening);
+ $pmgolf[] =& $this->createElement('select', "pmCourse$i", null, $courses);
- $source->addRow($amgolf, $calDate['date']);
- $source->addRow($pmgolf, ' ');
- }
- }
- }
+ $source->addRow($amgolf, $calDate['date']);
+ $source->addRow($pmgolf, ' ');
+ }
+ }
+ }
$this->addGroup($prevnext, 'control_buttons', '', ' ', false);
- $this->_setupFilters($filters);
+ $this->_setupFilters($filters);
$this->setDefaultAction('next');
}
}
{
$this->_formBuilt = true;
- $arrival = $this->controller->exportValue('page1', 'arrival');
- $departure = $this->controller->exportValue('page1', 'departure');
- list($arrivalMonth, $arrivalDay, $arrivalYear) = array_values($arrival);
- list($departureMonth, $departureDay, $departureYear) = array_values($departure);
-
- $vacationLength = date_difference(
- $arrivalMonth,
- $arrivalDay,
- $arrivalYear,
- $departureMonth,
- $departureDay,
- $departureYear
- );
-
- $reservationTime = array(
- '' => '-- Select --',
- '5:00 pm' => '5:00 pm',
- '5:30 pm' => '5:30 pm',
- '6:00 pm' => '6:00 pm',
- '6:30 pm' => '6:30 pm',
- '7:00 pm' => '7:00 pm',
- '7:30 pm' => '7:30 pm',
- '8:00 pm' => '8:00 pm',
- '8:30 pm' => '8:30 pm',
- '9:00 pm' => '9:00 pm',
- );
-
- $locations = array(
- '' => '-- Select --',
- 'Black Lake Golf Club' => 'Black Lake Golf Club',
- 'Little Traverse Bay' => 'Little Traverse Bay'
- );
-
- $states = array('' => '-- Select --') + $GLOBALS['states'];
- unset(
- $states['Asia'],
- $states['Australia'],
- $states['Bahamas'],
- $states['Caribbean'],
- $states['Costa Rica'],
- $states['South America'],
- $states['South Africa'],
- $states['Europe'],
- $states['Mexico']
- );
-
- try {
- $dns = 'pgsql:' . CONN_STR;
- $dbh = Toolkit_Database::getInstance();
-
- $sql = "
+ $arrival = $this->controller->exportValue('page1', 'arrival');
+ $departure = $this->controller->exportValue('page1', 'departure');
+ list($arrivalMonth, $arrivalDay, $arrivalYear) = array_values($arrival);
+ list($departureMonth, $departureDay, $departureYear) = array_values($departure);
+
+ $vacationLength = date_difference(
+ $arrivalMonth,
+ $arrivalDay,
+ $arrivalYear,
+ $departureMonth,
+ $departureDay,
+ $departureYear
+ );
+
+ $reservationTime = array(
+ '' => '-- Select --',
+ '5:00 pm' => '5:00 pm',
+ '5:30 pm' => '5:30 pm',
+ '6:00 pm' => '6:00 pm',
+ '6:30 pm' => '6:30 pm',
+ '7:00 pm' => '7:00 pm',
+ '7:30 pm' => '7:30 pm',
+ '8:00 pm' => '8:00 pm',
+ '8:30 pm' => '8:30 pm',
+ '9:00 pm' => '9:00 pm',
+ );
+
+ $locations = array(
+ '' => '-- Select --',
+ 'Black Lake Golf Club' => 'Black Lake Golf Club',
+ 'Little Traverse Bay' => 'Little Traverse Bay'
+ );
+
+ $states = array('' => '-- Select --') + $GLOBALS['states'];
+ unset(
+ $states['Asia'],
+ $states['Australia'],
+ $states['Bahamas'],
+ $states['Caribbean'],
+ $states['Costa Rica'],
+ $states['South America'],
+ $states['South Africa'],
+ $states['Europe'],
+ $states['Mexico']
+ );
+
+ try {
+ $dns = 'pgsql:' . CONN_STR;
+ $dbh = Toolkit_Database::getInstance();
+
+ $sql = "
SELECT *
FROM contact_inq
ORDER BY pos ASC";
- $stmt = $dbh->prepare($sql);
- $stmt->execute();
-
- while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
- $discovery[$row['header']] = $row['header'];
- }
-
- $discovery = array('' => '-- Select --') + $discovery;
- unset($dbh);
- unset($stmt);
- } catch (PDOException $e) {
- unset($dbh);
- unset($stmt);
- echo 'PDO Exception Caught. ';
- echo 'Error with the database:<br>';
- echo 'Error: ' . $e->getMessage() . '<br>';
- echo 'File: ' . $e->getFile() . '<br>';
- echo 'Line: ' . $e->getLine() . '<br>';
- }
-
-// $elements[] = array('type' => 'header', 'req' => false, 'name' => 'header_rmv', 'display' => 'Package Price Quote Request page 4 of 4');
-// $elements[] = array('type' => 'elementGrid', 'req' => false, 'name' => 'dining', 'display' => 'Dining Preference:', 'opts' => array('actAsGroup' => false));
- $elements[] = array('type' => 'header', 'req' => false, 'name' => 'cust_info_rmv', 'display' => 'Customer Information');
- $elements[] = array('type' => 'text', 'req' => true, 'name' => 'fname', 'display' => 'First Name:');
- $elements[] = array('type' => 'text', 'req' => true, 'name' => 'lname', 'display' => 'Last Name:');
- $elements[] = array('type' => 'text', 'req' => false, 'name' => 'address', 'display' => 'Address:');
- $elements[] = array('type' => 'text', 'req' => false, 'name' => 'city', 'display' => 'City:');
- $elements[] = array('type' => 'select', 'req' => false, 'name' => 'state', 'display' => 'State / Province:', 'opts' => $states);
- $elements[] = array('type' => 'select', 'req' => false, 'name' => 'country', 'display' => 'Country:', 'opts' => array('' => '-- Select --', 'USA' => 'USA', 'Canada' => 'Canada'));
- $elements[] = array('type' => 'text', 'req' => false, 'name' => 'zip', 'display' => 'Zip Code / Postal Code:');
- $elements[] = array('type' => 'text', 'req' => false, 'name' => 'phone', 'display' => 'Primary Phone:');
- $elements[] = array('type' => 'text', 'req' => false, 'name' => 'alt_phone', 'display' => 'Secondary Phone:');
- $elements[] = array('type' => 'text', 'req' => true, 'name' => 'email', 'display' => 'Email:');
- $elements[] = array('type' => 'text', 'req' => true, 'name' => 'email_rmv', 'display' => 'Confirm Email Address:');
- $elements[] = array('type' => 'textarea', 'req' => false, 'name' => 'comments', 'display' => 'Special Requests/Comments:', 'opts' => array('rows' => 10, 'cols' => 37));
- $elements[] = array('type' => 'select', 'req' => true, 'name' => 'discovery', 'display' => 'How did you hear of Big Fore:', 'opts' => $discovery);
+ $stmt = $dbh->prepare($sql);
+ $stmt->execute();
+
+ while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+ $discovery[$row['header']] = $row['header'];
+ }
+
+ $discovery = array('' => '-- Select --') + $discovery;
+ unset($dbh);
+ unset($stmt);
+ } catch (PDOException $e) {
+ unset($dbh);
+ unset($stmt);
+ echo 'PDO Exception Caught. ';
+ echo 'Error with the database:<br>';
+ echo 'Error: ' . $e->getMessage() . '<br>';
+ echo 'File: ' . $e->getFile() . '<br>';
+ echo 'Line: ' . $e->getLine() . '<br>';
+ }
+
+// $elements[] = array('type' => 'header', 'req' => false, 'name' => 'header_rmv', 'display' => 'Package Price Quote Request page 4 of 4');
+// $elements[] = array('type' => 'elementGrid', 'req' => false, 'name' => 'dining', 'display' => 'Dining Preference:', 'opts' => array('actAsGroup' => false));
+ $elements[] = array('type' => 'header', 'req' => false, 'name' => 'cust_info_rmv', 'display' => 'Customer Information');
+ $elements[] = array('type' => 'text', 'req' => true, 'name' => 'fname', 'display' => 'First Name:');
+ $elements[] = array('type' => 'text', 'req' => true, 'name' => 'lname', 'display' => 'Last Name:');
+ $elements[] = array('type' => 'text', 'req' => false, 'name' => 'address', 'display' => 'Address:');
+ $elements[] = array('type' => 'text', 'req' => false, 'name' => 'city', 'display' => 'City:');
+ $elements[] = array('type' => 'select', 'req' => false, 'name' => 'state', 'display' => 'State / Province:', 'opts' => $states);
+ $elements[] = array('type' => 'select', 'req' => false, 'name' => 'country', 'display' => 'Country:', 'opts' => array('' => '-- Select --', 'USA' => 'USA', 'Canada' => 'Canada'));
+ $elements[] = array('type' => 'text', 'req' => false, 'name' => 'zip', 'display' => 'Zip Code / Postal Code:');
+ $elements[] = array('type' => 'text', 'req' => false, 'name' => 'phone', 'display' => 'Primary Phone:');
+ $elements[] = array('type' => 'text', 'req' => false, 'name' => 'alt_phone', 'display' => 'Secondary Phone:');
+ $elements[] = array('type' => 'text', 'req' => true, 'name' => 'email', 'display' => 'Email:');
+ $elements[] = array('type' => 'text', 'req' => true, 'name' => 'email_rmv', 'display' => 'Confirm Email Address:');
+ $elements[] = array('type' => 'textarea', 'req' => false, 'name' => 'comments', 'display' => 'Special Requests/Comments:', 'opts' => array('rows' => 10, 'cols' => 37));
+ $elements[] = array('type' => 'select', 'req' => true, 'name' => 'discovery', 'display' => 'How did you hear of Big Fore:', 'opts' => $discovery);
$prevnext[] =& $this->createElement('submit', $this->getButtonName('next'), 'Finish');
- $rules[] = array('element' => 'email', 'message' => 'Error: Invalid email address!', 'type' => 'email', 'format' => null, 'validation' => $this->_validationType, 'reset' => false, 'force' => false);
- $rules[] = array('element' => array('email', 'email_rmv'), 'message' => 'Error: Your email addresses do not match!', 'type' => 'compare', 'format' => null, 'validation' => $this->_validationType, 'reset' => true, 'force' => false);
- $rules[] = array('element' => array('state', 'country'), 'message' => 'Error: Your state / province does not match your country!', 'type' => 'callback', 'format' => 'checkCountryState', 'validation' => $this->_validationType, 'reset' => true, 'force' => false);
+ $rules[] = array('element' => 'email', 'message' => 'Error: Invalid email address!', 'type' => 'email', 'format' => null, 'validation' => $this->_validationType, 'reset' => false, 'force' => false);
+ $rules[] = array('element' => array('email', 'email_rmv'), 'message' => 'Error: Your email addresses do not match!', 'type' => 'compare', 'format' => null, 'validation' => $this->_validationType, 'reset' => true, 'force' => false);
+ $rules[] = array('element' => array('state', 'country'), 'message' => 'Error: Your state / province does not match your country!', 'type' => 'callback', 'format' => 'checkCountryState', 'validation' => $this->_validationType, 'reset' => true, 'force' => false);
- $filters[] = array('element' => '__ALL__', 'filter' => 'trim');
+ $filters[] = array('element' => '__ALL__', 'filter' => 'trim');
- foreach ($elements as $e) {
- $source =& $this->addElement($e['type'], $e['name'], $e['display'], $e['opts'], $e['att'], $e['val']);
+ foreach ($elements as $e) {
+ $source =& $this->addElement($e['type'], $e['name'], $e['display'], $e['opts'], $e['att'], $e['val']);
- if ($e['name'] == 'dining') {
- $source->addColumnName('No. in Party');
- $source->addColumnName('Reservation Time');
- $source->addColumnName('Restaurant');
+ if ($e['name'] == 'dining') {
+ $source->addColumnName('No. in Party');
+ $source->addColumnName('Reservation Time');
+ $source->addColumnName('Restaurant');
- $date = gregoriantojd(
- $arrivalMonth,
- $arrivalDay,
- $arrivalYear
- );
+ $date = gregoriantojd(
+ $arrivalMonth,
+ $arrivalDay,
+ $arrivalYear
+ );
- $golfers = array('' => '-- Select --') + range(1, 20);
- for ($i = 0; $i <= $vacationLength; ++$i) {
- unset($dining);
+ $golfers = array('' => '-- Select --') + range(1, 20);
+ for ($i = 0; $i <= $vacationLength; ++$i) {
+ unset($dining);
- $calDate = cal_from_jd($date++, CAL_GREGORIAN);
+ $calDate = cal_from_jd($date++, CAL_GREGORIAN);
- $dining[] =& $this->createElement('select', "size$i", null, $golfers);
- $dining[] =& $this->createElement('select', "time$i", null, $reservationTime);
- $dining[] =& $this->createElement('select', "location$i", null, $locations);
+ $dining[] =& $this->createElement('select', "size$i", null, $golfers);
+ $dining[] =& $this->createElement('select', "time$i", null, $reservationTime);
+ $dining[] =& $this->createElement('select', "location$i", null, $locations);
- $source->addRow($dining, $calDate['date']);
- }
- }
- }
+ $source->addRow($dining, $calDate['date']);
+ }
+ }
+ }
$this->addGroup($prevnext, 'control_buttons', '', ' ', false);
- $this->formElements = $elements;
- $this->_setupRules($rules);
- $this->_setupFilters($filters);
+ $this->formElements = $elements;
+ $this->_setupRules($rules);
+ $this->_setupFilters($filters);
$this->setDefaultAction('next');
}
}
{
function _renderForm(&$page)
{
- $renderer =& $page->defaultRenderer();
-
-// $renderer->setFormTemplate('<table><form{attributes}>{content}</form></table>');
-// $renderer->setHeaderTemplate('<tr><td style="white-space:nowrap;background:#996;color:#ffc;" align="left" colspan="2"><b>{header}</b></td></tr>');
-// $renderer->setGroupTemplate('<table><tr>{content}</tr></table>', 'name');
-// $renderer->setGroupElementTemplate('<td>{element}<br /><span style="font-size:10px;"><!-- BEGIN required --><span style="color: #f00">*</span><!-- END required --><span style="color:#996;">{label}</span></span></td>', 'name');
- $renderer->setHeaderTemplate('<tr><td style="white-space:nowrap;background:#C3DBCD;color:#1A2D5A;" align="left" colspan="2"><b>{header}</b></td></tr>');
- $renderer->setElementTemplate('<td colspan="2"><br /><span><!-- BEGIN required --><span style="color: red">*</span><!-- END required --><span>{label}</span></span>{element}</td>', 'golfing');
- $renderer->setElementTemplate('<td colspan="2"><br /><span><!-- BEGIN required --><span style="color: red">*</span><!-- END required --><span>{label}</span></span>{element}</td>', 'dining');
- $renderer->setGroupElementTemplate('<td>{element}<br /><span style="font-size:10px;"><!-- BEGIN required --><span style="color: #f00">*</span><!-- END required --><span style="color:#996;">{label}</span></span></td>', 'golfing');
-
- $page->accept($renderer);
- return $renderer->toHtml();
+ $renderer =& $page->defaultRenderer();
+
+// $renderer->setFormTemplate('<table><form{attributes}>{content}</form></table>');
+// $renderer->setHeaderTemplate('<tr><td style="white-space:nowrap;background:#996;color:#ffc;" align="left" colspan="2"><b>{header}</b></td></tr>');
+// $renderer->setGroupTemplate('<table><tr>{content}</tr></table>', 'name');
+// $renderer->setGroupElementTemplate('<td>{element}<br /><span style="font-size:10px;"><!-- BEGIN required --><span style="color: #f00">*</span><!-- END required --><span style="color:#996;">{label}</span></span></td>', 'name');
+ $renderer->setHeaderTemplate('<tr><td style="white-space:nowrap;background:#C3DBCD;color:#1A2D5A;" align="left" colspan="2"><b>{header}</b></td></tr>');
+ $renderer->setElementTemplate('<td colspan="2"><br /><span><!-- BEGIN required --><span style="color: red">*</span><!-- END required --><span>{label}</span></span>{element}</td>', 'golfing');
+ $renderer->setElementTemplate('<td colspan="2"><br /><span><!-- BEGIN required --><span style="color: red">*</span><!-- END required --><span>{label}</span></span>{element}</td>', 'dining');
+ $renderer->setGroupElementTemplate('<td>{element}<br /><span style="font-size:10px;"><!-- BEGIN required --><span style="color: #f00">*</span><!-- END required --><span style="color:#996;">{label}</span></span></td>', 'golfing');
+
+ $page->accept($renderer);
+ return $renderer->toHtml();
}
}
{
function perform(&$page, $actionName)
{
- $return = $this->_getEntireForm($page);
- if ($this->_process($page, $return)) {
- $return = "<p>The information below was successfully submitted</p>\n<pre>\n{$return}\n</pre>\n";
- $return = "<p>Thank you for requesting a custom package price quote from Big Fore Golf.
- The lodging partner that you requested will receive your request and personally
- follow up with you to finalize any details of your selections, and return your
- package pricing and details.</p>\n{$return}\n";
- } else {
- $return = '<p>There was an error processing your request, if this problem persists please contact <a href="mail:'.OWNER_EMAIL.'">BigFore</a></p>';
- }
- return $return;
+ $return = $this->_getEntireForm($page);
+ if ($this->_process($page, $return)) {
+ $return = "<p>The information below was successfully submitted</p>\n<pre>\n{$return}\n</pre>\n";
+ $return = "<p>Thank you for requesting a custom package price quote from Big Fore Golf.
+ The lodging partner that you requested will receive your request and personally
+ follow up with you to finalize any details of your selections, and return your
+ package pricing and details.</p>\n{$return}\n";
+ } else {
+ $return = '<p>There was an error processing your request, if this problem persists please contact <a href="mail:'.OWNER_EMAIL.'">BigFore</a></p>';
+ }
+ return $return;
}
- private function _getEntireForm(&$page)
- {
- $values = $page->controller->exportValues();
+ private function _getEntireForm(&$page)
+ {
+ $values = $page->controller->exportValues();
// $return .= print_r($values, true);
- unset($temp);
- unset($renderer);
- $rmvElements = array(
- 'control_buttons',
- 'tos_rmv',
- 'view_courses_rmv',
- 'header_rmv',
- 'cust_info_rmv',
- 'accomodation_rmv',
- );
- for ($i = 1; $i < 4; ++$i) {
- $temp =& $page->controller->getPage("page$i");
- $back = $temp->getButtonName('back');
- $next = $temp->getButtonName('next');
- $temp->buildForm();
-// $return .= print_r($temp, true);
- if ($temp->elementExists($back)) {
- $temp->removeElement($back);
- }
- if ($temp->elementExists($next)) {
- $temp->removeElement($next);
- }
- foreach ($rmvElements as $e) {
- if ($temp->elementExists($e)) {
- $temp->removeElement($e);
- }
- }
- $temp->loadValues($values);
- $temp->freeze();
- $renderer =& $temp->defaultRenderer();
- $style = "border: 1px solid #eee; border-collapse: collapse; color: #000; font-family: arial, helvetica, sans-serif; padding: 3px;";
-
- $renderer->setHeaderTemplate('<tr><td style="white-space:nowrap;background:#C3DBCD;color:#1A2D5A;" align="left" colspan="2"><b>{header}</b></td></tr>');
-// $renderer->setElementTemplate('<td colspan="2" style="'.$style.'"><br /><span><!-- BEGIN required --><span style="color: red">*</span><!-- END required --><span>{label}</span></span>{element}</td>');
-// $renderer->setElementTemplate("\n\t<tr>\n\t\t<td style=\"$style\" valign=\"top\"><!-- BEGIN required --><span style=\"color: #ff0000\">*</span><!-- END required --><b>{label}</b></td>\n\t\t<td valign=\"top\" align=\"left\"><!-- BEGIN error --><span style=\"color: #ff0000\">{error}</span><br /><!-- END error -->\t{element}</td>\n\t</tr>");
- $renderer->setElementTemplate('<td colspan="2"><br /><span><!-- BEGIN required --><span style="color: red">*</span><!-- END required --><span>{label}</span></span>{element}</td>', 'golfing');
- $renderer->setElementTemplate('<td colspan="2"><br /><span><!-- BEGIN required --><span style="color: red">*</span><!-- END required --><span>{label}</span></span>{element}</td>', 'dining');
- $renderer->setGroupElementTemplate('<td>{element}<br /><span style="font-size:10px;"><!-- BEGIN required --><span style="color: #f00">*</span><!-- END required --><span style="color:#996;">{label}</span></span></td>', 'golfing');
-
- $temp->accept($renderer);
- $return .= $temp->toHtml();
- }
- foreach ($rmvElements as $e) {
- if ($page->elementExists($e)) {
- $page->removeElement($e);
- }
- }
- $renderer =& $page->defaultRenderer();
-
- $renderer->setHeaderTemplate('<tr><td style="white-space:nowrap;background:#C3DBCD;color:#1A2D5A;" align="left" colspan="2"><b>{header}</b></td></tr>');
- $renderer->setElementTemplate('<td colspan="2"><br /><span><!-- BEGIN required --><span style="color: red">*</span><!-- END required --><span>{label}</span></span>{element}</td>', 'golfing');
- $renderer->setElementTemplate('<td colspan="2"><br /><span><!-- BEGIN required --><span style="color: red">*</span><!-- END required --><span>{label}</span></span>{element}</td>', 'dining');
- $renderer->setGroupElementTemplate('<td>{element}<br /><span style="font-size:10px;"><!-- BEGIN required --><span style="color: #f00">*</span><!-- END required --><span style="color:#996;">{label}</span></span></td>', 'golfing');
-
- $page->accept($renderer);
- $page->freeze();
- $return .= $page->toHtml();
-
- return $return;
- }
-
- private function _process(&$page, $email)
- {
- $values = $page->controller->exportValues();
- try {
- $dbh = Toolkit_Database::getInstance();
- $dbh->beginTransaction();
- $sql = "
+ unset($temp);
+ unset($renderer);
+ $rmvElements = array(
+ 'control_buttons',
+ 'tos_rmv',
+ 'view_courses_rmv',
+ 'header_rmv',
+ 'cust_info_rmv',
+ 'accomodation_rmv',
+ );
+ for ($i = 1; $i < 4; ++$i) {
+ $temp =& $page->controller->getPage("page$i");
+ $back = $temp->getButtonName('back');
+ $next = $temp->getButtonName('next');
+ $temp->buildForm();
+// $return .= print_r($temp, true);
+ if ($temp->elementExists($back)) {
+ $temp->removeElement($back);
+ }
+ if ($temp->elementExists($next)) {
+ $temp->removeElement($next);
+ }
+ foreach ($rmvElements as $e) {
+ if ($temp->elementExists($e)) {
+ $temp->removeElement($e);
+ }
+ }
+ $temp->loadValues($values);
+ $temp->freeze();
+ $renderer =& $temp->defaultRenderer();
+ $style = "border: 1px solid #eee; border-collapse: collapse; color: #000; font-family: arial, helvetica, sans-serif; padding: 3px;";
+
+ $renderer->setHeaderTemplate('<tr><td style="white-space:nowrap;background:#C3DBCD;color:#1A2D5A;" align="left" colspan="2"><b>{header}</b></td></tr>');
+// $renderer->setElementTemplate('<td colspan="2" style="'.$style.'"><br /><span><!-- BEGIN required --><span style="color: red">*</span><!-- END required --><span>{label}</span></span>{element}</td>');
+// $renderer->setElementTemplate("\n\t<tr>\n\t\t<td style=\"$style\" valign=\"top\"><!-- BEGIN required --><span style=\"color: #ff0000\">*</span><!-- END required --><b>{label}</b></td>\n\t\t<td valign=\"top\" align=\"left\"><!-- BEGIN error --><span style=\"color: #ff0000\">{error}</span><br /><!-- END error -->\t{element}</td>\n\t</tr>");
+ $renderer->setElementTemplate('<td colspan="2"><br /><span><!-- BEGIN required --><span style="color: red">*</span><!-- END required --><span>{label}</span></span>{element}</td>', 'golfing');
+ $renderer->setElementTemplate('<td colspan="2"><br /><span><!-- BEGIN required --><span style="color: red">*</span><!-- END required --><span>{label}</span></span>{element}</td>', 'dining');
+ $renderer->setGroupElementTemplate('<td>{element}<br /><span style="font-size:10px;"><!-- BEGIN required --><span style="color: #f00">*</span><!-- END required --><span style="color:#996;">{label}</span></span></td>', 'golfing');
+
+ $temp->accept($renderer);
+ $return .= $temp->toHtml();
+ }
+ foreach ($rmvElements as $e) {
+ if ($page->elementExists($e)) {
+ $page->removeElement($e);
+ }
+ }
+ $renderer =& $page->defaultRenderer();
+
+ $renderer->setHeaderTemplate('<tr><td style="white-space:nowrap;background:#C3DBCD;color:#1A2D5A;" align="left" colspan="2"><b>{header}</b></td></tr>');
+ $renderer->setElementTemplate('<td colspan="2"><br /><span><!-- BEGIN required --><span style="color: red">*</span><!-- END required --><span>{label}</span></span>{element}</td>', 'golfing');
+ $renderer->setElementTemplate('<td colspan="2"><br /><span><!-- BEGIN required --><span style="color: red">*</span><!-- END required --><span>{label}</span></span>{element}</td>', 'dining');
+ $renderer->setGroupElementTemplate('<td>{element}<br /><span style="font-size:10px;"><!-- BEGIN required --><span style="color: #f00">*</span><!-- END required --><span style="color:#996;">{label}</span></span></td>', 'golfing');
+
+ $page->accept($renderer);
+ $page->freeze();
+ $return .= $page->toHtml();
+
+ return $return;
+ }
+
+ private function _process(&$page, $email)
+ {
+ $values = $page->controller->exportValues();
+ try {
+ $dbh = Toolkit_Database::getInstance();
+ $dbh->beginTransaction();
+ $sql = "
SELECT *
FROM contact
WHERE email = :email";
- $stmt = $dbh->prepare($sql);
- $stmt->bindParam(':email', $values['email'], PDO::PARAM_STR);
- $stmt->execute();
- $contact = $stmt->fetch(PDO::FETCH_ASSOC);
-
- if ($contact === false) {
- $sql = "
- INSERT INTO contact(pquote_create_date, fname, lname, address, city, state, zip, phone, alt_phone, email, mail_ok, arrival, departure, golfers, nongolfers,
- lodging, couples, singles, bathrooms, rooms, beds, twinok, sleepersofaok, comments, discover, partysize, pquote)
- VALUES (now(), :fname, :lname, :addy, :city, :state, :zip, :phone, :altphone, :email, true, :arrival, :departure, :golfers, :nongolfers, :lodging,
- :couples, :singles, :brooms, :rooms, :beds, :twinok, :sofaok, :comments, :discover, :partysize, true)";
- } else {
- $sql = "
+ $stmt = $dbh->prepare($sql);
+ $stmt->bindParam(':email', $values['email'], PDO::PARAM_STR);
+ $stmt->execute();
+ $contact = $stmt->fetch(PDO::FETCH_ASSOC);
+
+ if ($contact === false) {
+ $sql = "
+ INSERT INTO contact(pquote_create_date, fname, lname, address, city, state, zip, phone, alt_phone, email, mail_ok, arrival, departure, golfers, nongolfers,
+ lodging, couples, singles, bathrooms, rooms, beds, twinok, sleepersofaok, comments, discover, partysize, pquote)
+ VALUES (now(), :fname, :lname, :addy, :city, :state, :zip, :phone, :altphone, :email, true, :arrival, :departure, :golfers, :nongolfers, :lodging,
+ :couples, :singles, :brooms, :rooms, :beds, :twinok, :sofaok, :comments, :discover, :partysize, true)";
+ } else {
+ $sql = "
UPDATE contact
- SET pquote_create_date = now(),
- fname = :fname,
- lname = :lname,
- address = :addy,
- city = :city,
- state = :state,
- zip = :zip,
- phone = :phone,
- alt_phone = :altphone,
- email = :email,
- mail_ok = true,
- arrival = :arrival,
- departure = :departure,
- golfers = :golfers,
- nongolfers = :nongolfers,
- lodging = :lodging,
- couples = :couples,
- singles = :singles,
- bathrooms = :brooms,
- rooms = :rooms,
- beds = :beds,
- twinok = :twinok,
- sleepersofaok = :sofaok,
- comments = :comments,
- discover = :discover,
- partysize = :partysize,
- pquote= true
+ SET pquote_create_date = now(),
+ fname = :fname,
+ lname = :lname,
+ address = :addy,
+ city = :city,
+ state = :state,
+ zip = :zip,
+ phone = :phone,
+ alt_phone = :altphone,
+ email = :email,
+ mail_ok = true,
+ arrival = :arrival,
+ departure = :departure,
+ golfers = :golfers,
+ nongolfers = :nongolfers,
+ lodging = :lodging,
+ couples = :couples,
+ singles = :singles,
+ bathrooms = :brooms,
+ rooms = :rooms,
+ beds = :beds,
+ twinok = :twinok,
+ sleepersofaok = :sofaok,
+ comments = :comments,
+ discover = :discover,
+ partysize = :partysize,
+ pquote= true
WHERE email = :email";
- }
-
- $arrival = "{$values['arrival']['Y']}-{$values['arrival']['m']}-{$values['arrival']['d']}";
- $departure = "{$values['departure']['Y']}-{$values['departure']['m']}-{$values['departure']['d']}";
- $twin = ($values['twin'] == 'No') ? false : true;
- $sofa = ($values['sleeper'] == 'No') ? false : true;
- $partySize = ($values['golfers'] + $values['nongolfers']);
- $stmt = $dbh->prepare($sql);
- $stmt->bindParam(':fname', $values['fname'], PDO::PARAM_STR);
- $stmt->bindParam(':lname', $values['lname'], PDO::PARAM_STR);
- $stmt->bindParam(':addy', $values['address'], PDO::PARAM_STR);
- $stmt->bindParam(':city', $values['city'], PDO::PARAM_STR);
- $stmt->bindParam(':state', $values['state'], PDO::PARAM_STR);
- $stmt->bindParam(':zip', $values['zip'], PDO::PARAM_STR);
- $stmt->bindParam(':phone', $values['phone'], PDO::PARAM_STR);
- $stmt->bindParam(':altphone', $values['alt_phone'], PDO::PARAM_STR);
- $stmt->bindParam(':email', $values['email'], PDO::PARAM_STR);
- $stmt->bindParam(':arrival', $arrival, PDO::PARAM_STR);
- $stmt->bindParam(':departure', $departure, PDO::PARAM_STR);
- $stmt->bindParam(':golfers', $values['golfers'], PDO::PARAM_INT);
- $stmt->bindParam(':nongolfers', $values['nongolfers'], PDO::PARAM_INT);
- $stmt->bindParam(':lodging', $values['lodging'], PDO::PARAM_STR);
- $stmt->bindParam(':couples', $values['couples'], PDO::PARAM_INT);
- $stmt->bindParam(':singles', $values['singles'], PDO::PARAM_INT);
- $stmt->bindParam(':brooms', $values['bathrooms'], PDO::PARAM_INT);
- $stmt->bindParam(':rooms', $values['rooms'], PDO::PARAM_INT);
- $stmt->bindParam(':beds', $values['beds'], PDO::PARAM_INT);
- $stmt->bindParam(':twinok', $twin, PDO::PARAM_BOOL);
- $stmt->bindParam(':sofaok', $sofa, PDO::PARAM_BOOL);
- $stmt->bindParam(':comments', $values['comments'], PDO::PARAM_STR);
- $stmt->bindParam(':discover', $values['discovery'], PDO::PARAM_STR);
- $stmt->bindParam(':partysize', $partySize, PDO::PARAM_INT);
- $stmt->execute();
-
- if ($contact === false) {
- $sql = "
- SELECT id
- FROM contact
- ORDER BY id DESC LIMIT 1";
- $stmt = $dbh->prepare($sql);
- $stmt->execute();
- $contact = $stmt->fetch(PDO::FETCH_ASSOC);
- }
-
- $vacationLength = date_difference(
- $values['arrival']['m'],
- $values['arrival']['d'],
- $values['arrival']['Y'],
- $values['departure']['m'],
- $values['departure']['d'],
- $values['departure']['Y']
- );
-
- $golfingDate = $diningDate = gregoriantojd(
- $values['arrival']['m'],
- $values['arrival']['d'],
- $values['arrival']['Y']
- );
- $sql = "
- INSERT INTO golfing_preference (contact_id, date, golfers, teetime, course)
- VALUES (:cid, :date, :golfers, :teetime, :course)";
-
- $stmt = $dbh->prepare($sql);
- $stmt->bindParam(':cid', $contact['id'], PDO::PARAM_INT);
- // Add all the golfing trips the user scheduled
- for ($i = 0; $i <= $vacationLength; ++$i) {
- $calDate = cal_from_jd($golfingDate++, CAL_GREGORIAN);
- // Only add the trip into the DB if the user has selected a course.
- if (!empty($values["amCourse$i"]) && !empty($values["amGolfers$i"])) {
- $stmt->bindParam(':date', $calDate['date'], PDO::PARAM_STR);
- $stmt->bindParam(':golfers', $values["amGolfers$i"], PDO::PARAM_INT);
- $stmt->bindParam(':teetime', $values["amTeeTime$i"], PDO::PARAM_STR);
- $stmt->bindParam(':course', $values["amCourse$i"], PDO::PARAM_STR);
- $stmt->execute();
- }
- if (!empty($values["pmCourse$i"]) && !empty($values["pmGolfers$i"])) {
- $stmt->bindParam(':date', $calDate['date'], PDO::PARAM_STR);
- $stmt->bindParam(':golfers', $values["pmGolfers$i"], PDO::PARAM_INT);
- $stmt->bindParam(':teetime', $values["pmTeeTime$i"], PDO::PARAM_STR);
- $stmt->bindParam(':course', $values["pmCourse$i"], PDO::PARAM_STR);
- $stmt->execute();
- }
- }
-
-// $sql = "
-// insert into dining_preference(contact_id, size, time, restaurant, date)
-// values (:cid, :size, :time, :res, :date)";
-// $stmt = $dbh->prepare($sql);
-// $stmt->bindParam(':cid', $contact['id'], PDO::PARAM_INT);
-// // Add all the dining reservations the user scheduled
-// for ($i = 0; $i <= $vacationLength; ++$i) {
-// $calDate = cal_from_jd($diningDate++, CAL_GREGORIAN);
-// // Only add the reservation if the user changed the party size.
-// if (!empty($values["size$i"])) {
-// $stmt->bindParam(':size', $values["size$i"], PDO::PARAM_INT);
-// $stmt->bindParam(':time', $values["time$i"], PDO::PARAM_INT);
-// $stmt->bindParam(':res', $values["location$i"], PDO::PARAM_INT);
-// $stmt->bindParam(':date', $calDate['date'], PDO::PARAM_INT);
-// $stmt->execute();
-// }
-// }
-
- $dbh->commit();
-
- if ($values['lodging'] === 'Trout Creek Condominiums') {
- $toEmail = TROUT_CREEK_EMAILS;
- } else {
+ }
+
+ $arrival = "{$values['arrival']['Y']}-{$values['arrival']['m']}-{$values['arrival']['d']}";
+ $departure = "{$values['departure']['Y']}-{$values['departure']['m']}-{$values['departure']['d']}";
+ $twin = ($values['twin'] == 'No') ? false : true;
+ $sofa = ($values['sleeper'] == 'No') ? false : true;
+ $partySize = ($values['golfers'] + $values['nongolfers']);
+ $stmt = $dbh->prepare($sql);
+ $stmt->bindParam(':fname', $values['fname'], PDO::PARAM_STR);
+ $stmt->bindParam(':lname', $values['lname'], PDO::PARAM_STR);
+ $stmt->bindParam(':addy', $values['address'], PDO::PARAM_STR);
+ $stmt->bindParam(':city', $values['city'], PDO::PARAM_STR);
+ $stmt->bindParam(':state', $values['state'], PDO::PARAM_STR);
+ $stmt->bindParam(':zip', $values['zip'], PDO::PARAM_STR);
+ $stmt->bindParam(':phone', $values['phone'], PDO::PARAM_STR);
+ $stmt->bindParam(':altphone', $values['alt_phone'], PDO::PARAM_STR);
+ $stmt->bindParam(':email', $values['email'], PDO::PARAM_STR);
+ $stmt->bindParam(':arrival', $arrival, PDO::PARAM_STR);
+ $stmt->bindParam(':departure', $departure, PDO::PARAM_STR);
+ $stmt->bindParam(':golfers', $values['golfers'], PDO::PARAM_INT);
+ $stmt->bindParam(':nongolfers', $values['nongolfers'], PDO::PARAM_INT);
+ $stmt->bindParam(':lodging', $values['lodging'], PDO::PARAM_STR);
+ $stmt->bindParam(':couples', $values['couples'], PDO::PARAM_INT);
+ $stmt->bindParam(':singles', $values['singles'], PDO::PARAM_INT);
+ $stmt->bindParam(':brooms', $values['bathrooms'], PDO::PARAM_INT);
+ $stmt->bindParam(':rooms', $values['rooms'], PDO::PARAM_INT);
+ $stmt->bindParam(':beds', $values['beds'], PDO::PARAM_INT);
+ $stmt->bindParam(':twinok', $twin, PDO::PARAM_BOOL);
+ $stmt->bindParam(':sofaok', $sofa, PDO::PARAM_BOOL);
+ $stmt->bindParam(':comments', $values['comments'], PDO::PARAM_STR);
+ $stmt->bindParam(':discover', $values['discovery'], PDO::PARAM_STR);
+ $stmt->bindParam(':partysize', $partySize, PDO::PARAM_INT);
+ $stmt->execute();
+
+ if ($contact === false) {
+ $sql = "
+ SELECT id
+ FROM contact
+ ORDER BY id DESC LIMIT 1";
+ $stmt = $dbh->prepare($sql);
+ $stmt->execute();
+ $contact = $stmt->fetch(PDO::FETCH_ASSOC);
+ }
+
+ $vacationLength = date_difference(
+ $values['arrival']['m'],
+ $values['arrival']['d'],
+ $values['arrival']['Y'],
+ $values['departure']['m'],
+ $values['departure']['d'],
+ $values['departure']['Y']
+ );
+
+ $golfingDate = $diningDate = gregoriantojd(
+ $values['arrival']['m'],
+ $values['arrival']['d'],
+ $values['arrival']['Y']
+ );
+ $sql = "
+ INSERT INTO golfing_preference (contact_id, date, golfers, teetime, course)
+ VALUES (:cid, :date, :golfers, :teetime, :course)";
+
+ $stmt = $dbh->prepare($sql);
+ $stmt->bindParam(':cid', $contact['id'], PDO::PARAM_INT);
+ // Add all the golfing trips the user scheduled
+ for ($i = 0; $i <= $vacationLength; ++$i) {
+ $calDate = cal_from_jd($golfingDate++, CAL_GREGORIAN);
+ // Only add the trip into the DB if the user has selected a course.
+ if (!empty($values["amCourse$i"]) && !empty($values["amGolfers$i"])) {
+ $stmt->bindParam(':date', $calDate['date'], PDO::PARAM_STR);
+ $stmt->bindParam(':golfers', $values["amGolfers$i"], PDO::PARAM_INT);
+ $stmt->bindParam(':teetime', $values["amTeeTime$i"], PDO::PARAM_STR);
+ $stmt->bindParam(':course', $values["amCourse$i"], PDO::PARAM_STR);
+ $stmt->execute();
+ }
+ if (!empty($values["pmCourse$i"]) && !empty($values["pmGolfers$i"])) {
+ $stmt->bindParam(':date', $calDate['date'], PDO::PARAM_STR);
+ $stmt->bindParam(':golfers', $values["pmGolfers$i"], PDO::PARAM_INT);
+ $stmt->bindParam(':teetime', $values["pmTeeTime$i"], PDO::PARAM_STR);
+ $stmt->bindParam(':course', $values["pmCourse$i"], PDO::PARAM_STR);
+ $stmt->execute();
+ }
+ }
+
+// $sql = "
+// insert into dining_preference(contact_id, size, time, restaurant, date)
+// values (:cid, :size, :time, :res, :date)";
+// $stmt = $dbh->prepare($sql);
+// $stmt->bindParam(':cid', $contact['id'], PDO::PARAM_INT);
+// // Add all the dining reservations the user scheduled
+// for ($i = 0; $i <= $vacationLength; ++$i) {
+// $calDate = cal_from_jd($diningDate++, CAL_GREGORIAN);
+// // Only add the reservation if the user changed the party size.
+// if (!empty($values["size$i"])) {
+// $stmt->bindParam(':size', $values["size$i"], PDO::PARAM_INT);
+// $stmt->bindParam(':time', $values["time$i"], PDO::PARAM_INT);
+// $stmt->bindParam(':res', $values["location$i"], PDO::PARAM_INT);
+// $stmt->bindParam(':date', $calDate['date'], PDO::PARAM_INT);
+// $stmt->execute();
+// }
+// }
+
+ $dbh->commit();
+
+ if ($values['lodging'] === 'Trout Creek Condominiums') {
+ $toEmail = TROUT_CREEK_EMAILS;
+ } else {
$toEmail = HAMLET_VILLAGE_EMAILS;
}
- require_once 'Mail.php';
- require_once 'Mail/mime.php';
-
- $msg = "<html><body>{$email}</body></html>";
- $crlf = "\n";
- $mimeMail = new Mail_mime($crlf);
- $mimeMail->setFrom(SITENAME . '<' . OWNER_EMAIL . '>');
- $mimeMail->addBcc('jodie@gaslightmedia.com');
- //$mimeMail->addBcc('veilig2000@gmail.com');
- $mimeMail->setSubject(SITENAME . ' Price Quote Request Form');
- $mimeMail->setHTMLBody($msg);
-
- $mail =& Mail::factory('mail');
- $body = $mimeMail->get();
- $headers = $mimeMail->headers();
-
- $mail->send($toEmail, $headers, $body);
- unset($dbh);
- unset($stmt);
- unset($mimeMail);
- unset($mail);
- return true;
- } catch (PDOException $e) {
- $dbh->rollBack();
- unset($dbh);
- unset($stmt);
- echo 'PDO Exception Caught. ';
- echo 'Error with the database:<br>';
- echo 'Error: ' . $e->getMessage() . '<br>';
- echo 'File: ' . $e->getFile() . '<br>';
- echo 'Line: ' . $e->getLine() . '<br>';
-// echo 'PDO::errorInfo(): <pre>' . print_r($dbh->errorInfo(), true) . '</pre><br>';
-// echo 'TraceAsString: <pre>' . print_r($e->getTrace(), true) . '</pre><br>';
- return false;
- }
- return false;
- }
+ require_once 'Mail.php';
+ require_once 'Mail/mime.php';
+
+ $msg = "<html><body>{$email}</body></html>";
+ $crlf = "\n";
+ $mimeMail = new Mail_mime($crlf);
+ $mimeMail->setFrom(SITENAME . '<' . OWNER_EMAIL . '>');
+ $mimeMail->addBcc('jodie@gaslightmedia.com');
+ //$mimeMail->addBcc('veilig2000@gmail.com');
+ $mimeMail->setSubject(SITENAME . ' Price Quote Request Form');
+ $mimeMail->setHTMLBody($msg);
+
+ $mail =& Mail::factory('mail');
+ $body = $mimeMail->get();
+ $headers = $mimeMail->headers();
+
+ $mail->send($toEmail, $headers, $body);
+ unset($dbh);
+ unset($stmt);
+ unset($mimeMail);
+ unset($mail);
+ return true;
+ } catch (PDOException $e) {
+ $dbh->rollBack();
+ unset($dbh);
+ unset($stmt);
+ echo 'PDO Exception Caught. ';
+ echo 'Error with the database:<br>';
+ echo 'Error: ' . $e->getMessage() . '<br>';
+ echo 'File: ' . $e->getFile() . '<br>';
+ echo 'Line: ' . $e->getLine() . '<br>';
+// echo 'PDO::errorInfo(): <pre>' . print_r($dbh->errorInfo(), true) . '</pre><br>';
+// echo 'TraceAsString: <pre>' . print_r($e->getTrace(), true) . '</pre><br>';
+ return false;
+ }
+ return false;
+ }
}
$wizard = new HTML_QuickForm_Controller('spacey');
$wizard->addPage(new PageFourth('page4'));
$wizard->addAction('display', new ActionDisplay());
-$wizard->addAction('process', new ActionProcess());
\ No newline at end of file
+$wizard->addAction('process', new ActionProcess());
// colons (:), or periods (.)
$path = preg_split('(\/|:|\.)', get_include_path());
$catid = filter_var($_REQUEST['catid'], FILTER_VALIDATE_INT);
-if ($catid == ORDER_FORM_PAGE && !in_array(BASE . 'glmPEAR', $path)) {
- set_include_path(
- BASE . 'glmPEAR' . PATH_SEPARATOR . get_include_path()
- );
-} else if (!in_array(GLM_APP_BASE . 'glmPEAR', $path)) {
+if (!in_array(GLM_APP_BASE . 'glmPEAR', $path)) {
set_include_path(
GLM_APP_BASE . 'glmPEAR' . PATH_SEPARATOR . get_include_path()
);
/**
* The email address to send banner expiration notices to
*/
-//define('EXPIRING_BANNER_NOTIFICATION_EMAIL', $serverConfig->email->expiring->banner_notification);
- die('test');
+define('EXPIRING_BANNER_NOTIFICATION_EMAIL', $serverConfig->email->expiring_banner_notification);
/**
* Authorize.net processing parameters
* ALSO SEE "Authorize.Net Configuration" SECTION BELOW CONDITIONAL SETTINGS